예제 #1
0
파일: JobsTask.cs 프로젝트: yeco96/FE
        private void decodeXML()
        {
            using (var conexion = new DataModelFE())
            {
                List <WSRecepcionPOST> lista = conexion.WSRecepcionPOST.
                                               Where(x => x.comprobanteXml.Substring(0, 3) == "PD9").ToList();
                foreach (var item in lista)
                {
                    WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(item.clave);
                    if (dato.comprobanteXml != null)
                    {
                        dato.comprobanteXml = XMLUtils.base64Decode(dato.comprobanteXml);
                    }
                    if (dato.comprobanteRespXML != null)
                    {
                        if (dato.comprobanteRespXML.Substring(0, 3) == "PD9")
                        {
                            dato.comprobanteRespXML = XMLUtils.base64Decode(dato.comprobanteRespXML);
                        }
                    }

                    conexion.Entry(dato).State = EntityState.Modified;
                    conexion.SaveChanges();
                }
            }
        }
        protected void btnDescargarXML_Click(object sender, EventArgs e)
        {
            try
            {
                string xml = "";

                using (var conexion = new DataModelFE())
                {
                    string          clave = Session["clave"].ToString();
                    WSRecepcionPOST dato  = conexion.WSRecepcionPOST.Where(x => x.clave == clave).FirstOrDefault();
                    xml = dato.comprobanteXml;
                }
                Response.Clear();
                Response.ClearHeaders();

                Response.AddHeader("Content-Length", xml.Length.ToString());
                Response.ContentType = "application/xml";
                Response.AppendHeader("content-disposition", String.Format("attachment;filename=\"{0}.xml\"", Session["clave"].ToString()));

                Response.Write(xml);
                Response.End();
            }
            catch (Exception ex)
            {
                this.alertMessages.Attributes["class"] = "alert alert-danger";
                this.alertMessages.InnerText           = Utilidades.validarExepcionSQL(ex);
            }
        }
예제 #3
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);
        }
        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);
            }
        }
예제 #5
0
        protected async void btnEnviar_Click(object sender, EventArgs e)
        {
            try
            {
                using (var conexion = new DataModelFE())
                {
                    EmisorReceptorIMEC  emisor   = (EmisorReceptorIMEC)Session["elEmisor"];
                    string              ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                    OAuth2.OAuth2Config config   = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                    config.username = emisor.usernameOAuth2;
                    config.password = emisor.passwordOAuth2;

                    await OAuth2.OAuth2Config.getTokenWeb(config);

                    string xmlFile = Session["xmlFile"].ToString();
                    WSDomain.WSRecepcionPOST trama = new WSDomain.WSRecepcionPOST();
                    trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile);

                    string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlFile);
                    trama.emisor.tipoIdentificacion   = emisorIdentificacion.Substring(0, 2);
                    trama.emisor.numeroIdentificacion = emisorIdentificacion.Substring(2);
                    trama.emisorTipo           = trama.emisor.tipoIdentificacion;
                    trama.emisorIdentificacion = trama.emisor.numeroIdentificacion;

                    string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlFile);
                    trama.receptor.tipoIdentificacion   = receptorIdentificacion.Substring(0, 2);
                    trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2);
                    trama.receptorTipo           = trama.receptor.tipoIdentificacion;
                    trama.receptorIdentificacion = trama.receptor.numeroIdentificacion;

                    trama.comprobanteXml = EncodeXML.XMLUtils.base64Encode(xmlFile);

                    string jsonTrama = JsonConvert.SerializeObject(trama);

                    using (var conexion2 = new DataModelFE())
                    {
                        WSRecepcionPOST tramaObjeto = JsonConvert.DeserializeObject <WSRecepcionPOST>(jsonTrama);
                        conexion2.WSRecepcionPOST.Add(tramaObjeto);
                        conexion2.SaveChanges();
                    }

                    string responsePost = await Services.postRecepcion(config.token, jsonTrama);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
        }
예제 #6
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);
        }
예제 #7
0
        /// <summary>
        /// envia documento a hacienda, requiere de una factura en xml y firmada , codebase64
        /// </summary>
        public static void enviarDocumento(OAuth2Token token)
        {
            WSRecepcionPOST post = new WSRecepcionPOST();

            post.clave = "50613021800060354097400100002010000000003188888888";
            post.emisor.tipoIdentificacion     = "01";
            post.emisor.numeroIdentificacion   = "603540974";
            post.receptor.tipoIdentificacion   = "01";
            post.receptor.numeroIdentificacion = "601230863";

            FacturaElectronica fact = new FacturaElectronica();

            fact.iniciarParametros();

            string path = Path.Combine(Path.GetFullPath("fact.xml"));

            string xmlData = File.ReadAllText(path);
            //string xmlData = XMLUtilsgetXMLFromObject(fact);

            //XMLUtilsvalidadXMLXSD(xmlData);

            string xmlDataSigned = FirmaXML.getXMLFirmado(xmlData);



            // guarda xml firmado para pruebas
            File.WriteAllText(Path.GetFullPath("fact_firma.xml"), xmlDataSigned);

            post.comprobanteXml = EncodeXML.XMLUtils.base64Encode(xmlDataSigned);

            string jsonTrama = JsonConvert.SerializeObject(post);

            string responsePost = postRecepcion(token, jsonTrama)
                                  .GetAwaiter()
                                  .GetResult();
        }
예제 #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="tieneFirma">determina si el XML esta firmado o no</param>
        /// <param name="documento">puede ser cualquer tipo de documento electronico</param>
        /// <param name="responsePost">respuesta del webs ervices</param>
        /// <param name="tipoDocumento">Facura, Nota Crédito, Nota Débito</param>
        public static async Task <string> enviarDocumentoElectronico(bool tieneFirma, DocumentoElectronico documentoElectronico, EmisorReceptorIMEC emisor, string tipoDocumento, string usuario)
        {
            String responsePost = "";

            try
            {
                string xmlFile = EncodeXML.XMLUtils.getXMLFromObject(documentoElectronico);

                using (var conexion = new DataModelFE())
                {
                    string ambiente            = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                    OAuth2.OAuth2Config config = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                    config.username = emisor.usernameOAuth2;
                    config.password = emisor.passwordOAuth2;

                    await OAuth2.OAuth2Config.getTokenWeb(config);

                    WSDomain.WSRecepcionPOST trama = new WSDomain.WSRecepcionPOST();
                    trama.clave = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "Clave", xmlFile);
                    trama.fecha = DateTime.ParseExact(XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xmlFile), "FechaEmision", xmlFile), "yyyy-MM-ddTHH:mm:ss-06:00",
                                                      System.Globalization.CultureInfo.InvariantCulture);


                    string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlFile);
                    trama.emisor.tipoIdentificacion   = emisorIdentificacion.Substring(0, 2);
                    trama.emisor.numeroIdentificacion = emisorIdentificacion.Substring(2);
                    trama.emisorTipo           = trama.emisor.tipoIdentificacion;
                    trama.emisorIdentificacion = trama.emisor.numeroIdentificacion;

                    string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlFile);

                    if (!string.IsNullOrWhiteSpace(receptorIdentificacion))
                    {
                        trama.receptor.tipoIdentificacion   = receptorIdentificacion.Substring(0, 2);
                        trama.receptor.numeroIdentificacion = receptorIdentificacion.Substring(2);
                    }
                    else
                    {
                        trama.receptor.tipoIdentificacion   = "99";
                        trama.receptor.numeroIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "IdentificacionExtranjero", xmlFile);
                    }

                    trama.receptorTipo           = trama.receptor.tipoIdentificacion;
                    trama.receptorIdentificacion = trama.receptor.numeroIdentificacion;
                    trama.tipoDocumento          = tipoDocumento;

                    //trama.callbackUrl = ConfigurationManager.AppSettings["ENVIROMENT_URL"].ToString();

                    if (!tieneFirma)
                    {
                        xmlFile = FirmaXML.getXMLFirmadoWeb(xmlFile, emisor.llaveCriptografica, emisor.claveLlaveCriptografica.ToString());
                    }
                    trama.consecutivoReceptor = null;
                    // SE CODIFICA ENVIO HACIENDA
                    trama.comprobanteXml = XMLUtils.base64Encode(xmlFile);

                    string jsonTrama = JsonConvert.SerializeObject(trama);

                    if (config.token.access_token != null)
                    {
                        responsePost = await Services.postRecepcion(config.token, jsonTrama);
                    }
                    else
                    {
                        // facturar guardada para envio en linea
                        trama.indEstado = 9;
                    }
                    // SE DECODIFICA PARA GUARDAR A BASE DE DATOS
                    trama.comprobanteXml = xmlFile;

                    WSRecepcionPOST tramaExiste = conexion.WSRecepcionPOST.Find(trama.clave);
                    documentoElectronico.resumenFactura.clave = documentoElectronico.clave;
                    trama.cargarEmisorReceptor();

                    if (tramaExiste != null)
                    {// si existe
                        trama.fechaModificacion           = Date.DateTimeNow();
                        trama.usuarioModificacion         = usuario;
                        trama.indEstado                   = 0;
                        conexion.Entry(tramaExiste).State = EntityState.Modified;

                        conexion.Entry(documentoElectronico.resumenFactura).State = EntityState.Modified;
                    }
                    else//si no existe
                    {
                        trama.fechaCreacion   = Date.DateTimeNow();
                        trama.usuarioCreacion = usuario;
                        conexion.WSRecepcionPOST.Add(trama);

                        conexion.ResumenFactura.Add(documentoElectronico.resumenFactura);

                        Plan plan = conexion.Plan.Find(emisor.identificacion);
                        if (plan != null)
                        {
                            plan.cantidadDocEmitido   += 1;
                            conexion.Entry(plan).State = EntityState.Modified;
                        }
                    }
                    conexion.SaveChanges();

                    //guarda la relacion de clientes asociados al emisor
                    Cliente cliente = conexion.Cliente.Where(x => x.emisor == trama.emisor.numeroIdentificacion).Where(x => x.receptor == trama.receptor.numeroIdentificacion).FirstOrDefault();
                    if (cliente == null && !string.IsNullOrWhiteSpace(trama.receptor.numeroIdentificacion))
                    {
                        cliente          = new Cliente();
                        cliente.emisor   = trama.emisor.numeroIdentificacion;
                        cliente.receptor = trama.receptor.numeroIdentificacion;
                        conexion.Cliente.Add(cliente);
                        conexion.SaveChanges();
                    }
                }
            }
            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.
                throw new DbEntityValidationException(fullErrorMessage, ex.EntityValidationErrors);
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
            return(responsePost);
        }
예제 #9
0
        private void cargarDatosDocumento()
        {
            if (Session["clave"] != null)
            {
                string clave = Session["clave"].ToString();
                using (var conexion = new DataModelFE())
                {
                    string xml = "";
                    if (clave.Substring(29, 2) == TipoDocumento.PROFORMA)
                    {
                        WSRecepcionPOSTProforma dato = conexion.WSRecepcionPOSTProforma.Find(clave);
                        xml = dato.comprobanteXml;
                    }
                    else
                    {
                        WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(clave);
                        xml = dato.comprobanteXml;
                    }

                    this.cmbTipoDocumento.Value = Session["tipoDocumento"].ToString();

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

                    this.cmbCondicionVenta.Value = documento.condicionVenta;
                    this.cmbMedioPago.Value      = documento.medioPago;
                    this.cmbTipoDocumento.Value  = documento.tipoDocumento;
                    this.cmbTipoMoneda.Value     = documento.resumenFactura.codigoMoneda;
                    this.txtTipoCambio.Text      = documento.resumenFactura.tipoCambio.ToString();
                    this.txtPlazoCredito.Text    = documento.plazoCredito;
                    this.txtFechaEmision.Text    = documento.fechaEmision;

                    foreach (var otros in documento.otros.otrosTextos)
                    {
                        this.txtOtrosTextos.Text += string.Format("{0}\n", otros);
                    }

                    txtNombreEmisor.Text   = string.Format("{0} - {1}", documento.emisor.identificacion.numero, documento.emisor.nombre);
                    txtNombreReceptor.Text = string.Format("{0} - {1}", documento.receptor.identificacion.numero, documento.receptor.nombre);


                    if (!string.IsNullOrWhiteSpace(documento.receptor.correoElectronico))
                    {
                        foreach (var correo in documento.receptor.correoElectronico.Split(','))
                        {
                            txtCorreos.Tokens.Add(correo);
                        }
                    }

                    // deja el monto neto facturado
                    foreach (var item in documento.detalleServicio.lineaDetalle)
                    {
                        item.precioUnitario = item.precioUnitario - item.montoDescuento;
                        item.montoDescuento = 0;
                        item.calcularMontos();
                    }

                    Session["detalleServicio"] = documento.detalleServicio;

                    this.refreshData();
                }
            }
        }
예제 #10
0
        public void guardarDocumentoReceptor()
        {
            using (var conexion = new DataModelFE())
            {
                //Se guardan los datos en la tabla de ws_resumen_xml_receptor
                string xmlr = Session["xmlFileValidar"].ToString();
                DocumentoElectronico   documento = (DocumentoElectronico)EncodeXML.XMLUtils.getObjetcFromXML(xmlr);
                ResumenFacturaReceptor datos     = conexion.ResumenFacturaReceptor.Find(documento.clave);

                if (datos == null)
                {
                    datos                         = new ResumenFacturaReceptor();
                    datos.clave                   = documento.clave;
                    datos.tipoCambio              = documento.resumenFactura.tipoCambio;
                    datos.codigoMoneda            = documento.resumenFactura.codigoMoneda;
                    datos.totalServGravados       = documento.resumenFactura.totalServGravados;
                    datos.totalServExentos        = documento.resumenFactura.totalServExentos;
                    datos.totalMercanciasGravadas = documento.resumenFactura.totalMercanciasGravadas;
                    datos.totalMercanciasExentas  = documento.resumenFactura.totalMercanciasExentas;
                    datos.totalGravado            = documento.resumenFactura.totalGravado;
                    datos.totalExento             = documento.resumenFactura.totalExento;
                    datos.totalVenta              = documento.resumenFactura.totalVenta;
                    datos.totalDescuentos         = documento.resumenFactura.totalDescuentos;
                    datos.totalVentaNeta          = documento.resumenFactura.totalVentaNeta;
                    datos.totalImpuesto           = documento.resumenFactura.totalImpuesto;
                    datos.totalComprobante        = documento.resumenFactura.totalComprobante;
                    conexion.ResumenFacturaReceptor.Add(datos);

                    //Guardar la información en ws_recepcion_documento_receptor
                    WSRecepcionPOSTReceptor datosReceptor = new WSRecepcionPOSTReceptor();
                    datosReceptor.clave = datos.clave;
                    //Emisor
                    string emisorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Emisor", "Identificacion", xmlr);
                    datosReceptor.emisorIdentificacion = emisorIdentificacion.Substring(2);
                    datosReceptor.emisorTipo           = emisorIdentificacion.Substring(0, 2);
                    //Receptor
                    string receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "Identificacion", xmlr);
                    if (!string.IsNullOrWhiteSpace(receptorIdentificacion))
                    {
                        datosReceptor.receptorIdentificacion = receptorIdentificacion.Substring(2);
                        datosReceptor.receptorTipo           = receptorIdentificacion.Substring(0, 2);
                    }
                    else
                    {
                        datosReceptor.receptorTipo           = "99";
                        datosReceptor.receptorIdentificacion = XMLUtils.buscarValorEtiquetaXML("Receptor", "IdentificacionExtranjero", xmlr);
                    }
                    //Comprobante XML
                    datosReceptor.comprobanteXml = EncodeXML.XMLUtils.base64Encode(xmlr);

                    //Auditoría
                    datosReceptor.usuarioCreacion = Session["usuario"].ToString();
                    datosReceptor.fechaCreacion   = Date.DateTimeNow();

                    //Valores de la tabla
                    datosReceptor.montoTotalFactura  = decimal.Parse(this.txtTotalFactura.Text);
                    datosReceptor.montoTotalImpuesto = decimal.Parse(this.txtMontoTotalImpuesto.Text);
                    datosReceptor.tipoDocumento      = datos.clave.Substring(29, 2);

                    //Verificar si este dato es el correcto
                    datosReceptor.mensaje = this.txtDetalleMensaje.Text;
                    datosReceptor.fecha   = DateTime.ParseExact(documento.fechaEmision.Replace("-06:00", ""), "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture);

                    //Datos Hacienda
                    using (var conexionWS = new DataModelFE())
                    {
                        WSRecepcionPOST datoHacienda = conexionWS.WSRecepcionPOST.Find(datosReceptor.clave);
                        if (datoHacienda != null)
                        {
                            datosReceptor.indEstado = datoHacienda.indEstado;
                            datosReceptor.mensaje   = datoHacienda.mensaje;
                        }
                        else
                        {
                            datosReceptor.indEstado = 1;
                        }
                    }
                    conexion.WSRecepcionPOSTReceptor.Add(datosReceptor);
                    conexion.SaveChanges();
                }
            }
        }
예제 #11
0
        public async Task <IHttpActionResult> respuestamesajehacienda(string clave)
        {
            try
            {
                using (var conexion = new DataModelFE())
                {
                    WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(clave);
                    if (dato != null)
                    {
                        if (dato.montoTotalFactura == 0)
                        {
                            return(Ok(new WSRespuestaGET(dato)));
                        }
                        else
                        {
                            string respuestaJSON = await ServicesHacienda.getRecepcion(await this.getToken(), clave);

                            if (!string.IsNullOrWhiteSpace(respuestaJSON))
                            {
                                WSRecepcionGET respuesta = JsonConvert.DeserializeObject <WSRecepcionGET>(respuestaJSON);
                                if (respuesta.respuestaXml != null)
                                {
                                    string respuestaXML = respuesta.respuestaXml;

                                    MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML);

                                    //dato = conexion.WSRecepcionPOST.Where(x=>x.clave==clave).FirstOrDefault();
                                    dato.mensaje             = mensajeHacienda.mensajeDetalle;
                                    dato.indEstado           = mensajeHacienda.mensaje;
                                    dato.fechaModificacion   = Date.DateTimeNow();
                                    dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO;
                                    //dato.receptorIdentificacion = mensajeHacienda.receptorNumeroCedula;
                                    dato.montoTotalFactura     = mensajeHacienda.montoTotalFactura;
                                    dato.montoTotalImpuesto    = mensajeHacienda.montoTotalImpuesto;
                                    conexion.Entry(dato).State = EntityState.Modified;
                                    conexion.SaveChanges();

                                    return(Ok(new WSRespuestaGET(dato)));
                                }
                                else
                                {
                                    if (respuesta.indEstado.ToLower().Equals("recibido"))
                                    {
                                        using (var conexionWS = new DataModelFE())
                                        {
                                            dato                         = conexionWS.WSRecepcionPOST.Find(clave);
                                            dato.indEstado               = 8 /*recibido por hacienda*/;
                                            dato.fechaModificacion       = Date.DateTimeNow();
                                            dato.usuarioModificacion     = Usuario.USUARIO_AUTOMATICO;
                                            conexionWS.Entry(dato).State = EntityState.Modified;
                                            conexionWS.SaveChanges();

                                            return(Ok(new WSRespuestaGET(dato)));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                return(NotFound());
            }
            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(Ok(fullErrorMessage));
            }
            catch (Exception ex)
            {
                return(Ok(ex.Message));
            }
        }
예제 #12
0
        protected void btnEnviarCorreo_Click(object sender, EventArgs e)
        {
            try
            {
                using (var conexion = new DataModelFE())
                {
                    string clave  = Session["clave"].ToString();
                    string xml    = "";
                    string asunto = "";

                    if (clave.Substring(29, 2) == TipoDocumento.PROFORMA)
                    {
                        WSRecepcionPOSTProforma dato = conexion.WSRecepcionPOSTProforma.Find(clave);
                        xml    = dato.comprobanteXml;
                        asunto = "Proforma";
                    }
                    else
                    {
                        WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(clave);
                        xml    = dato.comprobanteXml;
                        asunto = "Documento Electrónico";
                    }

                    string numeroConsecutivo = XMLUtils.buscarValorEtiquetaXML(XMLUtils.tipoDocumentoXML(xml), "NumeroConsecutivo", xml);
                    string correoElectronico = XMLUtils.buscarValorEtiquetaXML("Receptor", "CorreoElectronico", xml);
                    string nombre            = XMLUtils.buscarValorEtiquetaXML("Emisor", "Nombre", xml);

                    if (this.txtCorreos.Tokens.Count > 0)
                    {
                        List <string> cc        = new List <string>();
                        Regex         validator = new Regex(@"\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*");

                        foreach (var correo in this.txtCorreos.Tokens)
                        {
                            if (validator.IsMatch(correo))
                            {
                                cc.Add(correo);
                            }
                            else
                            {
                                this.alertMessages.Attributes["class"] = "alert alert-danger";
                                this.alertMessages.InnerText           = String.Format("Favor verifique el formato de la dirección {0}", correo);
                                return;
                            }
                        }

                        if (!string.IsNullOrWhiteSpace(correoElectronico))
                        {
                            cc.RemoveAt(0);
                        }


                        if (!string.IsNullOrWhiteSpace(correoElectronico) || cc.Count > 0)
                        {
                            bool result = Utilidades.sendMail(Session["emisor"].ToString(), correoElectronico,
                                                              string.Format("{0} - {1}", numeroConsecutivo, nombre),
                                                              Utilidades.mensageGenerico(), asunto, xml, numeroConsecutivo, clave, cc);

                            if (result)
                            {
                                this.alertMessages.Attributes["class"] = "alert alert-info";
                                this.alertMessages.InnerText           = "El envió se realizó exitosamente";
                            }
                            else
                            {
                                this.alertMessages.Attributes["class"] = "alert alert-danger";
                                this.alertMessages.InnerText           = "Tenemos problema para enviar el correo, favor intente más tarde";
                            }
                        }
                    }
                    else
                    {
                        this.alertMessages.Attributes["class"] = "alert alert-danger";
                        this.alertMessages.InnerText           = "Debe digitar una dirección de correo eléctronico";
                    }
                }
            }
            catch (Exception ex)
            {
                this.alertMessages.Attributes["class"] = "alert alert-danger";
                this.alertMessages.InnerText           = Utilidades.validarExepcionSQL(ex);
            }
            finally
            {
                //refescar los datos
                this.refreshData();
            }
        }
        protected async void btnActualizar_Click(object sender, EventArgs e)
        {
            try
            {
                using (var conexion = new DataModelFE())
                {
                    EmisorReceptorIMEC  emisor   = (EmisorReceptorIMEC)Session["elEmisor"];
                    string              ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                    OAuth2.OAuth2Config config   = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                    config.username = emisor.usernameOAuth2;
                    config.password = emisor.passwordOAuth2;

                    await OAuth2.OAuth2Config.getTokenWeb(config);

                    string clave         = Session["clave"].ToString();
                    string respuestaJSON = await Services.getRecepcion(config.token, clave);

                    if (!string.IsNullOrWhiteSpace(respuestaJSON))
                    {
                        WSRecepcionGET respuesta = JsonConvert.DeserializeObject <WSRecepcionGET>(respuestaJSON);
                        if (!string.IsNullOrWhiteSpace(respuesta.respuestaXml))
                        {
                            string respuestaXML = EncodeXML.XMLUtils.base64Decode(respuesta.respuestaXml);

                            MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML);

                            using (var conexionWS = new DataModelFE())
                            {
                                WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(clave);
                                dato.mensaje             = mensajeHacienda.mensajeDetalle;
                                dato.indEstado           = mensajeHacienda.mensaje;
                                dato.fechaModificacion   = Date.DateTimeNow();
                                dato.usuarioModificacion = Session["usuario"].ToString();
                                //dato.receptorIdentificacion = mensajeHacienda.receptorNumeroCedula;
                                dato.montoTotalFactura  = mensajeHacienda.montoTotalFactura;
                                dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto;
                                dato.montoTotalImpuesto = mensajeHacienda.montoTotalImpuesto;
                                dato.comprobanteRespXML = respuestaXML;

                                if (mensajeHacienda.montoTotalFactura == 0)
                                {
                                    string xml = XMLUtils.base64Decode(dato.comprobanteXml);
                                    dato.montoTotalImpuesto = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalImpuesto", xml));
                                    dato.montoTotalFactura  = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalComprobante", xml));
                                }


                                conexionWS.Entry(dato).State = EntityState.Modified;
                                conexionWS.SaveChanges();

                                Session["indEstado"] = dato.indEstado;
                            }
                        }
                        else
                        {
                            if (respuesta.indEstado.Equals("recibido"))
                            {
                                using (var conexionWS = new DataModelFE())
                                {
                                    WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(clave);
                                    dato.indEstado               = 8 /*recibido por hacienda*/;
                                    dato.fechaModificacion       = Date.DateTimeNow();
                                    dato.usuarioModificacion     = Usuario.USUARIO_AUTOMATICO;
                                    conexionWS.Entry(dato).State = EntityState.Modified;
                                    conexionWS.SaveChanges();
                                }
                            }

                            this.alertMessages.Attributes["class"] = "alert alert-info";
                            this.alertMessages.InnerText           = String.Format("Documento eléctronico se encuentra RECIBIDO pero aún pendiente de ser ACEPTADO");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(Utilidades.validarExepcionSQL(ex), ex.InnerException);
            }
            finally
            {
                //refescar los datos
                this.refreshData();
            }
        }
예제 #14
0
        private void cargarDatosDocumento()
        {
            if (Session["clave"] != null)
            {
                string clave = Session["clave"].ToString();
                using (var conexion = new DataModelFE())
                {
                    WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(clave);
                    this.txtClave.Text          = dato.clave;
                    this.txtConsecutivo.Text    = dato.numeroConsecutivo;
                    this.txtFechaEmisor.Text    = dato.fecha.ToString();
                    this.cmbTipoDocumento.Value = Session["tipoNota"].ToString();

                    /* SUCURSAL CAJA */
                    string emisor = Session["emisor"].ToString();
                    List <ConsecutivoDocElectronico> lista = conexion.ConsecutivoDocElectronico.Where(x => x.emisor == emisor &&
                                                                                                      x.tipoDocumento == this.cmbTipoDocumento.Value.ToString() && x.estado == Estado.ACTIVO.ToString()).ToList();
                    if (lista.Count == 0)
                    {
                        ConsecutivoDocElectronico consecutivo = new ConsecutivoDocElectronico();
                        consecutivo.sucursal          = ConsecutivoDocElectronico.DEFAULT_SUCURSAL;
                        consecutivo.caja              = ConsecutivoDocElectronico.DEFAULT_CAJA;
                        consecutivo.digitoVerificador = ConsecutivoDocElectronico.DEFAULT_DIGITO_VERIFICADOR;
                        consecutivo.emisor            = emisor;
                        consecutivo.tipoDocumento     = this.cmbTipoDocumento.Value.ToString();
                        consecutivo.consecutivo       = 1;
                        consecutivo.estado            = Estado.ACTIVO.ToString();
                        consecutivo.fechaCreacion     = Date.DateTimeNow();
                        conexion.ConsecutivoDocElectronico.Add(consecutivo);
                        conexion.SaveChanges();

                        lista = conexion.ConsecutivoDocElectronico.Where(x => x.emisor == emisor &&
                                                                         x.tipoDocumento == this.cmbTipoDocumento.Value.ToString() && x.estado == Estado.ACTIVO.ToString()).ToList();
                    }

                    this.cmbSucursalCaja.Items.Clear();
                    foreach (var item in lista)
                    {
                        this.cmbSucursalCaja.Items.Add(item.ToString(), string.Format("{0}{1}", item.sucursal, item.caja));
                    }
                    this.cmbSucursalCaja.IncrementalFilteringMode = IncrementalFilteringMode.Contains;


                    string xml = dato.comprobanteXml;

                    FacturaElectronica factura = (FacturaElectronica)EncodeXML.XMLUtils.getObjetcFromXML(xml, typeof(FacturaElectronica));

                    txtNombreEmisor.Text   = string.Format("{0} - {1}", factura.emisor.identificacion.numero, factura.emisor.nombre);
                    txtNombreReceptor.Text = string.Format("{0} - {1}", factura.receptor.identificacion.numero, factura.receptor.nombre);

                    txtCorreoReceptor.Text = factura.receptor.correoElectronico;

                    // deja el monto neto facturado
                    foreach (var item in factura.detalleServicio.lineaDetalle)
                    {
                        item.precioUnitario = item.precioUnitario - item.montoDescuento;
                        item.montoDescuento = 0;
                        item.calcularMontos();
                    }

                    Session["detalleServicio"] = factura.detalleServicio;

                    this.refreshData();
                }
            }
        }
예제 #15
0
        public async Task <IHttpActionResult> respuestamesajehacienda(string clave)
        {
            using (var conexion = new DataModelFE())
            {
                WSRecepcionPOST dato = conexion.WSRecepcionPOST.Find(clave);
                if (dato.montoTotalFactura > 0)
                {
                    return(Ok(new WSDomain.WSRespuestaGET(dato)));
                }
                else
                {
                    EmisorReceptorIMEC  elEmisor = conexion.EmisorReceptorIMEC.Find(Usuario.USUARIO_TOKEN);
                    string              ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                    OAuth2.OAuth2Config config   = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                    config.username = elEmisor.usernameOAuth2;
                    config.password = elEmisor.passwordOAuth2;

                    await OAuth2.OAuth2Config.getTokenWeb(config);

                    string respuestaJSON = await ServicesHacienda.getRecepcion(config.token, clave);

                    if (!string.IsNullOrWhiteSpace(respuestaJSON))
                    {
                        WSRecepcionGET respuesta = JsonConvert.DeserializeObject <WSRecepcionGET>(respuestaJSON);
                        if (respuesta.respuestaXml != null)
                        {
                            string respuestaXML = EncodeXML.EncondeXML.base64Decode(respuesta.respuestaXml);

                            MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML);

                            dato                     = conexion.WSRecepcionPOST.Find(clave);
                            dato.mensaje             = mensajeHacienda.mensajeDetalle;
                            dato.indEstado           = mensajeHacienda.mensaje;
                            dato.fechaModificacion   = Date.DateTimeNow();
                            dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO;
                            //dato.receptorIdentificacion = mensajeHacienda.receptorNumeroCedula;
                            dato.montoTotalFactura     = mensajeHacienda.montoTotalFactura;
                            dato.montoTotalImpuesto    = mensajeHacienda.montoTotalImpuesto;
                            conexion.Entry(dato).State = EntityState.Modified;
                            conexion.SaveChanges();

                            return(Ok(new WSRespuestaGET(dato)));
                        }
                        else
                        {
                            if (respuesta.indEstado.ToLower().Equals("recibido"))
                            {
                                using (var conexionWS = new DataModelFE())
                                {
                                    dato                         = conexionWS.WSRecepcionPOST.Find(clave);
                                    dato.indEstado               = 8 /*recibido por hacienda*/;
                                    dato.fechaModificacion       = Date.DateTimeNow();
                                    dato.usuarioModificacion     = Usuario.USUARIO_AUTOMATICO;
                                    conexionWS.Entry(dato).State = EntityState.Modified;
                                    conexionWS.SaveChanges();

                                    return(Ok(new WSRespuestaGET(dato)));
                                }
                            }
                        }
                    }
                }
            }
            return(NotFound());
        }
예제 #16
0
        private XtraReport CreateReport()
        {
            XtraReport report1 = new XtraReport();
            XtraReport report2 = new XtraReport();

            List <XtraReport> oLista = new List <XtraReport>();
            XtraReport        report = null;
            var pLista = (List <String>)Session["claves"];

            foreach (var item in pLista)
            {
                XtraReport reportP = new XtraReport();

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

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

                    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();
                        reportP = 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();
                        reportP = reportES;
                    }
                }
                oLista.Add(reportP);
            }

            if (oLista.Count == 1)
            {
                report1 = oLista[0];
            }
            else
            {
                if (oLista.Count == 2)
                {
                    report1 = oLista[0];
                    report2 = oLista[1];
                    report1.Pages.AddRange(report2.Pages);
                    report1.PrintingSystem.ContinuousPageNumbering = true;
                }
                else
                {
                    for (int i = 0; i < oLista.Count - 1; i++)
                    {
                        if (i == 0)
                        {
                            report1 = oLista[i];
                        }
                        else
                        {
                            report1 = report1;
                        }

                        report2 = oLista[i + 1];
                        report1.Pages.AddRange(report2.Pages);
                        report1.PrintingSystem.ContinuousPageNumbering = true;
                    }
                }
            }

            report = report1;
            return(report);
        }
예제 #17
0
        XtraReport CreateReport(string clave)
        {
            XtraReport report = null;

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

                //WSRecepcionPOST dato = conexion.WSRecepcionPOST.Where(x => x.clave == clave).FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(xml))
                {
                    //string xml = EncodeXML.XMLUtils.base64Decode(xml);

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

                    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, 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
                    {
                        if (empresa != null && "ES".Equals(empresa.idioma))
                        {
                            object dataSource = UtilidadesReporte.cargarObjetoImpresion(documento, 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;
                        }
                        else
                        {
                            this.alertMessages.Attributes["class"] = "alert alert-danger";
                            this.alertMessages.InnerText           = "El documento ingresado no se encuentra en el repositorio de datos del emisor!!!";
                        }
                    }
                    this.alertMessages.Attributes["class"] = "alert alert-info";
                    this.alertMessages.InnerText           = "Los datos fueron enviados correctamente!!!";
                }
                else
                {
                    this.alertMessages.Attributes["class"] = "alert alert-danger";
                    this.alertMessages.InnerText           = "El documento ingresado no se encuentra en el repositorio de datos del emisor!!!";
                }
            }

            return(report);
        }
예제 #18
0
파일: JobsTask.cs 프로젝트: yeco96/FE
        /// <summary>
        /// Se actualizan los mensajes del ministerio de hacienda que esten pendientes
        /// </summary>
        /// <returns></returns>
        public async Task <bool> actualizarMensajesHacienda()
        {
            try
            {
                EmisorReceptorIMEC  emisor = null;
                OAuth2.OAuth2Config config = null;
                Thread.CurrentThread.CurrentCulture = Utilidades.getCulture();

                using (var conexion = new DataModelFE())
                {
                    List <WSRecepcionPOST> lista = conexion.WSRecepcionPOST.
                                                   Where(x => x.indEstado == 0 /*ENVIADO*/ ||
                                                         x.indEstado == 8 /*RECIBIDO*/ ||
                                                         x.indEstado == 9  /*PENDIENTE  ||
                                                                            * x.comprobanteRespXML == null*/).ToList();
                    foreach (var item in lista)
                    {
                        if (config == null)
                        {
                            emisor = conexion.EmisorReceptorIMEC.Find(Usuario.USUARIO_TOKEN);
                            string ambiente = ConfigurationManager.AppSettings["ENVIROMENT"].ToString();
                            config          = conexion.OAuth2Config.Where(x => x.enviroment == ambiente).FirstOrDefault();
                            config.username = emisor.usernameOAuth2;
                            config.password = emisor.passwordOAuth2;
                            await OAuth2.OAuth2Config.getTokenWeb(config);
                        }

                        string respuestaJSON = await Services.getRecepcion(config.token, item.clave);

                        if (!string.IsNullOrWhiteSpace(respuestaJSON))
                        {
                            WSRecepcionGET respuesta = JsonConvert.DeserializeObject <WSRecepcionGET>(respuestaJSON);
                            if (respuesta.respuestaXml != null)
                            {
                                string          respuestaXML    = EncodeXML.XMLUtils.base64Decode(respuesta.respuestaXml);
                                MensajeHacienda mensajeHacienda = new MensajeHacienda(respuestaXML);

                                using (var conexionWS = new DataModelFE())
                                {
                                    WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(item.clave);
                                    dato.mensaje             = mensajeHacienda.mensajeDetalle;
                                    dato.indEstado           = mensajeHacienda.mensaje;
                                    dato.fechaModificacion   = Date.DateTimeNow();
                                    dato.usuarioModificacion = Usuario.USUARIO_AUTOMATICO;
                                    dato.montoTotalFactura   = mensajeHacienda.montoTotalFactura;
                                    dato.montoTotalImpuesto  = mensajeHacienda.montoTotalImpuesto;
                                    dato.comprobanteRespXML  = respuestaXML;

                                    if (mensajeHacienda.montoTotalFactura == 0)
                                    {
                                        string xml = XMLUtils.base64Decode(dato.comprobanteXml);

                                        try
                                        {
                                            dato.montoTotalImpuesto = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalImpuesto", xml));
                                            dato.montoTotalFactura  = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalComprobante", xml));
                                        }
                                        catch (Exception ex)
                                        {
                                            dato.montoTotalImpuesto = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalImpuesto", xml).Replace(".", ","));
                                            dato.montoTotalFactura  = Convert.ToDecimal(XMLUtils.buscarValorEtiquetaXML("ResumenFactura", "TotalComprobante", xml).Replace(".", ","));
                                        }
                                    }

                                    conexionWS.Entry(dato).State = EntityState.Modified;
                                    conexionWS.SaveChanges();
                                }
                            }
                            else
                            {
                                if (respuesta.indEstado.Equals("recibido"))
                                {
                                    using (var conexionWS = new DataModelFE())
                                    {
                                        WSRecepcionPOST dato = conexionWS.WSRecepcionPOST.Find(item.clave);
                                        dato.indEstado               = 8 /*recibido por hacienda*/;
                                        dato.fechaModificacion       = Date.DateTimeNow();
                                        dato.usuarioModificacion     = Usuario.USUARIO_AUTOMATICO;
                                        conexionWS.Entry(dato).State = EntityState.Modified;
                                        conexionWS.SaveChanges();
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                String data = e.Message;
            }
            return(true);
        }
예제 #19
0
        protected async void btnCrearNota_Click(object sender, EventArgs e)
        {
            try
            {
                Thread.CurrentThread.CurrentCulture = Utilidades.getCulture();


                List <string> cc        = new List <string>();
                Regex         validator = new Regex(@"\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*");

                foreach (var correo in this.txtCorreoReceptor.Tokens)
                {
                    if (validator.IsMatch(correo))
                    {
                        cc.Add(correo);
                    }
                    else
                    {
                        this.alertMessages.Attributes["class"] = "alert alert-danger";
                        this.alertMessages.InnerText           = String.Format("Favor verifique el formato de la dirección {0}", correo);
                        return;
                    }
                }
                cc.RemoveAt(0);


                DetalleServicio detalle = (DetalleServicio)Session["detalleServicio"];
                if (detalle.lineaDetalle.Count == 0)
                {
                    this.alertMessages.Attributes["class"] = "alert alert-danger";
                    this.alertMessages.InnerText           = "Debe agregar almenos una linea de detalle a la factura";
                    return;
                }

                // datos de la factura original
                FacturaElectronica factura = new FacturaElectronica();
                string             clave   = Session["clave"].ToString();
                using (var conexion = new DataModelFE())
                {
                    WSRecepcionPOST datoPost   = conexion.WSRecepcionPOST.Find(clave);
                    string          xmlFactura = datoPost.comprobanteXml;
                    factura = (FacturaElectronica)EncodeXML.XMLUtils.getObjetcFromXML(xmlFactura, typeof(FacturaElectronica));

                    DocumentoElectronico dato = null;
                    if (TipoDocumento.NOTA_CREDITO.Equals(Session["tipoNota"].ToString()))
                    {
                        dato = new NotaCreditoElectronica();
                    }
                    else
                    {
                        dato = new NotaDebitoElectronica();
                    }


                    /* ENCABEZADO */
                    dato.medioPago      = factura.medioPago;
                    dato.plazoCredito   = factura.plazoCredito;
                    dato.condicionVenta = factura.condicionVenta;
                    dato.fechaEmision   = Date.DateTimeNow().ToString("yyyy-MM-ddTHH:mm:ss") + "-06:00";
                    /* DETALLE */
                    dato.detalleServicio = detalle;

                    /* EMISOR */
                    dato.emisor = factura.emisor;


                    /* RECEPTOR */
                    dato.receptor = factura.receptor;


                    /* INFORMACION DE REFERENCIA */
                    InformacionReferencia informacionReferencia = new InformacionReferencia();
                    informacionReferencia.numero        = factura.clave;
                    informacionReferencia.fechaEmision  = factura.fechaEmision;
                    informacionReferencia.codigo        = this.cmbCodigoReferencia.Value.ToString();
                    informacionReferencia.razon         = this.txtRazón.Text;
                    informacionReferencia.tipoDocumento = TipoDocumento.FACTURA_ELECTRONICA;
                    dato.informacionReferencia.Add(informacionReferencia);

                    /* RESUMEN */
                    dato.resumenFactura.tipoCambio   = factura.resumenFactura.tipoCambio;
                    dato.resumenFactura.codigoMoneda = factura.resumenFactura.codigoMoneda;
                    foreach (var item in dato.detalleServicio.lineaDetalle)
                    {
                        if (item.tipoServMerc == null)
                        {
                            Producto producto = conexion.Producto.Where(x => x.codigo == item.codigo.codigo && x.emisor == dato.emisor.identificacion.numero).FirstOrDefault();
                            item.tipoServMerc = producto.tipoServMerc;
                            item.producto     = producto.codigo;
                        }
                    }
                    dato.resumenFactura.calcularResumenFactura(dato.detalleServicio.lineaDetalle);

                    /* VERIFICA VACIOS PARA XML */
                    dato.verificaDatosParaXML();

                    //genera el consecutivo del documento
                    string   sucursal = this.cmbSucursalCaja.Value.ToString().Substring(0, 3);
                    string   caja     = this.cmbSucursalCaja.Value.ToString().Substring(3, 5);
                    object[] key      = new object[] { dato.emisor.identificacion.numero, sucursal, caja, this.cmbTipoDocumento.Value.ToString() };
                    ConsecutivoDocElectronico consecutivo = conexion.ConsecutivoDocElectronico.Find(key);
                    if (consecutivo != null)
                    {
                        dato.clave             = consecutivo.getClave(Date.DateTimeNow().ToString("yyyyMMdd"));
                        dato.numeroConsecutivo = consecutivo.getConsecutivo();

                        consecutivo.consecutivo          += 1;
                        conexion.Entry(consecutivo).State = EntityState.Modified;
                    }
                    else
                    {
                        consecutivo                   = new ConsecutivoDocElectronico();
                        consecutivo.sucursal          = ConsecutivoDocElectronico.DEFAULT_SUCURSAL;
                        consecutivo.caja              = ConsecutivoDocElectronico.DEFAULT_CAJA;
                        consecutivo.digitoVerificador = ConsecutivoDocElectronico.DEFAULT_DIGITO_VERIFICADOR;
                        consecutivo.emisor            = dato.emisor.identificacion.numero;
                        consecutivo.tipoDocumento     = this.cmbTipoDocumento.Value.ToString();
                        consecutivo.consecutivo       = 1;
                        consecutivo.estado            = Estado.ACTIVO.ToString();
                        consecutivo.fechaCreacion     = Date.DateTimeNow();

                        dato.clave             = consecutivo.getClave(Date.DateTimeNow().ToString("yyyyMMdd"));
                        dato.numeroConsecutivo = consecutivo.getConsecutivo();

                        consecutivo.consecutivo += 1;
                        conexion.ConsecutivoDocElectronico.Add(consecutivo);
                    }

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

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

                        if (!string.IsNullOrWhiteSpace(dato.receptor.correoElectronico) || this.txtCorreoReceptor.Tokens.Count > 0)
                        {
                            string xml = EncodeXML.XMLUtils.getXMLFromObject(dato);

                            Utilidades.sendMail(Session["emisor"].ToString(), dato.receptor.correoElectronico,
                                                string.Format("{0} - {1}", dato.numeroConsecutivo, elEmisor.nombre),
                                                Utilidades.mensageGenerico(), "Documento Electrónico", xml, dato.numeroConsecutivo, dato.clave, cc);
                        }
                    }
                    else if (responsePost.Equals("Error"))
                    {
                        this.alertMessages.Attributes["class"] = "alert alert-danger";
                        this.alertMessages.InnerText           = String.Format("Documento #{0} con errores.", dato.numeroConsecutivo);
                        return;
                    }
                    else
                    {
                        this.alertMessages.Attributes["class"] = "alert alert-warning";
                        this.alertMessages.InnerText           = String.Format("Documento #{0} pendiente de envío", dato.numeroConsecutivo);
                    }

                    conexion.SaveChanges();


                    Response.Redirect("~/Pages/Consulta/" + dato.clave);
                }
            }
            catch (Exception ex)
            {
                this.alertMessages.Attributes["class"] = "alert alert-danger";
                this.alertMessages.InnerText           = Utilidades.validarExepcionSQL(ex);
            }
            finally
            {
                //refescar los datos
                this.refreshData();
            }
        }