Beispiel #1
0
        //TODO: correr en otro thread o utilizar updatepanel para mostrar barra de estado
        protected void btnCheckWSAA_Click(object sender, EventArgs e)
        {
            try
            {
                Settings oSettings = new Settings(ddlEmpresa.SelectedItem.Value);

                lblWSAAExportacion.Text = CheckAfipLogin("wsfex", oSettings);
                if (lblWSAAExportacion.Text == "OK")
                    lblWSAAExportacion.ForeColor = System.Drawing.Color.Green;
                else
                    lblWSAAExportacion.ForeColor = System.Drawing.Color.Red;

                lblWSAABienes.Text = CheckAfipLogin("wsfe", oSettings);
                if (lblWSAABienes.Text == "OK")
                    lblWSAABienes.ForeColor = System.Drawing.Color.Green;
                else
                    lblWSAABienes.ForeColor = System.Drawing.Color.Red;

                lblWSAACapital.Text = CheckAfipLogin("wsbfe", oSettings);
                if (lblWSAACapital.Text == "OK")
                    lblWSAACapital.ForeColor = System.Drawing.Color.Green;
                else
                    lblWSAACapital.ForeColor = System.Drawing.Color.Red;
            }
            catch (Exception ex)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "alert('Error al intentar login con AFIP, vuelva a intentar la operacion en unos minutos. Exception: " + ex.Message + "')", true);
            }
        }
Beispiel #2
0
        private void ProcessDownload(string EmpresaID)
        {
            FEPrint.FEPrintService FEPrintService = new FEPrint.FEPrintService();

            string strId = Request.QueryString["nc"];
            string strTipoCbte = Request.QueryString["nt"];
            string strNumeroLegal = Request.QueryString["leg"];

            try
            {
                Settings oSettings = new Settings(EmpresaID);

                FEPrintService.Url = oSettings.UrlPrintWebService;
                FEPrintService.Credentials = System.Net.CredentialCache.DefaultCredentials;

                byte[] fileData = null;

                switch (Request.QueryString["type"])
                {
                    case "o":
                        fileData = FEPrintService.GetCbte(EmpresaID, strId, FEPrint.TipoDeCopia.Original);//(byte[])sqlDReader["PDF" + strType];
                        break;
                    case "d":
                        fileData = FEPrintService.GetCbte(EmpresaID, strId, FEPrint.TipoDeCopia.Duplicado);
                        break;
                    case "t":
                        fileData = FEPrintService.GetCbte(EmpresaID, strId, FEPrint.TipoDeCopia.Triplicado);
                        break;
                    case "c":
                        fileData = FEPrintService.GetCbte(EmpresaID, strId, FEPrint.TipoDeCopia.Copia);
                        break;
                }

                if (fileData != null)
                {
                    Response.ClearContent();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + strNumeroLegal + ".pdf");
                    Response.ContentType = "application/pdf";

                    BinaryWriter bw = new BinaryWriter(Response.OutputStream);
                    bw.Write(fileData);
                    bw.Close();

                    Response.End();
                }
                else
                {
                    lblMsg.Text = "No se pudo generar archivo PDF.<br>No se encontro detalle del comprobante.";
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }
Beispiel #3
0
        public AfipBFE(ref wsbfe.Service afipBfexService, ref wsbfe.ClsBFEAuthRequest afipObjBFEAuthRequest, Settings oSettings)
        {
            bfeService = afipBfexService;
            bfeService.Url = oSettings.UrlAFIPwsbfe;
            bfeService.Timeout = 10000;

            objBFEAuthRequest = afipObjBFEAuthRequest;
            objLastCMP.Token = afipObjBFEAuthRequest.Token;
            objLastCMP.Cuit = afipObjBFEAuthRequest.Cuit;
            objLastCMP.Sign = afipObjBFEAuthRequest.Sign;
        }
Beispiel #4
0
        protected void btnCheckAfipService_Click(object sender, EventArgs e)
        {
            try
            {
                Settings oSettings = new Settings(ddlEmpresa.SelectedItem.Value);

                CheckAfipFexService(oSettings);

                CheckAfipFeService(oSettings);

                CheckAfipFebService(oSettings);
            }
            catch (Exception ex)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "alert('Error: " + ex.Message + "')", true);
            }
        }
Beispiel #5
0
        protected override void OnStart(string[] args)
        {
            Settings oSettings = null;
            EmpresaCollection eColl = null;

            try
            {
                eColl = Settings.GetEmpresas();

                foreach (Empresa oEmp in eColl)
                {
                    oSettings = new Settings(oEmp.EmpresaID);

                    switch (oSettings.TipoEntrada)
                    {
                        case Settings.TipoDato.FS:

                            StartFSProcess(oSettings);
                            break;

                        case Settings.TipoDato.MSSQL:

                            StartMSSQLProcess(oSettings);
                            break;

                        case Settings.TipoDato.MSMQ:
                            break;

                        case Settings.TipoDato.WS:
                            break;
                    }
                }
                eColl.Clear();
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Servicio Factura Electronica", "OnStart Error: " + ex.Message, EventLogEntryType.Error);

                this.Stop();
            }
        }
Beispiel #6
0
        private void button1_Click(object sender, EventArgs e)
        {
            Settings oSettings = null;
            EmpresaCollection eColl = null;

            try
            {
                eColl = Settings.GetEmpresas();

                foreach (Empresa oEmp in eColl)
                {
                    oSettings = new Settings(oEmp.EmpresaID);

                    switch (oSettings.TipoEntrada)
                    {
                        case Settings.TipoDato.FS:

                            StartFSProcess(oSettings);
                            break;

                        case Settings.TipoDato.MSSQL:

                            StartMSSQLProcess(oSettings);

                            break;

                        case Settings.TipoDato.MSMQ:
                            break;

                        case Settings.TipoDato.WS:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Servicio Factura Electronica", "OnStart Error: " + ex.Message, EventLogEntryType.Error);

                this.Close();
            }
        }
Beispiel #7
0
        private RequestBatch ProcesarLoteComprobantes(FileInfo fi, Settings oSettings)
        {
            RequestBatch requestBatch = new RequestBatch();

            string filePath = fi.FullName;
            string line;

            bool bProcessOK = true;

            StreamReader fileInput = null;

            //Totales del lote
            double Importe = 0;
            double ImporteComprobanteB = 0;
            double ImporteNoGravado = 0;
            double ImporteGravado = 0;
            double ImporteImpuestoLiquidado = 0;
            double ImporteRNI_Percepcion = 0;
            double ImporteExento = 0;
            double ImportePercepciones_PagosCuentaImpuestosNacionales = 0;
            double ImportePercepcionIIBB = 0;
            double ImportePercepcionImpuestosMunicipales = 0;
            double ImporteImpuestosInternos = 0;
            double ImporteMonedaFacturacion = 0;
            double ImporteMonedaFacturacionComprobanteB = 0;
            double ImporteNoGravadoMonedaFacturacion = 0;
            double ImporteGravadoMonedaFacturacion = 0;
            double ImporteImpuestoLiquidadoMonedaFacturacion = 0;
            double ImporteRNI_PercepcionMonedaFacturacion = 0;
            double ImporteExentoMonedaFacturacion = 0;
            double ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion = 0;
            double ImportePercepcionIIBBMonedaFacturacion = 0;
            double ImportePercepcionImpuestosMunicipalesMonedaFacturacion = 0;
            double ImporteImpuestosInternosMonedaFacturacion = 0;

            int qtyComprobantes = 0;

            try
            {
                fileInput = new StreamReader(filePath, System.Text.Encoding.GetEncoding(1252));

                line = fileInput.ReadLine();
                while (line != null)
                {
                    if (line == "CABECERA")
                    {
                        line = fileInput.ReadLine();
                        if (line != null)
                        {
                            //proceso CABECERA
                            string[] camposCabecera = line.Split(';');

                            RequestHeader thisDocument = new RequestHeader();
                            if (camposCabecera[0] == "" || camposCabecera[0] == " ")
                                thisDocument.TipoTransaccion = "0";
                            else
                                thisDocument.TipoTransaccion = camposCabecera[0];

                            thisDocument.EmpresaID = oSettings.EmpresaID;
                            thisDocument.FechaComprobante = camposCabecera[1].Substring(6, 4) + "-" + camposCabecera[1].Substring(3, 2) + "-" + camposCabecera[1].Substring(0, 2);
                            thisDocument.FechaDesdeServicioFacturado = camposCabecera[2].Substring(6, 4) + "-" + camposCabecera[2].Substring(3, 2) + "-" + camposCabecera[2].Substring(0, 2); ;
                            thisDocument.FechaHastaServicioFacturado = camposCabecera[3].Substring(6, 4) + "-" + camposCabecera[3].Substring(3, 2) + "-" + camposCabecera[3].Substring(0, 2); ;
                            thisDocument.TipoComprobante = camposCabecera[4];
                            thisDocument.PuntoVenta = camposCabecera[5];
                            thisDocument.LetraComprobante = camposCabecera[6];
                            thisDocument.NroComprobanteDesde = camposCabecera[7];
                            thisDocument.NroComprobanteHasta = camposCabecera[7];
                            thisDocument.NroInternoERP = camposCabecera[8];
                            thisDocument.FechaVencimientoPago = camposCabecera[9].Substring(6, 4) + "-" + camposCabecera[9].Substring(3, 2) + "-" + camposCabecera[9].Substring(0, 2);
                            thisDocument.CondicionPago = camposCabecera[10];
                            thisDocument.CompradorCodigoDocumento = camposCabecera[11];
                            thisDocument.CompradorNroDocumento = camposCabecera[12];
                            thisDocument.CompradorTipoResponsable = camposCabecera[13];
                            thisDocument.CompradorTipoResponsableDescripcion = camposCabecera[14];
                            thisDocument.CompradorRazonSocial = camposCabecera[15];
                            thisDocument.CompradorDireccion = camposCabecera[16];
                            thisDocument.CompradorLocalidad = camposCabecera[17];
                            thisDocument.CompradorProvincia = camposCabecera[18];
                            thisDocument.CompradorPais = camposCabecera[19];
                            thisDocument.CompradorCodigoPostal = camposCabecera[20];
                            thisDocument.CompradorNroIIBB = camposCabecera[21];
                            thisDocument.CompradorCodigoCliente = camposCabecera[22];
                            thisDocument.CompradorNroReferencia = camposCabecera[23];
                            thisDocument.CompradorEmail = camposCabecera[24];
                            thisDocument.NroRemito = camposCabecera[25];
                            thisDocument.Importe = IntegrationEngine.ImporteConDecimales(camposCabecera[26], 2);
                            thisDocument.ImporteComprobanteB = IntegrationEngine.ImporteConDecimales(camposCabecera[27], 2);
                            thisDocument.ImporteNoGravado = IntegrationEngine.ImporteConDecimales(camposCabecera[28], 2);
                            thisDocument.ImporteGravado = IntegrationEngine.ImporteConDecimales(camposCabecera[29], 2);
                            thisDocument.AlicuotaIVA = IntegrationEngine.ImporteConDecimales(camposCabecera[30], 2);
                            thisDocument.ImporteImpuestoLiquidado = IntegrationEngine.ImporteConDecimales(camposCabecera[31], 2);
                            thisDocument.ImporteRNI_Percepcion = IntegrationEngine.ImporteConDecimales(camposCabecera[32], 2);
                            thisDocument.ImporteExento = IntegrationEngine.ImporteConDecimales(camposCabecera[33], 2);
                            thisDocument.ImportePercepciones_PagosCuentaImpuestosNacionales = IntegrationEngine.ImporteConDecimales(camposCabecera[34], 2);
                            thisDocument.ImportePercepcionIIBB = IntegrationEngine.ImporteConDecimales(camposCabecera[35], 2);
                            thisDocument.TasaIIBB = IntegrationEngine.ImporteConDecimales(camposCabecera[36], 2);
                            thisDocument.CodigoJurisdiccionIIBB = camposCabecera[37];
                            thisDocument.ImportePercepcionImpuestosMunicipales = IntegrationEngine.ImporteConDecimales(camposCabecera[38], 2);
                            thisDocument.JurisdiccionImpuestosMunicipales = camposCabecera[39];
                            thisDocument.ImporteImpuestosInternos = IntegrationEngine.ImporteConDecimales(camposCabecera[40], 2);
                            thisDocument.ImporteMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[41], 2);
                            thisDocument.ImporteMonedaFacturacionComprobanteB = IntegrationEngine.ImporteConDecimales(camposCabecera[42], 2);
                            thisDocument.ImporteNoGravadoMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[43], 2);
                            thisDocument.ImporteGravadoMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[44], 2);
                            thisDocument.ImporteImpuestoLiquidadoMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[45], 2);
                            thisDocument.ImporteRNI_PercepcionMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[46], 2);
                            thisDocument.ImporteExentoMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[47], 2);
                            thisDocument.ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[48], 2);
                            thisDocument.ImportePercepcionIIBBMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[49], 2);
                            thisDocument.ImportePercepcionImpuestosMunicipalesMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[50], 2);
                            thisDocument.ImporteImpuestosInternosMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposCabecera[51], 2);
                            thisDocument.CantidadAlicuotasIVA = camposCabecera[52];
                            thisDocument.CodigoOperacion = camposCabecera[53];
                            thisDocument.TasaCambio = IntegrationEngine.ImporteConDecimales(camposCabecera[54], 5);
                            thisDocument.CodigoMoneda = camposCabecera[55];
                            thisDocument.ImporteEscrito = camposCabecera[56];
                            thisDocument.CantidadRegistrosDetalle = camposCabecera[57];
                            thisDocument.CodigoMecanismoDistribucion = camposCabecera[58];
                            thisDocument.TipoExportacion = camposCabecera[59];
                            thisDocument.PermisoExistente = camposCabecera[60];
                            thisDocument.CompradorPais = camposCabecera[61];
                            thisDocument.FormaPagoDescripcion = camposCabecera[63];
                            thisDocument.IncoTerms = camposCabecera[64];
                            thisDocument.Idioma = camposCabecera[65];
                            thisDocument.Observaciones1 = camposCabecera[66];
                            thisDocument.Observaciones2 = camposCabecera[67];
                            thisDocument.Observaciones3 = camposCabecera[68];
                            thisDocument.EmisorDireccion = camposCabecera[69];
                            thisDocument.EmisorCalle = camposCabecera[70];
                            thisDocument.EmisorCP = camposCabecera[71];
                            thisDocument.EmisorLocalidad = camposCabecera[72];
                            thisDocument.EmisorProvincia = camposCabecera[73];
                            thisDocument.EmisorPais = camposCabecera[74];
                            thisDocument.EmisorTelefonos = camposCabecera[75];
                            thisDocument.EmisorEMail = camposCabecera[76];
                            thisDocument.OficinaVentas = camposCabecera[77];

                            //Actualizar los importes del lote
                            Importe += Utils.Utils.DoubleFromString(thisDocument.Importe);
                            ImporteComprobanteB += Utils.Utils.DoubleFromString(thisDocument.ImporteComprobanteB);
                            ImporteNoGravado += Utils.Utils.DoubleFromString(thisDocument.ImporteNoGravado);
                            ImporteGravado += Utils.Utils.DoubleFromString(thisDocument.ImporteGravado);
                            ImporteImpuestoLiquidado += Utils.Utils.DoubleFromString(thisDocument.ImporteImpuestoLiquidado);
                            ImporteRNI_Percepcion += Utils.Utils.DoubleFromString(thisDocument.ImporteRNI_Percepcion);
                            ImporteExento += Utils.Utils.DoubleFromString(thisDocument.ImporteExento);
                            ImportePercepciones_PagosCuentaImpuestosNacionales += Utils.Utils.DoubleFromString(thisDocument.ImportePercepciones_PagosCuentaImpuestosNacionales);
                            ImportePercepcionIIBB += Utils.Utils.DoubleFromString(thisDocument.ImportePercepcionIIBB);
                            ImportePercepcionImpuestosMunicipales += Utils.Utils.DoubleFromString(thisDocument.ImportePercepcionImpuestosMunicipales);
                            ImporteImpuestosInternos += Utils.Utils.DoubleFromString(thisDocument.ImporteImpuestosInternos);
                            ImporteMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImporteMonedaFacturacion);
                            ImporteMonedaFacturacionComprobanteB += Utils.Utils.DoubleFromString(thisDocument.ImporteMonedaFacturacionComprobanteB);
                            ImporteNoGravadoMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImporteNoGravadoMonedaFacturacion);
                            ImporteGravadoMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImporteGravadoMonedaFacturacion);
                            ImporteImpuestoLiquidadoMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImporteImpuestoLiquidadoMonedaFacturacion);
                            ImporteRNI_PercepcionMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImporteRNI_PercepcionMonedaFacturacion);
                            ImporteExentoMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImporteExentoMonedaFacturacion);
                            ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion);
                            ImportePercepcionIIBBMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImportePercepcionIIBBMonedaFacturacion);
                            ImportePercepcionImpuestosMunicipalesMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImportePercepcionImpuestosMunicipalesMonedaFacturacion);
                            ImporteImpuestosInternosMonedaFacturacion += Utils.Utils.DoubleFromString(thisDocument.ImporteImpuestosInternosMonedaFacturacion);

                            line = fileInput.ReadLine();
                            if (line != null && line == "DETALLE")
                            {
                                //proceso el detalle
                                RequestLine thisLine = new RequestLine();

                                line = fileInput.ReadLine();
                                if (line != null)
                                {
                                    while (line != null && line != "CABECERA")
                                    {
                                        thisLine = new RequestLine();
                                        string[] camposDetalle = line.Split(';');

                                        if (camposDetalle.Length > 10)
                                        {
                                            thisLine.CodigoProductoEmpresa = camposDetalle[0];
                                            while (thisLine.CodigoProductoEmpresa.Substring(0, 1) == "0")
                                            {
                                                thisLine.CodigoProductoEmpresa = thisLine.CodigoProductoEmpresa.Substring(1, thisLine.CodigoProductoEmpresa.Length - 1);
                                            }
                                            thisLine.CodigoProductoNCM = camposDetalle[1]; // RUTINA PARA OBTENERLO
                                            thisLine.CodigoProductoSecretaria = camposDetalle[2];
                                            thisLine.Descripcion = camposDetalle[3];
                                            thisLine.Cantidad = IntegrationEngine.ImporteConDecimales(camposDetalle[4], 3);
                                            thisLine.UnidadMedida = camposDetalle[5];
                                            thisLine.ImportePrecioUnitario = IntegrationEngine.ImporteConDecimales(camposDetalle[6], 2);
                                            thisLine.ImporteBonificacion = IntegrationEngine.ImporteConDecimales(camposDetalle[7], 2);
                                            thisLine.ImporteAjuste = IntegrationEngine.ImporteConDecimales(camposDetalle[8], 2);
                                            thisLine.ImporteSubtotal = IntegrationEngine.ImporteConDecimales(camposDetalle[9], 2);
                                            thisLine.ImportePrecioUnitarioMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposDetalle[10], 2);
                                            thisLine.ImporteBonificacionMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposDetalle[11], 2);
                                            thisLine.ImporteAjusteMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposDetalle[12], 2);
                                            thisLine.ImporteSubtotalMonedaFacturacion = IntegrationEngine.ImporteConDecimales(camposDetalle[13], 2);
                                            thisLine.ImporteSubtotalMonedaFacturacionConIVA = IntegrationEngine.ImporteConDecimales(camposDetalle[14], 2);
                                            thisLine.AlicuotaIVA = IntegrationEngine.ImporteConDecimales(camposDetalle[15], 2);
                                            thisLine.IndicadorExentoGravadoNoGravado = camposDetalle[16];
                                            thisLine.Observaciones = camposDetalle[17];
                                            //thisLine.MesPrestacion = camposDetalle[17];

                                            thisDocument.RequestLines.Add(thisLine);
                                        }
                                        line = fileInput.ReadLine();
                                    }
                                    requestBatch.RequestHeaders.Add(thisDocument);
                                    qtyComprobantes++;
                                }
                                else
                                {
                                    //error: el detalle está vacío
                                    sqlEngine.LogError("0", "0", "Leyendo archivo", "El archivo " + fi.Name + " no responde al formato esperado. El detalle está vacío.");
                                    bProcessOK = false;
                                }
                            }
                            else
                            {
                                //error: luego de la cabecera se espera el detalle
                                sqlEngine.LogError("0", "0", "Leyendo archivo", "El archivo " + fi.Name + " no responde al formato esperado. Luego de la cabecera debe venir el detalle.");
                                bProcessOK = false;
                            }
                        }
                        else
                        {
                            //error: la cabecera está vacía
                            sqlEngine.LogError("0", "0", "Leyendo archivo", "El archivo " + fi.Name + " no responde al formato esperado. La cabecera está vacía.");
                            bProcessOK = false;
                        }
                    }
                    else
                    {
                        //error
                        sqlEngine.LogError("0", "0", "Leyendo archivo", "El archivo " + fi.Name + " no responde al formato esperado. Debe comenzar con una cabecera.");
                        bProcessOK = false;
                    }
                }

                if (bProcessOK)
                {
                    requestBatch.CantidadComprobantes = qtyComprobantes.ToString();
                    requestBatch.Total = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", Importe));
                    requestBatch.TotalComprobanteB = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteComprobanteB));
                    requestBatch.TotalExento = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteExento));
                    requestBatch.TotalExentoMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteExentoMonedaFacturacion));
                    requestBatch.TotalGravado = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteGravado));
                    requestBatch.TotalGravadoMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteGravadoMonedaFacturacion));
                    requestBatch.TotalImpuestoLiquidado = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteImpuestoLiquidado));
                    requestBatch.TotalImpuestoLiquidadoMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteImpuestoLiquidadoMonedaFacturacion));
                    requestBatch.TotalImpuestosInternos = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteImpuestosInternos));
                    requestBatch.TotalImpuestosInternosMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteImpuestosInternosMonedaFacturacion));
                    requestBatch.TotalMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteMonedaFacturacion));
                    requestBatch.TotalMonedaFacturacionComprobanteB = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteMonedaFacturacionComprobanteB));
                    requestBatch.TotalNoGravado = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteNoGravado));
                    requestBatch.TotalNoGravadoMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteNoGravadoMonedaFacturacion));
                    requestBatch.TotalPercepciones_PagosCuentaImpuestosNacionales = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImportePercepciones_PagosCuentaImpuestosNacionales));
                    requestBatch.TotalPercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion));
                    requestBatch.TotalPercepcionIIBB = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImportePercepcionIIBB));
                    requestBatch.TotalPercepcionIIBBMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImportePercepcionIIBBMonedaFacturacion));
                    requestBatch.TotalPercepcionImpuestosMunicipales = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImportePercepcionImpuestosMunicipales));
                    requestBatch.TotalPercepcionImpuestosMunicipalesMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImportePercepcionImpuestosMunicipalesMonedaFacturacion));
                    requestBatch.TotalRNI_Percepcion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteRNI_Percepcion));
                    requestBatch.TotalRNI_PercepcionMonedaFacturacion = IntegrationEngine.ChangeDecimalPointToPoint(String.Format("{0:0.00}", ImporteRNI_PercepcionMonedaFacturacion));

                    //TODO: Lote automático donde configurarlo?
                    requestBatch.BatchUniqueId = "AUTO";

                    fileInput.Close();
                }
            }
            catch(Exception ex)
            {
                sqlEngine.LogError("0", "0", "Leyendo archivo", ex.Message);
            }

            return requestBatch;
        }
Beispiel #8
0
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            Settings oSettings = null;

            wsfex.Service afipFEXService = null;
            wsfex.ClsFEXAuthRequest afipObjFEXAuthRequest = null;

            wsfeb.Service afipFEBService = null;
            wsfeb.ClsBFEAuthRequest afipObjFEBAuthRequest = null;

            AfipConnection afipConnFEX = null;
            AfipConnection afipConnFEB = null;

            string strCodigo = string.Empty;
            string strDescripcion = string.Empty;

            FacturaElectronica.DBEngine.SQLEngine sqlEngine = new FacturaElectronica.DBEngine.SQLEngine();

            try
            {
                oSettings = new Settings(ddlEmpresa.SelectedItem.Value);

                //Exportacion
                afipFEXService = new wsfex.Service();
                afipFEXService.Url = oSettings.UrlAFIPwsfex;
                afipObjFEXAuthRequest = new wsfex.ClsFEXAuthRequest();

                afipConnFEX = new AfipConnection("wsfex", oSettings);
                afipConnFEB = new AfipConnection("wsbfe", oSettings);

                //Inicializo el objeto AuthRequest de la Afip
                afipObjFEXAuthRequest.Cuit = afipConnFEX.Cuit;
                afipObjFEXAuthRequest.Sign = afipConnFEX.Sign;
                afipObjFEXAuthRequest.Token = afipConnFEX.Token;

                //Bienes y Servicios
                afipFEBService = new wsfeb.Service();
                afipFEBService.Url = oSettings.UrlAFIPwsbfe;
                afipObjFEBAuthRequest = new wsfeb.ClsBFEAuthRequest();

                if (afipConnFEB.ConnectionErrorDescription == string.Empty)
                {
                    //Inicializo el objeto AuthRequest de la Afip
                    afipObjFEBAuthRequest.Cuit = afipConnFEB.Cuit;
                    afipObjFEBAuthRequest.Sign = afipConnFEB.Sign;
                    afipObjFEBAuthRequest.Token = afipConnFEB.Token;

                    if (chkIncoterms.Checked)
                    {
                        wsfex.FEXResponse_Inc resultInc = afipFEXService.FEXGetPARAM_Incoterms(afipObjFEXAuthRequest);
                        for (int u = 0; u < resultInc.FEXResultGet.Length; u++)
                        {
                            wsfex.ClsFEXResponse_Inc thisValue = (wsfex.ClsFEXResponse_Inc)resultInc.FEXResultGet.GetValue(u);
                            strCodigo = thisValue.Inc_Id.ToString();
                            strDescripcion = thisValue.Inc_Ds.ToString();
                            sqlEngine.InsertarCodigo("AFIPIncoterms", strCodigo, strDescripcion);
                        }
                    }

                    if (chkJurisdiccion.Checked)
                    {
                        //No hay clase en AFIP
                    }

                    if (chkMoneda.Checked)
                    {
                        wsfex.FEXResponse_Mon resultMon = afipFEXService.FEXGetPARAM_MON(afipObjFEXAuthRequest);
                        for (int u = 0; u < resultMon.FEXResultGet.Length; u++)
                        {
                            wsfex.ClsFEXResponse_Mon thisValue = (wsfex.ClsFEXResponse_Mon)resultMon.FEXResultGet.GetValue(u);
                            strCodigo = thisValue.Mon_Id.ToString();
                            strDescripcion = thisValue.Mon_Ds.ToString();
                            sqlEngine.InsertarCodigo("AFIPMoneda", strCodigo, strDescripcion);
                        }
                    }

                    if (chkOperacion.Checked)
                    {
                        //No hay clase en AFIP
                    }

                    if (chkPais.Checked)
                    {
                        wsfex.FEXResponse_DST_pais resultPais = afipFEXService.FEXGetPARAM_DST_pais(afipObjFEXAuthRequest);
                        for (int u = 0; u < resultPais.FEXResultGet.Length; u++)
                        {
                            wsfex.ClsFEXResponse_DST_pais thisValue = (wsfex.ClsFEXResponse_DST_pais)resultPais.FEXResultGet.GetValue(u);
                            strCodigo = thisValue.DST_Codigo.ToString();
                            strDescripcion = thisValue.DST_Ds.ToString();
                            sqlEngine.InsertarCodigo("AFIPPais", strCodigo, strDescripcion);
                        }
                    }

                    if (chkTasaIVA.Checked)
                    {
                        wsfeb.BFEResponse_Tipo_IVA resultTipoIVA = afipFEBService.BFEGetPARAM_Tipo_IVA(afipObjFEBAuthRequest);
                        for (int u = 0; u < resultTipoIVA.BFEResultGet.Length; u++)
                        {
                            wsfeb.ClsBFEResponse_Tipo_IVA thisValue = (wsfeb.ClsBFEResponse_Tipo_IVA)resultTipoIVA.BFEResultGet.GetValue(u);
                            strCodigo = thisValue.IVA_Id.ToString();
                            strDescripcion = thisValue.IVA_Ds.ToString();
                            sqlEngine.InsertarCodigo("AFIPTasaIVA", strCodigo, strDescripcion);
                        }
                    }

                    if (chkTipoCbte.Checked)
                    {
                        wsfex.FEXResponse_Tipo_Cbte resultCbtes = afipFEXService.FEXGetPARAM_Tipo_Cbte(afipObjFEXAuthRequest);
                        for (int u = 0; u < resultCbtes.FEXResultGet.Length; u++)
                        {
                            wsfex.ClsFEXResponse_Tipo_Cbte thisValue = (wsfex.ClsFEXResponse_Tipo_Cbte)resultCbtes.FEXResultGet.GetValue(u);
                            strCodigo = thisValue.Cbte_Id.ToString();
                            strDescripcion = thisValue.Cbte_Ds.ToString();
                            sqlEngine.InsertarCodigo("AFIPTipoComprobante", strCodigo, strDescripcion);
                        }
                    }

                    if (chkTipoDoc.Checked)
                    {
                        wsfeb.BFEResponse_Tipo_doc resultTipoDoc = afipFEBService.BFEGetPARAM_Tipo_doc(afipObjFEBAuthRequest);
                        for (int u = 0; u < resultTipoDoc.BFEResultGet.Length; u++)
                        {
                            wsfeb.ClsBFEResponse_Tipo_doc thisValue = (wsfeb.ClsBFEResponse_Tipo_doc)resultTipoDoc.BFEResultGet.GetValue(u);
                            strCodigo = thisValue.Doc_Id.ToString();
                            strDescripcion = thisValue.Doc_Ds.ToString();
                            sqlEngine.InsertarCodigo("AFIPTipoDocumento", strCodigo, strDescripcion);
                        }
                    }

                    if (chkUnidadMedida.Checked)
                    {
                        wsfex.FEXResponse_Umed resultUmed = afipFEXService.FEXGetPARAM_UMed(afipObjFEXAuthRequest); ;
                        for (int u = 0; u < resultUmed.FEXResultGet.Length; u++)
                        {
                            wsfex.ClsFEXResponse_UMed thisValue = (wsfex.ClsFEXResponse_UMed)resultUmed.FEXResultGet.GetValue(u);
                            strCodigo = thisValue.Umed_Id.ToString();
                            strDescripcion = thisValue.Umed_Ds.ToString();
                            sqlEngine.InsertarCodigo("AFIPUnidadMedida", strCodigo, strDescripcion);
                        }
                    }

                    if (chkTipoResponsable.Checked)
                    {
                        //No hay clase en AFIP
                    }

                    if (chkZona.Checked)
                    {
                        wsfeb.BFEResponse_Zon resultZon = afipFEBService.BFEGetPARAM_Zonas(afipObjFEBAuthRequest);
                        for (int u = 0; u < resultZon.BFEResultGet.Length; u++)
                        {
                            wsfeb.ClsBFEResponse_Zon thisValue = (wsfeb.ClsBFEResponse_Zon)resultZon.BFEResultGet.GetValue(u);
                            strCodigo = thisValue.Zon_Id.ToString();
                            strDescripcion = thisValue.Zon_Ds.ToString();
                            sqlEngine.InsertarCodigo("AFIPZona", strCodigo, strDescripcion);
                        }
                    }

                    if (chkTipoNCM.Checked)
                    {
                        wsfeb.BFEResponse_NCM resultNCM = afipFEBService.BFEGetPARAM_NCM(afipObjFEBAuthRequest);

                        if (resultNCM.BFEResultGet != null)
                        {
                            for (int u = 0; u < resultNCM.BFEResultGet.Length; u++)
                            {
                                wsfeb.ClsBFEResponse_NCM thisValue = (wsfeb.ClsBFEResponse_NCM)resultNCM.BFEResultGet.GetValue(u);
                                strCodigo = thisValue.NCM_Codigo.ToString();
                                strDescripcion = thisValue.NCM_Ds.ToString();
                                sqlEngine.InsertarCodigo("AFIPCodigoNCM", strCodigo, strDescripcion);
                            }
                        }
                        else if (resultNCM.BFEErr != null)
                        {
                            lblErrorMessages.Text = "Error al procesar Tabla AFIPCodigoNCM.<br>Codigo: " + resultNCM.BFEErr.ErrCode.ToString() + "<br>Error: " + resultNCM.BFEErr.ErrMsg;
                        }
                    }
                }
                else
                {
                    string errorMessage = "Error de login con AFIP.";

                    if (afipConnFEB != null && afipConnFEB.ConnectionErrorDescription != string.Empty)
                        errorMessage += "Error: " + afipConnFEB.ConnectionErrorDescription;

                    Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "alert('" + errorMessage + "')", true);
                }
            }
            catch (Exception ex)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "alert('Error: " + ex.Message + "')", true);
            }
            sqlEngine.Close();
        }
Beispiel #9
0
        protected void btnObtenerNum_Click(object sender, EventArgs e)
        {
            Settings oSettings = new Settings(ddlEmpresa.SelectedItem.Value);

            AfipConnection afipConnFex = new AfipConnection("wsfex", oSettings);
            AfipConnection afipConnFe = new AfipConnection("wsfe", oSettings);

            wsfex.Service afipFexService = new wsfex.Service();
            afipFexService.Url = oSettings.UrlAFIPwsfex;

            wsfe.Service feService = new wsfe.Service();
            feService.Url = oSettings.UrlAFIPwsfe;

            wsfex.ClsFEX_LastCMP afipLastEx = new wsfex.ClsFEX_LastCMP();

            wsfe.FEAuthRequest afipObjFEAuthRequest = new wsfe.FEAuthRequest();

            switch (ddlTipoComprobante.SelectedValue)
            {
                case "1":
                case "2":
                case "3":
                case "6":
                case "7":
                case "8":
                    try
                    {
                        lblErrorMessages.Text = "";
                        if (afipConnFe.ConnectionErrorDescription == string.Empty)
                        {
                            //Inicializo el objeto AuthRequest de la Afip
                            afipObjFEAuthRequest.Cuit = afipConnFe.Cuit;
                            afipObjFEAuthRequest.Sign = afipConnFe.Sign;
                            afipObjFEAuthRequest.Token = afipConnFe.Token;

                            wsfe.FERecuperaLastCbteResponse objFERecuperaLastCMPResponse = new wsfe.FERecuperaLastCbteResponse();

                            objFERecuperaLastCMPResponse = feService.FECompUltimoAutorizado(afipObjFEAuthRequest, Convert.ToInt16(ddlSucursales.SelectedValue), Convert.ToInt16(ddlTipoComprobante.SelectedValue));

                            lblNumCbte.Text = (objFERecuperaLastCMPResponse.CbteNro + 1).ToString();
                            lblNumCbte.Text = FillWithCeros(lblNumCbte.Text);
                        }
                        else
                        {
                            lblNumCbte.Text = "XXXXXXXX";
                            lblErrorMessages.Text = "Error de login con AFIP.<br>Error: " + afipConnFe.ConnectionErrorDescription;
                        }
                    }
                    catch (Exception ex)
                    {
                        lblNumCbte.Text = "XXXXXXXX";
                        lblErrorMessages.Text = "Error: " + ex.Message;
                    }

                    //wsfe.FETributoResponse trires = feService.FEParamGetTiposTributos(afipObjFEAuthRequest);
                    break;

                case "19":
                case "20":
                case "21":
                    try
                    {
                        lblErrorMessages.Text = "";
                        if (afipConnFex.ConnectionErrorDescription == string.Empty)
                        {
                            //Inicializo el objeto AuthRequest de la Afip
                            afipLastEx.Cuit = afipConnFex.Cuit;
                            afipLastEx.Sign = afipConnFex.Sign;
                            afipLastEx.Token = afipConnFex.Token;
                            afipLastEx.Pto_venta = Convert.ToInt16(ddlSucursales.SelectedItem.Text);
                            afipLastEx.Tipo_cbte = Convert.ToInt16(ddlTipoComprobante.SelectedItem.Value);

                            wsfex.FEXResponseLast_CMP lastResp = afipFexService.FEXGetLast_CMP(afipLastEx);

                            lblNumCbte.Text = (lastResp.FEXResult_LastCMP.Cbte_nro + 1).ToString();
                            lblNumCbte.Text = FillWithCeros(lblNumCbte.Text);
                        }
                        else
                        {
                            lblNumCbte.Text = "XXXXXXXX";
                            lblErrorMessages.Text = "Error de login con AFIP.<br>Error: " + afipConnFex.ConnectionErrorDescription;
                        }
                    }
                    catch (Exception ex)
                    {
                        lblNumCbte.Text = "XXXXXXXX";
                        lblErrorMessages.Text = "Error: " + ex.Message;
                    }

                    break;
            }
        }
Beispiel #10
0
        private string PrintComprobante(string EmpresaID, string CbteId, TipoDeCopia tipoDeCopia)
        {
            var sqlEngine = new FacturaElectronica.DBEngine.SQLEngine();
            var oEmpresa = new Empresa(EmpresaID);
            var oSettings = new Settings(EmpresaID);
            var strResult = string.Empty;

            var cbteCodigo = 0;
            var puntoVenta = string.Empty;
            var nroComprobante = string.Empty;
            var fileName = "{0}_{1}_{2}_{3}_{4}.pdf"; //EmprCod_TipoDoc_PtoVta_NroDoc_Copia.pdf
            var codigoDocFileName = string.Empty;

            DataTable dtHeader = null;
            DataTable dtDetails = null;
            DataTable dtImpuestos = null;

            try
            {
                //Obtengo el comprobante de la DB.
                dtHeader = Common.GetComprobanteDataTable(CbteId);
                dtDetails = Common.GetComprobanteDetailDataTable(CbteId);
                dtImpuestos = Common.GetComprobanteImpuestoDataTable(CbteId);

                var newPdf = new PrintEngine.Documento();

                if (ComprobanteEncontrado(dtHeader, dtDetails, dtImpuestos))
                {
                    cbteCodigo = Convert.ToInt32(dtHeader.Rows[0]["TipoComprobante"]);
                    puntoVenta = Convert.ToString(dtHeader.Rows[0]["PuntoVenta"]);
                    nroComprobante = Utils.Utils.FillWithCeros(Convert.ToString(dtHeader.Rows[0]["NroComprobanteDesde"]), 8);

                    //Lleno el objeto del reporte, con todos los datos necesarios.
                    newPdf.FillPdfProperties(Convert.ToString(cbteCodigo), tipoDeCopia, oEmpresa, oSettings, dtHeader);

                    //Preparo el nombre del Archivo, con el Nro de Comprobante y el Pto. de Venta.
                    GetTipoDocByAfipCode(cbteCodigo, out codigoDocFileName);

                    fileName = oSettings.PathTemporales + "\\" + string.Format(fileName, EmpresaID, codigoDocFileName, puntoVenta, nroComprobante, tipoDeCopia.ToString());

                    //Llamo al metodo de newPdf que corresponde, segun el tipo de Doc y si es Local o Extranjero.
                    ImprimirComprobanteCorrespondiente(cbteCodigo, fileName, dtDetails, dtImpuestos, tipoDeCopia, newPdf);
                }
                else
                {
                    fileName = string.Empty;
                }
            }
            catch (Exception ex)
            {
                strResult = ex.Message + "FechaComprobante: " + dtHeader.Rows[0]["FechaComprobante"].ToString() + " | FechaVencimiento: " + dtHeader.Rows[0]["FechaVencimiento"].ToString();
                sqlEngine.LogError(dtHeader.Rows[0]["SQLID"].ToString(), "0", "Imprimiendo Factura", "Error: " + ex.Message);
            }

            return fileName;
        }
Beispiel #11
0
        private bool BuscarEquivalencias(ref RequestBatch loteDocs, Settings oSettings, ref string strEquivalenciaErrorFields)
        {
            string resultado = string.Empty;
            string strSQLID = string.Empty;

            bool bEquivalenciaError = false;

            try
            {
                foreach (RequestHeader thisHeader in loteDocs.RequestHeaders)
                {
                    strSQLID = thisHeader.SQLID;

                    resultado = sqlEngine.ObtenerEquivalencia("EquivAFIPTipoComprobante", oSettings.EmpresaID, thisHeader.TipoComprobante);
                    if (resultado == "")
                    {
                        bEquivalenciaError = true;
                        strEquivalenciaErrorFields += "Tipo Comprobante: " + thisHeader.TipoComprobante + "; ";
                        sqlEngine.LogError(thisHeader.SQLID, "0", "Equivalencias", "No se encontró la equivalencia con AFIP del tipo de comprobante (" + thisHeader.TipoComprobante + ")");
                    }
                    else
                    {
                        thisHeader.TipoComprobante = resultado;
                    }

                    //PAIS TRANSACCIONES 0, 1, 2 y 3
                    resultado = sqlEngine.ObtenerEquivalencia("EquivAFIPPais", oSettings.EmpresaID, thisHeader.CompradorPais);
                    if (resultado == "")
                    {
                        bEquivalenciaError = true;
                        strEquivalenciaErrorFields += "Pais Comprador(" + thisHeader.CompradorPais + "); ";
                        sqlEngine.LogError(thisHeader.SQLID, "0", "Equivalencias", "No se encontró la equivalencia con AFIP del país (" + thisHeader.CompradorPais + ")");
                    }
                    else
                    {
                        thisHeader.CompradorPais = resultado;
                    }

                    //MONEDA TRANSACCIONES 0, 1, 2 y 3
                    resultado = sqlEngine.ObtenerEquivalencia("EquivAFIPMoneda",oSettings.EmpresaID, thisHeader.CodigoMoneda);
                    if (resultado == "")
                    {
                        bEquivalenciaError = true;
                        strEquivalenciaErrorFields += "Codigo Moneda(" + thisHeader.CodigoMoneda + "); ";
                        sqlEngine.LogError(thisHeader.SQLID, "0", "Equivalencias", "No se encontró la equivalencia con AFIP de la moneda (" + thisHeader.CodigoMoneda + ")");
                    }
                    else
                    {
                        thisHeader.CodigoMoneda = resultado;
                    }

                    //TIPO RESPONSABLE TRANSACCIONES 0, 1, 2 y 3
                    resultado = sqlEngine.ObtenerEquivalencia("EquivAFIPTipoResponsable", oSettings.EmpresaID, thisHeader.CompradorTipoResponsable);
                    if (resultado == "")
                    {
                        bEquivalenciaError = true;
                        strEquivalenciaErrorFields += "Tipo Responsable Comprador(" + thisHeader.CompradorTipoResponsable + "); ";
                        sqlEngine.LogError(thisHeader.SQLID, "0", "Equivalencias", "No se encontró la equivalencia con AFIP del tipo de responsable (" + thisHeader.CompradorTipoResponsable + ")");
                    }
                    else
                    {
                        thisHeader.CompradorTipoResponsable = resultado;
                    }

                    //SOLO PARA TRANSACCIONES 0 y 1 (BIENES Y SERVICIOS)
                    if (thisHeader.TipoTransaccion == "0" || thisHeader.TipoTransaccion == "1")
                    {
                        //CODIGO DOCUMENTO
                        resultado = sqlEngine.ObtenerEquivalencia("EquivAFIPCodigoDocumento", oSettings.EmpresaID, thisHeader.CompradorCodigoDocumento);
                        if (resultado == "")
                        {
                            bEquivalenciaError = true;
                            strEquivalenciaErrorFields += "Codigo Documento Comprador(" + thisHeader.CompradorCodigoDocumento + "); ";
                            sqlEngine.LogError(thisHeader.SQLID, "0", "Equivalencias", "No se encontró la equivalencia con AFIP del Código de documento (" + thisHeader.CompradorCodigoDocumento + ")");
                        }
                        else
                        {
                            thisHeader.CompradorCodigoDocumento = resultado;
                        }
                    }

                    //SOLO PARA TRANSACCIONES 3 (EXPORTACION)
                    if (thisHeader.TipoTransaccion == "3")
                    {
                        resultado = sqlEngine.ObtenerEquivalencia("EquivAFIPIncoterms", oSettings.EmpresaID, thisHeader.IncoTerms);
                        if (resultado == "")
                        {
                            bEquivalenciaError = true;
                            strEquivalenciaErrorFields += "Incoterms(" + thisHeader.IncoTerms + "); ";
                            sqlEngine.LogError(thisHeader.SQLID, "0", "Equivalencias", "No se encontró la equivalencia con AFIP del incoterms (" + thisHeader.IncoTerms + ")");
                        }
                        else
                        {
                            thisHeader.IncoTerms = resultado;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                sqlEngine.LogError(strSQLID, "0", "Equivalencias", "Error no identificado: " + ex.Message);
                bEquivalenciaError = true;
            }
            return bEquivalenciaError;
        }
Beispiel #12
0
        protected void Page_Load(object sender, EventArgs e)
        {
            chkJurisdiccion.Enabled = false;
            chkOperacion.Enabled = false;
            chkTipoResponsable.Enabled = false;

            if (!IsPostBack)
            {
                lblBienes.ForeColor = System.Drawing.Color.Black;
                lblBienes.Text = "Sin Verificar";

                lblCapital.ForeColor = System.Drawing.Color.Black;
                lblCapital.Text = "Sin Verificar";

                lblExportacion.ForeColor = System.Drawing.Color.Black;
                lblExportacion.Text = "Sin Verificar";

                lblWSAABienes.ForeColor = System.Drawing.Color.Black;
                lblWSAABienes.Text = "Sin verificar";

                lblWSAACapital.ForeColor = System.Drawing.Color.Black;
                lblWSAACapital.Text = "Sin verificar";

                lblWSAAExportacion.ForeColor = System.Drawing.Color.Black;
                lblWSAAExportacion.Text = "Sin verificar";

                FillEmpresas();

                Settings oSettings = new Settings(ddlEmpresa.SelectedItem.Value);

                FillSucursales(oSettings.EmpresaID);
            }
        }
Beispiel #13
0
 public AfipFEX(ref wsfex.Service afipFexService, ref wsfex.ClsFEXAuthRequest afipObjFEXAuthRequest, Settings oSettings)
 {
     fexService = afipFexService;
     fexService.Url = oSettings.UrlAFIPwsfex;
     objFEXAuthRequest = afipObjFEXAuthRequest;
 }
Beispiel #14
0
        //TODO: correr en otro thread o utilizar updatepanel para mostrar barra de estado
        protected void CheckAfipFebService(Settings oSettings)
        {
            try
            {
                wsfeb.Service afipFebService = new wsfeb.Service();
                afipFebService.Url = oSettings.UrlAFIPwsbfe;

                wsfeb.DummyResponse dumResp = afipFebService.BFEDummy();

                if (dumResp.AppServer == "OK" && dumResp.AuthServer == "OK" && dumResp.DbServer == "OK")
                {
                    lblCapital.ForeColor = System.Drawing.Color.Green;
                    lblCapital.Text = "OK";
                }
                else
                {
                    lblCapital.ForeColor = System.Drawing.Color.Red;
                    lblCapital.Text = "ERROR";
                }
            }
            catch
            {
                lblCapital.ForeColor = System.Drawing.Color.Red;
                lblCapital.Text = "ERROR";
            }
        }
Beispiel #15
0
 //TODO: correr en otro thread o utilizar updatepanel para mostrar barra de estado
 protected string CheckAfipLogin(string serviceID, Settings oSettings)
 {
     lblErrorMessages.Text = "";
     AfipConnection.ResetCurrentAfipConnection(serviceID, oSettings);
     AfipConnection afipConn = new AfipConnection(serviceID, oSettings);
     if (afipConn.ConnectionErrorDescription == string.Empty)
     {
         return "OK";
     }
     else
     {
         if (afipConn.ConnectionErrorDescription != string.Empty)
             return "ERROR: " + afipConn.ConnectionErrorDescription;
         else
             return "ERROR de Conexion.";
     }
 }
Beispiel #16
0
        public RequestBatch ProcessData(FileInfo fi, Settings oSettings)
        {
            RequestBatch requestBatch = null;

            StreamReader fileInput = null;

            string line = string.Empty;

            try
            {
                //TODO: Espero que el SO libere el archivo
                while (Utils.Utils.FileIsInUse(fi))
                {
                }

                if (File.Exists(fi.FullName))
                {
                    //Determinar el tipo de comprobante basado en el nombre del archivo (left,2)
                    try
                    {
                        fileInput = new StreamReader(fi.FullName);

                        if ((line = fileInput.ReadLine()) != null)
                        {
                            if (line == "CABECERA")
                            {
                                if ((line = fileInput.ReadLine()) != null)
                                {
                                    fileInput.Close();

                                    //Identificar el tipo de archivo
                                    string tipoArchivo = line.Substring(0, 1);

                                    //Si está vacío asumo que es blanco
                                    if (tipoArchivo == ";")
                                        tipoArchivo = " ";

                                    if (tipoArchivo == " " || tipoArchivo == "1" || tipoArchivo == "2" || tipoArchivo == "3")
                                    {
                                        requestBatch = ProcesarLoteComprobantes(fi, oSettings);
                                    }
                                    else
                                    {
                                        ResponseError(null, fi, "E1", "El tipo de transacción es erróneo. Tipo de Transacción: '" + tipoArchivo + "'", oSettings);
                                    }
                                }
                                else
                                {
                                    sqlEngine.LogError("0", "0", "Identificando transacción", fi.Name + ": archivo no válido. Sin contenido de cabecera.");
                                }
                            }
                            else
                            {
                                sqlEngine.LogError("0", "0", "Identificando transacción", fi.Name + ": archivo no válido. La primera línea debe ser 'CABECERA'.");
                            }
                        }
                        else
                        {
                            sqlEngine.LogError("0", "0", "Identificando transacción", fi.Name + ": archivo no válido.");
                        }
                    }
                    catch (Exception ex)
                    {
                        sqlEngine.LogError("0", "0", "Identificando transacción", "Error no identificado 1: " + ex.Message);
                    }
                    finally
                    {
                        if (fileInput != null)
                            fileInput.Close();
                    }

                    fi.CopyTo(oSettings.PathHistorico + @"\" + fi.Name, true);

                    //Espero que el SO libere el file
                    while (Utils.Utils.FileIsInUse(fi))
                    {
                    }
                    fi.Delete();
                }
            }
            catch (Exception ex)
            {
                sqlEngine.LogError("0", "0", "Identificando transacción", "Error no identificado 2: " + ex.Message);
            }

            return requestBatch;
        }
Beispiel #17
0
        public void ProcessResponse(ResponseBatch rbResponse, Settings oSettings)
        {
            XmlDocument xmlResponse = new XmlDocument();

            try
            {
                xmlResponse.LoadXml(rbResponse.GetXMLString());

                //Generar para debug formato xml
                xmlResponse.Save(oSettings.PathDebug + @"\RESP_ " + rbResponse.BatchUniqueId + "_" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + ".xml");

                try
                {
                    XmlDocument respSEW = new XmlDocument();
                    XmlElement xmlElem = respSEW.CreateElement("comprobantes");
                    XmlNode rootNode = respSEW.AppendChild(xmlElem);

                    XmlNode detailsNode = null;
                    XmlNode comprobanteNode = null;
                    XmlAttribute comprobanteAttr = null;

                    string fileNameRespuesta = @"RESP_ " + rbResponse.BatchUniqueId + "_" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + ".xml";
                    string strFolderName = string.Empty;

                    switch (rbResponse.ResponseHeaders[0].TipoTransaccion)
                    {
                        case "0":
                        case "1":
                            {
                                #region Bienes y Servicios

                                detailsNode = respSEW.CreateElement("Resultado");
                                detailsNode.InnerText = rbResponse.Resultado;
                                xmlElem.AppendChild(detailsNode);

                                detailsNode = respSEW.CreateElement("Motivo");
                                detailsNode.InnerText = rbResponse.Motivo;
                                xmlElem.AppendChild(detailsNode);

                                detailsNode = respSEW.CreateElement("MotivoDescripcion");
                                detailsNode.InnerText = rbResponse.MotivoDescripcion;
                                xmlElem.AppendChild(detailsNode);

                                detailsNode = respSEW.CreateElement("Reproceso");
                                detailsNode.InnerText = rbResponse.Reproceso;
                                xmlElem.AppendChild(detailsNode);

                                detailsNode = respSEW.CreateElement("SonServicios");
                                detailsNode.InnerText = rbResponse.SonServicios;
                                xmlElem.AppendChild(detailsNode);

                                //detailsNode = respSEW.CreateElement("CodigoError");
                                //detailsNode.InnerText = rbResponse.CodigoError;
                                //xmlElem.AppendChild(detailsNode);

                                //detailsNode = respSEW.CreateElement("MensajeError");
                                //detailsNode.InnerText = rbResponse.MensajeError;
                                //xmlElem.AppendChild(detailsNode);

                                foreach (ResponseHeader thisResponse in rbResponse.ResponseHeaders)
                                {
                                    //Actualizar el documento con el nombre del archivo de respuesta
                                    sqlEngine.UpdateCabeceraNombreObjetoSalida(thisResponse.SQLID, fileNameRespuesta.Replace(".txt", string.Empty));

                                    xmlElem = respSEW.CreateElement("comprobante");
                                    comprobanteAttr = respSEW.CreateAttribute("idsolicitud");
                                    comprobanteAttr.Value = thisResponse.NroComprobanteDesde;
                                    xmlElem.Attributes.Append(comprobanteAttr);
                                    comprobanteNode = rootNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("nro");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.NroComprobanteDesde));
                                    comprobanteNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("tipocodaut");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.LetraComprobante));
                                    comprobanteNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("codaut");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.CAE));
                                    comprobanteNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("vtocodaut");
                                    if (thisResponse.FechaVencimiento.Length == 8)
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.FechaVencimiento.Substring(0, 4) + "-" + thisResponse.FechaVencimiento.Substring(4, 2) + "-" + thisResponse.FechaVencimiento.Substring(6, 2)));
                                    comprobanteNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("Tipo_cbte");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.TipoComprobante));
                                    comprobanteNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("Punto_vta");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.PuntoVenta));
                                    comprobanteNode.AppendChild(xmlElem);

                                    if (thisResponse.Resultado == "A" || thisResponse.Resultado == "R")
                                    {
                                        xmlElem = respSEW.CreateElement("codtarea");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.Motivo));
                                        comprobanteNode.AppendChild(xmlElem);

                                        switch (thisResponse.Resultado)
                                        {
                                            case "A":
                                                xmlElem = respSEW.CreateElement("msgerror");
                                                xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.MotivoDescripcion));
                                                comprobanteNode.AppendChild(xmlElem);

                                                xmlElem = respSEW.CreateElement("estadocmp");
                                                xmlElem.AppendChild(respSEW.CreateTextNode("AC"));
                                                comprobanteNode.AppendChild(xmlElem);

                                                break;

                                            case "R":
                                                xmlElem = respSEW.CreateElement("msgerror");
                                                xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.MotivoDescripcion + " - (Ultimo Comprobante Utilizado: " + thisResponse.UltimoNroComprobanteUsado + ")"));
                                                comprobanteNode.AppendChild(xmlElem);

                                                xmlElem = respSEW.CreateElement("estadocmp");
                                                xmlElem.AppendChild(respSEW.CreateTextNode("NP"));
                                                comprobanteNode.AppendChild(xmlElem);

                                                sqlEngine.LogError(thisResponse.SQLID, "0", thisResponse.Motivo, thisResponse.MotivoDescripcion + " - (Ultimo Comprobante Utilizado: " + thisResponse.UltimoNroComprobanteUsado + ")");

                                                break;
                                        }
                                    }
                                    else
                                    {
                                        xmlElem = respSEW.CreateElement("codtarea");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.CodigoError));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("msgerror");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.MensajeError));
                                        comprobanteNode.AppendChild(xmlElem);

                                        if (rbResponse.CodigoError.Length > 0 && rbResponse.CodigoError != "0" && rbResponse.CodigoError != "Equivalencias")
                                        {
                                            xmlElem = respSEW.CreateElement("estadocmp");
                                            xmlElem.AppendChild(respSEW.CreateTextNode("E"));
                                            comprobanteNode.AppendChild(xmlElem);

                                            sqlEngine.LogError(thisResponse.SQLID, "0", rbResponse.CodigoError, rbResponse.MensajeError);
                                        }
                                        else
                                        {
                                            xmlElem = respSEW.CreateElement("estadocmp");
                                            xmlElem.AppendChild(respSEW.CreateTextNode("E1"));
                                            comprobanteNode.AppendChild(xmlElem);
                                        }
                                    }
                                }

                                //Guardo la respuesta sino hay errores
                                if (respSEW.SelectSingleNode("comprobantes/comprobante/nro") != null && respSEW.SelectSingleNode("comprobantes/comprobante/nro").InnerText != string.Empty &&
                                    respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut") != null && respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut").InnerText != string.Empty &&
                                    respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte").InnerText != string.Empty &&
                                    respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta").InnerText != string.Empty)
                                {
                                    respSEW.Save(oSettings.Salida + "\\" + fileNameRespuesta.Replace(".txt", string.Empty));
                                }
                                #endregion
                            }
                            break;

                        case "2":
                            {
                                #region Bienes de Capital

                                if (rbResponse.ResponseHeaders != null)
                                {
                                    foreach (ResponseHeader thisResponse in rbResponse.ResponseHeaders)
                                    {
                                        //Actualizar el documento con el nombre del archivo de respuesta
                                        sqlEngine.UpdateCabeceraNombreObjetoSalida(thisResponse.SQLID, fileNameRespuesta.Replace(".txt", string.Empty));

                                        xmlElem = respSEW.CreateElement("comprobante");
                                        comprobanteAttr = respSEW.CreateAttribute("idsolicitud");
                                        comprobanteAttr.Value = thisResponse.NroComprobanteDesde;
                                        xmlElem.Attributes.Append(comprobanteAttr);
                                        comprobanteNode = rootNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("nro");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.NroComprobanteDesde));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("tipocodaut");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.LetraComprobante));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("codaut");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.CAE));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("vtocodaut");
                                        if (thisResponse.FechaVencimiento.Length > 0)
                                            xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.FechaVencimiento.Substring(0, 4) + "-" + thisResponse.FechaVencimiento.Substring(4, 2) + "-" + thisResponse.FechaVencimiento.Substring(6, 2)));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("Tipo_cbte");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.TipoComprobante));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("Punto_vta");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.PuntoVenta));
                                        comprobanteNode.AppendChild(xmlElem);

                                        if (rbResponse.Resultado == "A" || rbResponse.Resultado == "R")
                                        {
                                            switch (rbResponse.Resultado)
                                            {
                                                case "A":
                                                    xmlElem = respSEW.CreateElement("estadocmp");
                                                    xmlElem.AppendChild(respSEW.CreateTextNode("AC"));
                                                    comprobanteNode.AppendChild(xmlElem);

                                                    break;

                                                case "R":

                                                    if (rbResponse.ResponseHeaders[0].Motivo != string.Empty || rbResponse.ResponseHeaders[0].MotivoDescripcion != string.Empty && rbResponse.CodigoError != "Equivalencias")
                                                    {
                                                        xmlElem = respSEW.CreateElement("estadocmp");
                                                        xmlElem.AppendChild(respSEW.CreateTextNode("NP"));
                                                        comprobanteNode.AppendChild(xmlElem);

                                                        sqlEngine.LogError(thisResponse.SQLID, "0", rbResponse.ResponseHeaders[0].Motivo, rbResponse.ResponseHeaders[0].MotivoDescripcion + " - (Ultimo Comprobante Utilizado: " + rbResponse.ResponseHeaders[0].UltimoNroComprobanteUsado + ")");
                                                    }
                                                    else
                                                    {
                                                        xmlElem = respSEW.CreateElement("estadocmp");
                                                        xmlElem.AppendChild(respSEW.CreateTextNode("E1"));
                                                        comprobanteNode.AppendChild(xmlElem);

                                                        //sqlEngine.LogError(thisResponse.SQLID, "0", responseBatch.CodigoError, responseBatch.MensajeError);
                                                    }

                                                    break;
                                            }
                                        }
                                        else
                                        {
                                            xmlElem = respSEW.CreateElement("estadocmp");
                                            xmlElem.AppendChild(respSEW.CreateTextNode("E"));
                                            comprobanteNode.AppendChild(xmlElem);
                                        }
                                    }
                                }
                                else
                                {
                                    xmlElem = respSEW.CreateElement("comprobante");
                                    comprobanteAttr = respSEW.CreateAttribute("idsolicitud");
                                    comprobanteAttr.Value = rbResponse.ResponseHeaders[0].NroComprobanteDesde;
                                    xmlElem.Attributes.Append(comprobanteAttr);
                                    comprobanteNode = rootNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("nro");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].NroComprobanteDesde));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("tipocodaut");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].LetraComprobante));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("codaut");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(""));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("vtocodaut");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(""));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("Tipo_cbte");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].TipoComprobante));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("Punto_vta");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].PuntoVenta));
                                    comprobanteNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("estadocmp");
                                    xmlElem.AppendChild(respSEW.CreateTextNode("NP"));
                                    comprobanteNode.AppendChild(xmlElem);

                                    sqlEngine.LogError(rbResponse.ResponseHeaders[0].SQLID, "0", rbResponse.ResponseHeaders[0].Motivo, rbResponse.ResponseHeaders[0].MotivoDescripcion + " - (Ultimo Comprobante Utilizado: " + rbResponse.ResponseHeaders[0].UltimoNroComprobanteUsado + ")");
                                }

                                //revisar si el motivo esta vacio o es 13, el 13 es solo informativo
                                if (rbResponse.CodigoError == "" && (rbResponse.ResponseHeaders[0].Motivo == "" || rbResponse.ResponseHeaders[0].Motivo == "13"))
                                {
                                    xmlElem = respSEW.CreateElement("codtarea");
                                    xmlElem.AppendChild(respSEW.CreateTextNode("0"));
                                    comprobanteNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("msgerror");
                                    xmlElem.AppendChild(respSEW.CreateTextNode("OK"));
                                    comprobanteNode.AppendChild(xmlElem);
                                }
                                else
                                {
                                    if (rbResponse.ResponseHeaders[0].Motivo != string.Empty)
                                    {
                                        if (rbResponse.ResponseHeaders[0].Motivo.IndexOf("11") > -1)
                                        {
                                            xmlElem = respSEW.CreateElement("codtarea");
                                            xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].Motivo));
                                            comprobanteNode.AppendChild(xmlElem);

                                            xmlElem = respSEW.CreateElement("msgerror");
                                            xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].MotivoDescripcion + " - (Ultimo Comprobante Utilizado: " + rbResponse.ResponseHeaders[0].UltimoNroComprobanteUsado + ")"));
                                            comprobanteNode.AppendChild(xmlElem);
                                        }
                                    }
                                    else
                                    {
                                        xmlElem = respSEW.CreateElement("codtarea");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.CodigoError));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("msgerror");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.MensajeError));
                                        comprobanteNode.AppendChild(xmlElem);
                                    }
                                }

                                //Guardo la respuesta sino hay errores
                                if (respSEW.SelectSingleNode("comprobantes/comprobante/nro") != null && respSEW.SelectSingleNode("comprobantes/comprobante/nro").InnerText != string.Empty &&
                                    respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut") != null && respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut").InnerText != string.Empty &&
                                    respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte").InnerText != string.Empty &&
                                    respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta").InnerText != string.Empty)
                                {
                                    respSEW.Save(oSettings.Salida + "\\" + fileNameRespuesta.Replace(".txt", string.Empty));
                                }

                                #endregion
                            }
                            break;

                        case "3":
                            {
                                #region Exportacion

                                //Si hay error la AFIP no devuelve valores, por lo que se agregan en base a la solicitud o vacíos
                                if (rbResponse.ResponseHeaders[0].CAE.Length > 4)
                                {
                                    foreach (ResponseHeader thisResponse in rbResponse.ResponseHeaders)
                                    {
                                        xmlElem = respSEW.CreateElement("comprobante");
                                        comprobanteAttr = respSEW.CreateAttribute("idsolicitud");
                                        comprobanteAttr.Value = thisResponse.NroComprobanteDesde;
                                        xmlElem.Attributes.Append(comprobanteAttr);
                                        comprobanteNode = rootNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("nro");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.NroComprobanteDesde));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("tipocodaut");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.LetraComprobante));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("codaut");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.CAE));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("vtocodaut");
                                        if (thisResponse.FechaVencimiento.Length == 8)
                                            xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.FechaVencimiento.Substring(0, 4) + "-" + thisResponse.FechaVencimiento.Substring(4, 2) + "-" + thisResponse.FechaVencimiento.Substring(6, 2)));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("Tipo_cbte");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.TipoComprobante));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("Punto_vta");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.PuntoVenta));
                                        comprobanteNode.AppendChild(xmlElem);

                                        if (rbResponse.Resultado == "A" || rbResponse.Resultado == "R")
                                        {
                                            switch (rbResponse.Resultado)
                                            {
                                                case "A":
                                                    xmlElem = respSEW.CreateElement("estadocmp");
                                                    xmlElem.AppendChild(respSEW.CreateTextNode("AC"));
                                                    comprobanteNode.AppendChild(xmlElem);

                                                    break;

                                                case "R":
                                                    xmlElem = respSEW.CreateElement("estadocmp");
                                                    xmlElem.AppendChild(respSEW.CreateTextNode("NP"));
                                                    comprobanteNode.AppendChild(xmlElem);

                                                    sqlEngine.LogError(rbResponse.ResponseHeaders[0].SQLID, "0", rbResponse.ResponseHeaders[0].Motivo, rbResponse.ResponseHeaders[0].MotivoDescripcion);

                                                    break;
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    xmlElem = respSEW.CreateElement("comprobante");
                                    comprobanteAttr = respSEW.CreateAttribute("idsolicitud");
                                    comprobanteAttr.Value = rbResponse.ResponseHeaders[0].NroComprobanteDesde;
                                    xmlElem.Attributes.Append(comprobanteAttr);
                                    comprobanteNode = rootNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("nro");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].NroComprobanteDesde));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("tipocodaut");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].LetraComprobante));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("codaut");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(""));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("vtocodaut");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(""));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("Tipo_cbte");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].TipoComprobante));
                                    comprobanteNode.AppendChild(xmlElem);
                                    xmlElem = respSEW.CreateElement("Punto_vta");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].PuntoVenta));
                                    comprobanteNode.AppendChild(xmlElem);

                                    if (rbResponse.CodigoError != "Equivalencias")
                                    {
                                        sqlEngine.LogError(rbResponse.ResponseHeaders[0].SQLID, "0", rbResponse.CodigoError, rbResponse.MensajeError);

                                        xmlElem = respSEW.CreateElement("estadocmp");
                                        xmlElem.AppendChild(respSEW.CreateTextNode("NP"));
                                        comprobanteNode.AppendChild(xmlElem);
                                    }
                                    else
                                    {
                                        xmlElem = respSEW.CreateElement("estadocmp");
                                        xmlElem.AppendChild(respSEW.CreateTextNode("E1"));
                                        comprobanteNode.AppendChild(xmlElem);
                                    }
                                }

                                //revisar si el motivo esta vacio o es 13, el 13 es solo informativo
                                if (rbResponse.ResponseHeaders[0].Motivo == string.Empty || rbResponse.CodigoError != string.Empty)
                                {
                                    xmlElem = respSEW.CreateElement("codtarea");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.CodigoError));
                                    comprobanteNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("msgerror");
                                    xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.MensajeError));
                                    comprobanteNode.AppendChild(xmlElem);
                                }
                                else if (rbResponse.ResponseHeaders[0].Motivo == "13")
                                {
                                    xmlElem = respSEW.CreateElement("codtarea");
                                    xmlElem.AppendChild(respSEW.CreateTextNode("0"));
                                    comprobanteNode.AppendChild(xmlElem);

                                    xmlElem = respSEW.CreateElement("msgerror");
                                    xmlElem.AppendChild(respSEW.CreateTextNode("OK"));
                                    comprobanteNode.AppendChild(xmlElem);
                                }
                                else
                                {
                                    if (rbResponse.ResponseHeaders[0].Motivo.IndexOf("11") > -1)
                                    {
                                        xmlElem = respSEW.CreateElement("codtarea");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].Motivo));
                                        comprobanteNode.AppendChild(xmlElem);

                                        xmlElem = respSEW.CreateElement("msgerror");
                                        xmlElem.AppendChild(respSEW.CreateTextNode(rbResponse.ResponseHeaders[0].MotivoDescripcion + " - (Ultimo Comprobante Utilizado: " + rbResponse.ResponseHeaders[0].UltimoNroComprobanteUsado + ")"));
                                        comprobanteNode.AppendChild(xmlElem);
                                    }
                                }

                                //Actualizar el documento con el nombre del archivo de respuesta
                                sqlEngine.UpdateCabeceraNombreObjetoSalida(rbResponse.ResponseHeaders[0].SQLID, fileNameRespuesta.Replace(".txt", string.Empty));

                                //Guardo la respuesta sino hay errores
                                if (respSEW.SelectSingleNode("comprobantes/comprobante/nro") != null && respSEW.SelectSingleNode("comprobantes/comprobante/nro").InnerText != string.Empty &&
                                    respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut") != null && respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut").InnerText != string.Empty &&
                                    respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte").InnerText != string.Empty &&
                                    respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta").InnerText != string.Empty)
                                {
                                    respSEW.Save(oSettings.Salida + "\\" + fileNameRespuesta.Replace(".txt", string.Empty));
                                }
                                #endregion
                            }
                            break;

                        default:
                            return;
                    }
                }
                catch(Exception ex)
                {
                    sqlEngine.LogError("0", "0", "File Engine", ex.Message);
                }
            }
            catch
            {
                sqlEngine.LogError("0", "0", "File Engine", "El resultado no es un mensaje xml.");
            }
        }
Beispiel #18
0
        public string ProcesarLoteFacturasBienesCapital(string EmpresaID, string xmlDocument)
        {
            #region Inicialización

            Settings oSettings = new Settings(EmpresaID);

            wsbfe.Service afipBfexService = new wsbfe.Service();
            afipBfexService.Url = oSettings.UrlAFIPwsbfe;

            wsbfe.ClsBFEAuthRequest afipObjBFEAuthRequest = new wsbfe.ClsBFEAuthRequest();
            wsbfe.BFEResponseAuthorize bfeResponseAuthorize = new wsbfe.BFEResponseAuthorize();

            ResponseBatch batchResponse = new ResponseBatch();
            RequestBatch loteDocs = new RequestBatch();

            string SQLID = "0";
            string estadoDocumento = "";
            string cae = "";
            string FechaVencimiento = "";
            string strEquivalenciaErrorFields = string.Empty;

            bool bRegistrarInicio = false;
            bool bEquivalenciaError = false;

            //Cargar el lote recibido
            loteDocs.LoadXMLString(xmlDocument);

            #endregion

            #region Registrar pedido

            try
            {
                bRegistrarInicio = sqlEngine.LogBatchStart(ref loteDocs);

                SQLID = loteDocs.RequestHeaders[0].SQLID;

                //DEBUG LINE
                if (Convert.ToBoolean(oSettings.ActivarDebug))
                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(batchResponse), oSettings.PathDebug + "\\" + SQLID + "-FERequestBatch-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");
            }
            catch (Exception ex)
            {
                bRegistrarInicio = false;
                sqlEngine.LogError(SQLID, "0", "Procesando lote", "Error: " + ex.Message);
            }

            #endregion

            if (bRegistrarInicio)
            {
                #region Verificar Login con AFIP

                AfipConnection afipConn = new AfipConnection("wsbfe", oSettings);
                if (afipConn.ConnectionErrorDescription == string.Empty)
                {
                    //Inicializo el objeto AuthRequest de la Afip
                    afipObjBFEAuthRequest.Cuit = afipConn.Cuit;
                    afipObjBFEAuthRequest.Sign = afipConn.Sign;
                    afipObjBFEAuthRequest.Token = afipConn.Token;
                }
                else
                {
                    try
                    {
                        sqlEngine.LogError(SQLID, "0", "AfipConnection", afipConn.ConnectionErrorDescription);

                        sqlEngine.LogBatchEnd(SQLID, "Error", cae, FechaVencimiento);
                    }
                    catch (Exception ex)
                    {
                        sqlEngine.LogError(SQLID, "0", "FEService-AFIP Login", "Error: " + ex.Message);
                    }
                }

                AfipBFE afipBFE = new AfipBFE(ref afipBfexService, ref afipObjBFEAuthRequest, oSettings);

                #endregion

                if (afipConn.ConnectionErrorDescription == string.Empty)
                {
                    #region Buscar Equivalencias

                    bEquivalenciaError = BuscarEquivalencias(ref loteDocs, oSettings, ref strEquivalenciaErrorFields);

                    #endregion

                    if (!bEquivalenciaError)
                    {
                        #region Realizar Validaciones
                        #endregion

                        #region Hacer el pedido a AFIP

                        try
                        {
                            if (afipConn.IsConnected)
                            {
                                bfeResponseAuthorize = afipBFE.BFEAuthorize(loteDocs, oSettings);

                                if (bfeResponseAuthorize.BFEErr == null)
                                {
                                    sqlEngine.LogError(SQLID, "0", "Respuesta AFIP", "AFIP no pudo procesar por un error previo. Vea el log de errores.");
                                    bfeResponseAuthorize.BFEErr = new wsbfe.ClsBFEErr();
                                    bfeResponseAuthorize.BFEErr.ErrCode = 0;
                                    bfeResponseAuthorize.BFEErr.ErrMsg = "AFIP no pudo procesar por un error previo. Vea el log de errores.";
                                }
                            }
                            else
                            {
                                sqlEngine.LogError(SQLID, "0", "Respuesta AFIP", "Sin Conexion. Descripcion: " + afipConn.ConnectionErrorDescription);
                                bfeResponseAuthorize.BFEErr = new wsbfe.ClsBFEErr();
                                bfeResponseAuthorize.BFEErr.ErrCode = 0;
                                bfeResponseAuthorize.BFEErr.ErrMsg = afipConn.ConnectionErrorDescription;
                            }
                        }
                        catch (Exception ex)
                        {
                            sqlEngine.LogError(SQLID, "0", "Respuesta AFIP", "Error: " + ex.Message);
                        }

                        #endregion
                    }
                }

                #region Armar y devolver respuesta

                //Armar info del lote
                if (bfeResponseAuthorize.BFEResultAuth != null && bfeResponseAuthorize.BFEResultAuth.Cae != null )
                {
                    batchResponse.BatchUniqueId = loteDocs.BatchUniqueId;
                    batchResponse.BatchUniqueId = bfeResponseAuthorize.BFEResultAuth.Id.ToString();
                    batchResponse.Resultado = bfeResponseAuthorize.BFEResultAuth.Resultado;
                    batchResponse.Reproceso = bfeResponseAuthorize.BFEResultAuth.Reproceso;
                    batchResponse.CUITInformante = bfeResponseAuthorize.BFEResultAuth.Cuit.ToString();
                    batchResponse.CantidadComprobantes = "1";

                    //Armar info del documento
                    ResponseHeader thisHeader = new ResponseHeader();

                    thisHeader.CAE = bfeResponseAuthorize.BFEResultAuth.Cae;
                    thisHeader.NroComprobanteDesde = loteDocs.RequestHeaders[0].NroComprobanteDesde.ToString();
                    thisHeader.NroComprobanteHasta = loteDocs.RequestHeaders[0].NroComprobanteHasta.ToString();
                    thisHeader.FechaComprobante = bfeResponseAuthorize.BFEResultAuth.Fch_cbte;
                    thisHeader.FechaVencimiento = bfeResponseAuthorize.BFEResultAuth.Fch_venc_Cae;

                    thisHeader.PuntoVenta = loteDocs.RequestHeaders[0].PuntoVenta.ToString();
                    thisHeader.TipoComprobante = loteDocs.RequestHeaders[0].TipoComprobante.ToString();
                    thisHeader.NroInternoERP = loteDocs.RequestHeaders[0].NroInternoERP;
                    thisHeader.LetraComprobante = loteDocs.RequestHeaders[0].LetraComprobante;
                    thisHeader.SQLID = loteDocs.RequestHeaders[0].SQLID;
                    thisHeader.UltimoIDUsado = "";

                    //Obtengo el último último comprobante
                    wsbfe.BFEResponseLast_CMP bfeLastCMPRespose = afipBFE.BFERecuperaLastCMPRequest(thisHeader.TipoComprobante, thisHeader.PuntoVenta);
                    thisHeader.UltimoNroComprobanteUsado = bfeLastCMPRespose.BFEResult_LastCMP.Cbte_nro.ToString();

                    batchResponse.ResponseHeaders.Add(thisHeader);

                    if (bfeResponseAuthorize.BFEResultAuth.Reproceso.ToLower() == "s")
                    {
                        thisHeader.Resultado = "R";
                        thisHeader.Motivo = "12";
                        thisHeader.MotivoDescripcion = AfipBFE.GetMotivoDescripcion(thisHeader.Motivo);
                    }
                    else
                    {
                        thisHeader.Motivo = bfeResponseAuthorize.BFEResultAuth.Obs;
                        thisHeader.MotivoDescripcion = AfipBFE.GetMotivoDescripcion(bfeResponseAuthorize.BFEResultAuth.Obs);
                    }
                }
                else
                {
                    batchResponse.BatchUniqueId = "0";
                    batchResponse.Resultado = "R";
                    batchResponse.Reproceso = "";
                    batchResponse.CUITInformante = "";
                    batchResponse.CantidadComprobantes = "1";

                    if (bfeResponseAuthorize.BFEErr != null)
                    {
                        batchResponse.CodigoError = bfeResponseAuthorize.BFEErr.ErrCode.ToString();
                        batchResponse.MensajeError = bfeResponseAuthorize.BFEErr.ErrMsg.ToString();
                    }
                    else if (afipConn.ConnectionErrorDescription != string.Empty)
                    {
                        batchResponse.CodigoError = "669";
                        batchResponse.MensajeError = afipConn.ConnectionErrorDescription;
                    }
                    else if (bEquivalenciaError)
                    {
                        batchResponse.Resultado = "E";
                        batchResponse.CodigoError = "Equivalencias";
                        batchResponse.MensajeError = "No se encontró equivalencia con AFIP. Campos: " + strEquivalenciaErrorFields;
                    }

                    //Devolver los documentos originales
                    ResponseHeader thisHeader = new ResponseHeader();
                    thisHeader.CAE = "";
                    thisHeader.NroComprobanteDesde = loteDocs.RequestHeaders[0].NroComprobanteDesde;
                    thisHeader.FechaComprobante = loteDocs.RequestHeaders[0].FechaComprobante;
                    thisHeader.FechaVencimiento = "";
                    thisHeader.Motivo = "";
                    thisHeader.MotivoDescripcion = "";
                    thisHeader.PuntoVenta = loteDocs.RequestHeaders[0].PuntoVenta;
                    thisHeader.TipoComprobante = loteDocs.RequestHeaders[0].TipoComprobante;
                    thisHeader.NroInternoERP = loteDocs.RequestHeaders[0].NroInternoERP;
                    thisHeader.LetraComprobante = loteDocs.RequestHeaders[0].LetraComprobante;
                    thisHeader.SQLID = loteDocs.RequestHeaders[0].SQLID;

                    //Obtengo el último último comprobante
                    if (afipConn.ConnectionErrorDescription == string.Empty)
                    {
                        wsbfe.BFEResponseLast_CMP bfeLastCMPRespose = afipBFE.BFERecuperaLastCMPRequest(thisHeader.TipoComprobante, thisHeader.PuntoVenta);
                        thisHeader.UltimoNroComprobanteUsado = bfeLastCMPRespose.BFEResult_LastCMP.Cbte_nro.ToString();
                    }

                    batchResponse.ResponseHeaders.Add(thisHeader);
                }

                #endregion

                #region Registrar respuesta recibida

                if (batchResponse.Resultado == "A" || batchResponse.Resultado == "R")
                {
                    switch (batchResponse.Resultado)
                    {
                        case "A":
                            estadoDocumento = "Aceptado";
                            cae = batchResponse.ResponseHeaders[0].CAE;
                            FechaVencimiento = batchResponse.ResponseHeaders[0].FechaVencimiento;

                            break;
                        case "R":
                            estadoDocumento = "Rechazado";
                            cae = "";
                            FechaVencimiento = "";
                            break;
                    }
                }
                else if (bfeResponseAuthorize.BFEResultAuth.Reproceso.ToLower() == "s")
                {
                    estadoDocumento = "Rechazado";
                    cae = batchResponse.ResponseHeaders[0].CAE;
                    FechaVencimiento = batchResponse.ResponseHeaders[0].FechaVencimiento;
                }
                else
                {
                    estadoDocumento = "Error";
                    cae = "";
                    FechaVencimiento = "";
                }

                try
                {
                    sqlEngine.LogBatchEnd(SQLID, estadoDocumento, cae, FechaVencimiento);
                }
                catch (Exception ex)
                {
                    sqlEngine.LogError(SQLID, "0", "Respuesta Recibida", "Error: " + ex.Message);
                }
                #endregion
            }
            return batchResponse.GetXMLString();
        }
Beispiel #19
0
        public string ProcesarLoteFacturasExportacion(string EmpresaID, string xmlDocument)
        {
            #region Inicialización

            Settings oSettings = new Settings(EmpresaID);

            wsfex.Service afipFexService = new wsfex.Service();
            afipFexService.Url = oSettings.UrlAFIPwsfex;

            wsfex.ClsFEXAuthRequest afipObjFEXAuthRequest = new wsfex.ClsFEXAuthRequest();
            wsfex.FEXResponseAuthorize fexResponseAuthorize = new wsfex.FEXResponseAuthorize();

            ResponseBatch batchResponse = new ResponseBatch();
            RequestBatch loteDocs = new RequestBatch();

            string SQLID = "0";
            string estadoDocumento = string.Empty;
            string cae = string.Empty;
            string FechaVencimiento = string.Empty;
            string strEquivalenciaErrorFields = string.Empty;

            bool bRegistrarInicio = false;
            bool bEquivalenciaError = false;

            //Cargar el lote recibido
            loteDocs.LoadXMLString(xmlDocument);

            #endregion

            #region Registrar pedido

            try
            {
                bRegistrarInicio = sqlEngine.LogBatchStart(ref loteDocs);

                SQLID = loteDocs.RequestHeaders[0].SQLID;

                //DEBUG LINE
                if (Convert.ToBoolean(oSettings.ActivarDebug))
                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(loteDocs), oSettings.PathDebug + "\\" + SQLID + "-FERequestBatch-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");
            }
            catch (Exception ex)
            {
                bRegistrarInicio = false;
                sqlEngine.LogError(SQLID, "0", "Procesando lote", "Error: " + ex.Message);
            }

            #endregion

            //Si pudo crear el registro en la base continuo
            if (bRegistrarInicio)
            {
                #region Verificar Login con AFIP

                AfipConnection afipConn = new AfipConnection("wsfex", oSettings);
                if (afipConn.ConnectionErrorDescription == string.Empty)
                {
                    //Inicializo el objeto AuthRequest de la Afip
                    afipObjFEXAuthRequest.Cuit = afipConn.Cuit;
                    afipObjFEXAuthRequest.Sign = afipConn.Sign;
                    afipObjFEXAuthRequest.Token = afipConn.Token;
                }
                else
                {
                    try
                    {
                        sqlEngine.LogError(SQLID, "0", "AfipConnection", afipConn.ConnectionErrorDescription);

                        sqlEngine.LogBatchEnd(SQLID, "Error", cae, FechaVencimiento);
                    }
                    catch (Exception ex)
                    {
                        sqlEngine.LogError(SQLID, "0", "FEService-AFIP Login", "Error: " + ex.Message);
                    }
                }

                AfipFEX afipFEX = new AfipFEX(ref afipFexService, ref afipObjFEXAuthRequest, oSettings);

                #endregion

                if (afipConn.ConnectionErrorDescription == string.Empty)
                {
                    #region Buscar Equivalencias

                    bEquivalenciaError = BuscarEquivalencias(ref loteDocs, oSettings, ref strEquivalenciaErrorFields);

                    #endregion

                    //Si no hay errore de equivalencia continuo
                    if (!bEquivalenciaError)
                    {
                        #region Realizar Validaciones
                        #endregion

                        #region Hacer el pedido a AFIP

                        try
                        {
                            if (afipConn.IsConnected)
                            {
                                fexResponseAuthorize = afipFEX.FEXAuthRequest(loteDocs, oSettings);
                                if (fexResponseAuthorize.FEXErr == null)
                                {
                                    sqlEngine.LogError(SQLID, "0", "Respuesta AFIP", "AFIP no pudo procesar por un error previo. Vea el log de errores.");
                                    fexResponseAuthorize.FEXErr = new wsfex.ClsFEXErr();
                                    fexResponseAuthorize.FEXErr.ErrCode = 0;
                                    fexResponseAuthorize.FEXErr.ErrMsg = "AFIP no pudo procesar por un error previo. Vea el log de errores.";
                                }
                            }
                            else
                            {
                                sqlEngine.LogError(SQLID, "0", "Respuesta AFIP", "Sin Conexion. Descripcion: " + afipConn.ConnectionErrorDescription);
                                fexResponseAuthorize.FEXErr = new wsfex.ClsFEXErr();
                                fexResponseAuthorize.FEXErr.ErrCode = 0;
                                fexResponseAuthorize.FEXErr.ErrMsg = afipConn.ConnectionErrorDescription;
                            }
                        }
                        catch (Exception ex)
                        {
                            sqlEngine.LogError(SQLID, "0", "Respuesta AFIP", "Error: " + ex.Message);
                        }

                        #endregion
                    }
                }

                #region Armar y devolver respuesta

                //Armar info del lote
                if (fexResponseAuthorize.FEXResultAuth != null)
                {
                    batchResponse.BatchUniqueId = loteDocs.BatchUniqueId;
                    batchResponse.BatchUniqueId = fexResponseAuthorize.FEXResultAuth.Id.ToString();
                    batchResponse.CUITInformante = fexResponseAuthorize.FEXResultAuth.Cuit.ToString();
                    batchResponse.FechaCAE = fexResponseAuthorize.FEXResultAuth.Fch_venc_Cae;
                    batchResponse.CantidadComprobantes = "1";
                    batchResponse.Resultado = fexResponseAuthorize.FEXResultAuth.Resultado;
                    batchResponse.Reproceso = fexResponseAuthorize.FEXResultAuth.Reproceso;
                    batchResponse.SonServicios = "";
                    batchResponse.CodigoError = fexResponseAuthorize.FEXErr.ErrCode.ToString();
                    batchResponse.MensajeError = fexResponseAuthorize.FEXErr.ErrMsg.ToString();

                    if (fexResponseAuthorize.FEXResultAuth.Reproceso.ToLower() == "s")
                    {
                        batchResponse.Resultado = "R";
                        batchResponse.Motivo = "12";
                        batchResponse.MotivoDescripcion = "EL RANGO INFORMADO SE ENCUENTRA AUTORIZADO CON ANTERIOIRIDAD PARA LA MISMA CUIT, TIPO DE COMPROBANTE Y PUNTO DE VENTA.";
                    }
                    else
                    {
                        batchResponse.Motivo = fexResponseAuthorize.FEXResultAuth.Motivos_Obs;
                        batchResponse.MotivoDescripcion = "";
                    }

                    //Armar info del documento
                    ResponseHeader thisHeader = new ResponseHeader();

                    thisHeader.CAE = fexResponseAuthorize.FEXResultAuth.Cae;
                    thisHeader.NroComprobanteDesde = fexResponseAuthorize.FEXResultAuth.Cbte_nro.ToString();
                    thisHeader.NroComprobanteHasta = fexResponseAuthorize.FEXResultAuth.Cbte_nro.ToString();
                    thisHeader.FechaComprobante = fexResponseAuthorize.FEXResultAuth.Fch_cbte;
                    thisHeader.FechaVencimiento = fexResponseAuthorize.FEXResultAuth.Fch_venc_Cae;
                    thisHeader.PuntoVenta = fexResponseAuthorize.FEXResultAuth.Punto_vta.ToString();
                    thisHeader.TipoComprobante = fexResponseAuthorize.FEXResultAuth.Tipo_cbte.ToString();
                    thisHeader.NroInternoERP = loteDocs.RequestHeaders[0].NroInternoERP;
                    thisHeader.LetraComprobante = loteDocs.RequestHeaders[0].LetraComprobante;
                    thisHeader.SQLID = loteDocs.RequestHeaders[0].SQLID;
                    thisHeader.Resultado = fexResponseAuthorize.FEXResultAuth.Resultado;
                    thisHeader.Importe = loteDocs.RequestHeaders[0].Importe;

                    if (fexResponseAuthorize.FEXResultAuth.Reproceso.ToLower() == "s")
                    {
                        thisHeader.Resultado = "R";
                        thisHeader.Motivo = "12";
                        thisHeader.MotivoDescripcion = AfipFEX.GetMotivoDescripcion(thisHeader.Motivo, string.Empty);
                    }
                    else
                    {
                        thisHeader.Motivo = fexResponseAuthorize.FEXResultAuth.Motivos_Obs;
                        thisHeader.MotivoDescripcion = "";
                    }

                    batchResponse.ResponseHeaders.Add(thisHeader);
                }
                else
                {
                    batchResponse.BatchUniqueId = "0";
                    batchResponse.CUITInformante = "";
                    batchResponse.FechaCAE = "";
                    batchResponse.CantidadComprobantes = "1";
                    batchResponse.Resultado = "R";
                    batchResponse.Motivo = "";
                    batchResponse.MotivoDescripcion = "";
                    batchResponse.Reproceso = "";
                    batchResponse.SonServicios = "";

                    if (fexResponseAuthorize.FEXErr != null)
                    {
                        batchResponse.CodigoError = fexResponseAuthorize.FEXErr.ErrCode.ToString();
                        batchResponse.MensajeError = fexResponseAuthorize.FEXErr.ErrMsg.ToString();
                    }
                    else if (afipConn.ConnectionErrorDescription != string.Empty)
                    {
                        batchResponse.CodigoError = "669";
                        batchResponse.MensajeError = afipConn.ConnectionErrorDescription;
                    }
                    else if (bEquivalenciaError)
                    {
                        batchResponse.Resultado = "E";
                        batchResponse.CodigoError = "Equivalencias";
                        batchResponse.MensajeError = "No se encontró equivalencia con AFIP. Campos: " + strEquivalenciaErrorFields;
                    }

                    //Devolver los documentos originales
                    ResponseHeader thisHeader = new ResponseHeader();
                    thisHeader.CAE = "";
                    thisHeader.NroComprobanteDesde = loteDocs.RequestHeaders[0].NroComprobanteDesde;
                    thisHeader.NroComprobanteHasta = loteDocs.RequestHeaders[0].NroComprobanteHasta;
                    thisHeader.FechaComprobante = loteDocs.RequestHeaders[0].FechaComprobante;
                    thisHeader.FechaVencimiento = "";
                    thisHeader.Motivo = batchResponse.CodigoError;
                    thisHeader.MotivoDescripcion = batchResponse.MensajeError;
                    thisHeader.PuntoVenta = loteDocs.RequestHeaders[0].PuntoVenta;
                    thisHeader.TipoComprobante = loteDocs.RequestHeaders[0].TipoComprobante;
                    thisHeader.NroInternoERP = loteDocs.RequestHeaders[0].NroInternoERP;
                    thisHeader.LetraComprobante = loteDocs.RequestHeaders[0].LetraComprobante;
                    thisHeader.Resultado = "R";
                    thisHeader.SQLID = loteDocs.RequestHeaders[0].SQLID;

                    batchResponse.ResponseHeaders.Add(thisHeader);
                }

                #endregion

                #region Registrar respuesta recibida

                if (batchResponse.Resultado == "A" || batchResponse.Resultado == "R")
                {
                    switch (batchResponse.Resultado)
                    {
                        case "A":
                            estadoDocumento = "Aceptado";
                            cae = batchResponse.ResponseHeaders[0].CAE;
                            FechaVencimiento = batchResponse.ResponseHeaders[0].FechaVencimiento;

                            break;
                        case "R":
                            estadoDocumento = "Rechazado";
                            cae = "";
                            FechaVencimiento = "";
                            break;
                    }
                }
                else if (batchResponse.Reproceso.ToLower() == "s")
                {
                    estadoDocumento = "Rechazado";
                    cae = batchResponse.ResponseHeaders[0].CAE;
                    FechaVencimiento = batchResponse.ResponseHeaders[0].FechaVencimiento;
                }
                else
                {
                    estadoDocumento = "Error";
                    cae = "";
                    FechaVencimiento = "";
                }

                try
                {
                    sqlEngine.LogBatchEnd(SQLID, estadoDocumento, cae, FechaVencimiento);
                }
                catch (Exception ex)
                {
                    sqlEngine.LogError(SQLID, "0", "Respuesta Recibida", "Error: " + ex.Message);
                }
                #endregion
            }
            return batchResponse.GetXMLString();
        }
Beispiel #20
0
        public string ProcesarLoteFacturasBienesServicios(string EmpresaID, string xmlDocument)
        {
            #region Inicialización

            Settings oSettings = new Settings(EmpresaID);

            wsfe.Service afipFeService = new wsfe.Service();
            afipFeService.Url = oSettings.UrlAFIPwsfe;

            wsfe.FEAuthRequest afipObjFEAuthRequest = new wsfe.FEAuthRequest();
            wsfe.CbteTipo afipObjFELastCMType = new wsfe.CbteTipo();
            wsfe.FECAEResponse feResponse = new wsfe.FECAEResponse();

            ResponseBatch batchResponse = new ResponseBatch();
            RequestBatch loteDocs = new RequestBatch();

            string url = oSettings.UrlFEWebService;
            string SQLID = "0";
            string estadoDocumento = string.Empty;
            string cae = string.Empty;
            string FechaVencimiento = string.Empty;
            string strEquivalenciaErrorFields = string.Empty;

            bool bRegistrarInicio = false;
            bool bEquivalenciaError = false;

            //Cargar el lote recibido
            loteDocs.LoadXMLString(xmlDocument);

            #endregion

            #region Registrar Inicio

            try
            {
                bRegistrarInicio = sqlEngine.LogBatchStart(ref loteDocs);

                SQLID = loteDocs.RequestHeaders[0].SQLID;

                //DEBUG LINE
                if (Convert.ToBoolean( oSettings.ActivarDebug ))
                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(loteDocs), oSettings.PathDebug + "\\" + SQLID + "-P1.RequestBatch-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");
            }
            catch (Exception ex)
            {
                sqlEngine.LogError(SQLID, "0", "ProcesarLoteFacturasBienesServicios", ex.Message);
                bRegistrarInicio = false;
            }

            #endregion

            //Si pudo crear el registro en la base continuo
            if (bRegistrarInicio)
            {
                #region Verificar Login con AFIP

                AfipConnection afipConn = new AfipConnection("wsfe", oSettings);
                if (afipConn.ConnectionErrorDescription == string.Empty)
                {
                    //Inicializo el objeto AuthRequest de la Afip
                    afipObjFEAuthRequest.Cuit = afipConn.Cuit;
                    afipObjFEAuthRequest.Sign = afipConn.Sign;
                    afipObjFEAuthRequest.Token = afipConn.Token;
                }
                else
                {
                    try
                    {
                        sqlEngine.LogError(SQLID, "0", "AfipConnection", afipConn.ConnectionErrorDescription);
                        sqlEngine.LogBatchEnd(SQLID, "Error", cae, FechaVencimiento);
                    }
                    catch (Exception ex)
                    {
                        sqlEngine.LogError(SQLID, "0", "FEService-AFIP Login", "Error: " + ex.Message);
                    }
                }

                AfipFE afipFE = new AfipFE(ref afipFeService, ref afipObjFEAuthRequest, ref afipObjFELastCMType);

                #endregion

                if (afipConn.ConnectionErrorDescription == string.Empty)
                {
                    #region Buscar Equivalencias

                    bEquivalenciaError = BuscarEquivalencias(ref loteDocs, oSettings, ref strEquivalenciaErrorFields);

                    #endregion

                    //Si no hay errores de equivalencia continuo
                    if (!bEquivalenciaError)
                    {
                        #region Hacer el pedido a AFIP

                        try
                        {
                            if (afipConn.IsConnected)
                            {
                                feResponse = afipFE.FEAuthRequest(loteDocs, oSettings);

                                //DEBUG LINE
                                if (Convert.ToBoolean(oSettings.ActivarDebug))
                                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(feResponse), oSettings.PathDebug + "\\" + SQLID + "-P3.FEResponse-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");
                            }
                            else
                            {
                                sqlEngine.LogError(SQLID, "0", "Respuesta AFIP", "Sin Conexion. Descripcion: " + afipConn.ConnectionErrorDescription);
                                feResponse.Errors = new wsfe.Err[1];
                                feResponse.Errors[0] = new wsfe.Err();
                                feResponse.Errors[0].Code = 0;
                                feResponse.Errors[0].Msg = afipConn.ConnectionErrorDescription;
                            }
                        }
                        catch (Exception ex)
                        {
                            sqlEngine.LogError(SQLID, "0", "Respuesta AFIP", "Error: " + ex.Message);
                        }

                        #endregion
                    }
                }

                #region Armar y devolver respuesta

                //Armar info del lote
                if (feResponse.FeCabResp != null)
                {
                    batchResponse.BatchUniqueId = loteDocs.BatchUniqueId;
                    batchResponse.CUITInformante = feResponse.FeCabResp.Cuit.ToString();
                    batchResponse.FechaCAE = feResponse.FeCabResp.FchProceso;
                    batchResponse.CantidadComprobantes = feResponse.FeCabResp.CantReg.ToString();
                    batchResponse.Resultado = feResponse.FeCabResp.Resultado;

                    batchResponse.Reproceso = feResponse.FeCabResp.Reproceso;

                    if (feResponse.Errors != null && feResponse.Errors.Length > 0 && feResponse.Errors[0] != null)
                    {
                        batchResponse.CodigoError = feResponse.Errors[0].Code.ToString();
                        batchResponse.MensajeError = feResponse.Errors[0].Msg.ToString();
                    }
                }
                else
                {
                    batchResponse.BatchUniqueId = "0";
                    batchResponse.Resultado = "R";
                    batchResponse.CantidadComprobantes = loteDocs.CantidadComprobantes;

                    if (feResponse.Errors != null && feResponse.Errors.Length > 0 && feResponse.Errors[0] != null)
                    {
                        batchResponse.CodigoError = feResponse.Errors[0].Code.ToString();
                        batchResponse.MensajeError = feResponse.Errors[0].Msg.ToString();
                    }
                    else if(afipConn.ConnectionErrorDescription != string.Empty)
                    {
                        batchResponse.Resultado = "E";
                        batchResponse.CodigoError = "669";
                        batchResponse.MensajeError = afipConn.ConnectionErrorDescription;
                    }
                    else if (bEquivalenciaError)
                    {
                        batchResponse.Resultado = "E";
                        batchResponse.CodigoError = "Equivalencias";
                        batchResponse.MensajeError = "No se encontró equivalencia con AFIP. Campos: " + strEquivalenciaErrorFields;
                    }
                }

                //Armar info de los documentos
                if (feResponse.FeDetResp != null)
                {
                    for (int i = 0; i < feResponse.FeDetResp.Length; i++)
                    {
                        ResponseHeader thisHeader = new ResponseHeader();
                        if (feResponse.FeDetResp[i].CAE == "NULL")
                            feResponse.FeDetResp[i].CAE = "";
                        thisHeader.CAE = feResponse.FeDetResp[i].CAE;
                        thisHeader.CodigoDocumentoComprador = feResponse.FeDetResp[i].DocTipo.ToString();
                        thisHeader.NroDocumentoComprador = feResponse.FeDetResp[i].DocNro.ToString();
                        thisHeader.TipoComprobante = feResponse.FeCabResp.CbteTipo.ToString();
                        thisHeader.NroComprobanteDesde = feResponse.FeDetResp[i].CbteDesde.ToString();
                        thisHeader.NroComprobanteHasta = feResponse.FeDetResp[i].CbteHasta.ToString();
                        thisHeader.Importe = loteDocs.RequestHeaders[i].Importe;
                        thisHeader.ImporteNoGravado = loteDocs.RequestHeaders[i].ImporteNoGravado;
                        thisHeader.ImporteGravado = loteDocs.RequestHeaders[i].ImporteGravado;
                        thisHeader.ImporteImpuestoLiquidado = loteDocs.RequestHeaders[i].ImporteImpuestoLiquidado;
                        thisHeader.ImporteRNI_Percepcion = loteDocs.RequestHeaders[i].ImporteRNI_Percepcion;
                        thisHeader.ImporteExento = loteDocs.RequestHeaders[i].ImporteExento;
                        thisHeader.Resultado = feResponse.FeDetResp[i].Resultado;

                        thisHeader.FechaComprobante = feResponse.FeDetResp[i].CbteFch;
                        thisHeader.FechaVencimiento = feResponse.FeDetResp[i].CAEFchVto;

                        thisHeader.PuntoVenta = loteDocs.RequestHeaders[i].PuntoVenta;
                        thisHeader.LetraComprobante = loteDocs.RequestHeaders[i].LetraComprobante;
                        thisHeader.NroInternoERP = loteDocs.RequestHeaders[i].NroInternoERP;
                        thisHeader.SQLID = loteDocs.RequestHeaders[i].SQLID;

                        wsfe.FERecuperaLastCbteResponse feLastCMPRespose = afipFE.FERecuperaUltimoComprobante(thisHeader.TipoComprobante, thisHeader.PuntoVenta);
                        thisHeader.UltimoNroComprobanteUsado = feLastCMPRespose.CbteNro.ToString();

                        if (feResponse.Errors != null && feResponse.Errors.Length > 0 && feResponse.Errors[0] != null)
                        {
                            thisHeader.Motivo = feResponse.Errors[0].Code.ToString();
                            thisHeader.MotivoDescripcion = feResponse.Errors[0].Msg;

                            if (thisHeader.Motivo == "10016")
                                thisHeader.MotivoDescripcion += " UltimoNroComprobanteUsado: " + thisHeader.UltimoNroComprobanteUsado;
                        }

                        //NUEVO DESDE VERSION 1 DE AFIP
                        if (feResponse.FeDetResp[i].Observaciones != null)
                        {
                            foreach (wsfe.Obs wsObs in feResponse.FeDetResp[i].Observaciones)
                            {
                                ResponseHeaderObs resObs = new ResponseHeaderObs();

                                resObs.Codigo = wsObs.Code.ToString();
                                resObs.Msg = wsObs.Msg;

                                if (resObs.Codigo == "10016")
                                    resObs.Msg += " UltimoNroComprobanteUsado: " + thisHeader.UltimoNroComprobanteUsado;

                                thisHeader.Observaciones.Add(resObs);
                            }
                        }

                        thisHeader.FechaDesdeServicioFacturado = feResponse.FeDetResp[i].CbteDesde.ToString();
                        thisHeader.FechaHastaServicioFacturado = feResponse.FeDetResp[i].CbteHasta.ToString();
                        thisHeader.FechaVencimientoPago = loteDocs.RequestHeaders[i].FechaVencimientoPago;

                        batchResponse.ResponseHeaders.Add(thisHeader);
                    }
                }
                else
                {
                    for (int i = 0; i < loteDocs.RequestHeaders.Count; i++)
                    {
                        ResponseHeader thisHeader = new ResponseHeader();

                        thisHeader.CAE = "";
                        thisHeader.TipoComprobante = loteDocs.RequestHeaders[i].TipoComprobante;
                        thisHeader.PuntoVenta = loteDocs.RequestHeaders[i].PuntoVenta;
                        thisHeader.NroComprobanteDesde = loteDocs.RequestHeaders[i].NroComprobanteDesde;
                        thisHeader.NroComprobanteHasta = loteDocs.RequestHeaders[i].NroComprobanteHasta;
                        thisHeader.Importe = loteDocs.RequestHeaders[i].Importe;
                        thisHeader.ImporteNoGravado = loteDocs.RequestHeaders[i].ImporteNoGravado;
                        thisHeader.ImporteGravado = loteDocs.RequestHeaders[i].ImporteGravado;
                        thisHeader.ImporteImpuestoLiquidado = loteDocs.RequestHeaders[i].ImporteImpuestoLiquidado;
                        thisHeader.ImporteRNI_Percepcion = loteDocs.RequestHeaders[i].ImporteRNI_Percepcion;
                        thisHeader.ImporteExento = loteDocs.RequestHeaders[i].ImporteExento;
                        thisHeader.FechaComprobante = loteDocs.RequestHeaders[i].FechaComprobante;
                        thisHeader.Motivo = batchResponse.CodigoError;
                        thisHeader.MotivoDescripcion = batchResponse.MensajeError;
                        thisHeader.FechaDesdeServicioFacturado = loteDocs.RequestHeaders[i].FechaDesdeServicioFacturado;
                        thisHeader.FechaHastaServicioFacturado = loteDocs.RequestHeaders[i].FechaHastaServicioFacturado;
                        thisHeader.FechaVencimientoPago = loteDocs.RequestHeaders[i].FechaVencimientoPago;
                        thisHeader.NroInternoERP = loteDocs.RequestHeaders[i].NroInternoERP;
                        thisHeader.LetraComprobante = loteDocs.RequestHeaders[i].LetraComprobante;
                        thisHeader.SQLID = loteDocs.RequestHeaders[i].SQLID;

                        batchResponse.ResponseHeaders.Add(thisHeader);
                    }
                }

                //DEBUG LINE
                if (Convert.ToBoolean(oSettings.ActivarDebug))
                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(batchResponse), oSettings.PathDebug + "\\" + SQLID + "-P4.ResponseBatch-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                #endregion

                #region Registrar Fin

                //TODO: VERIFICAR ESTA PARTE CAPTURA MAL LOS ERRORES
                switch (batchResponse.Resultado)
                {
                    case "A":
                        estadoDocumento = "Aceptado";
                        cae = batchResponse.ResponseHeaders[0].CAE;
                        FechaVencimiento = batchResponse.ResponseHeaders[0].FechaVencimiento;

                        break;
                    case "R":
                        estadoDocumento = "Rechazado";
                        cae = "";
                        FechaVencimiento = "";
                        break;

                    default:
                        if (batchResponse.Reproceso.ToLower() == "s")
                        {
                            estadoDocumento = "Rechazado";
                            cae = batchResponse.ResponseHeaders[0].CAE;
                            FechaVencimiento = batchResponse.ResponseHeaders[0].FechaVencimiento;
                        }
                        else
                        {
                            estadoDocumento = "Error";
                            cae = "";
                            FechaVencimiento = "";
                        }
                        break;
                }

                try
                {
                    sqlEngine.LogBatchEnd(SQLID, estadoDocumento, cae, FechaVencimiento);
                }
                catch (Exception ex)
                {
                    sqlEngine.LogError(SQLID, "0", "Respuesta Recibida", "Error: " + ex.Message);
                }

                #endregion
            }

            return batchResponse.GetXMLString();
        }
Beispiel #21
0
        //TODO: correr en otro thread o utilizar updatepanel para mostrar barra de estado
        protected void CheckAfipFexService(Settings oSettings)
        {
            try
            {
                wsfex.Service afipFexService = new wsfex.Service();
                afipFexService.Url = oSettings.UrlAFIPwsfex;

                wsfex.DummyResponse dumResp = afipFexService.FEXDummy();

                if (dumResp.AppServer == "OK" && dumResp.AuthServer == "OK" && dumResp.DbServer == "OK")
                {
                    lblExportacion.ForeColor = System.Drawing.Color.Green;
                    lblExportacion.Text = "OK";
                }
                else
                {
                    lblExportacion.ForeColor = System.Drawing.Color.Red;
                    lblExportacion.Text = "ERROR";
                }
            }
            catch
            {
                lblExportacion.ForeColor = System.Drawing.Color.Red;
                lblExportacion.Text = "ERROR";
            }
        }
Beispiel #22
0
        private void ResponseError(RequestBatch docBatch, FileInfo fi, string TipoLote, string strError, Settings oSettings)
        {
            XmlDocument respSEW = new XmlDocument();
            XmlElement xmlElem = respSEW.CreateElement("comprobantes");
            XmlNode rootNode = respSEW.AppendChild(xmlElem);
            XmlNode detailsNode;

            XmlNode comprobanteNode = null;
            XmlAttribute comprobanteAttr = null;

            try
            {
                string fileNameRespuesta = @"RESP_ " + fi.Name.Replace(".txt", string.Empty) + "_" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + ".xml";

                if (docBatch != null)
                {
                    if (TipoLote == "0" || TipoLote == "1")
                    {
                        detailsNode = respSEW.CreateElement("Resultado");
                        detailsNode.InnerText = "E1";
                        xmlElem.AppendChild(detailsNode);

                        detailsNode = respSEW.CreateElement("Motivo");
                        xmlElem.AppendChild(detailsNode);

                        detailsNode = respSEW.CreateElement("MotivoDescripcion");
                        xmlElem.AppendChild(detailsNode);

                        detailsNode = respSEW.CreateElement("Reproceso");
                        detailsNode.InnerText = "N";
                        xmlElem.AppendChild(detailsNode);

                        detailsNode = respSEW.CreateElement("SonServicios");
                        detailsNode.InnerText = docBatch.SonServicios;
                        xmlElem.AppendChild(detailsNode);

                        //detailsNode = respSEW.CreateElement("CodigoError");
                        //detailsNode.InnerText = "E1";
                        //xmlElem.AppendChild(detailsNode);

                        //detailsNode = respSEW.CreateElement("MensajeError");
                        //detailsNode.AppendChild(respSEW.CreateTextNode(strError));
                        //xmlElem.AppendChild(detailsNode);
                    }

                    foreach (RequestHeader thisResponse in docBatch.RequestHeaders)
                    {
                        xmlElem = respSEW.CreateElement("comprobante");
                        comprobanteAttr = respSEW.CreateAttribute("idsolicitud");
                        comprobanteAttr.Value = thisResponse.NroComprobanteDesde;
                        xmlElem.Attributes.Append(comprobanteAttr);
                        comprobanteNode = rootNode.AppendChild(xmlElem);

                        xmlElem = respSEW.CreateElement("nro");
                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.NroComprobanteDesde));
                        comprobanteNode.AppendChild(xmlElem);

                        xmlElem = respSEW.CreateElement("tipocodaut");
                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.LetraComprobante));
                        comprobanteNode.AppendChild(xmlElem);

                        xmlElem = respSEW.CreateElement("codaut");
                        comprobanteNode.AppendChild(xmlElem);

                        xmlElem = respSEW.CreateElement("vtocodaut");
                        comprobanteNode.AppendChild(xmlElem);

                        xmlElem = respSEW.CreateElement("Tipo_cbte");
                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.TipoComprobante));
                        comprobanteNode.AppendChild(xmlElem);

                        xmlElem = respSEW.CreateElement("Punto_vta");
                        xmlElem.AppendChild(respSEW.CreateTextNode(thisResponse.PuntoVenta));
                        comprobanteNode.AppendChild(xmlElem);

                        xmlElem = respSEW.CreateElement("estadocmp");
                        xmlElem.AppendChild(respSEW.CreateTextNode("E1"));
                        comprobanteNode.AppendChild(xmlElem);

                        xmlElem = respSEW.CreateElement("codtarea");
                        xmlElem.AppendChild(respSEW.CreateTextNode(""));
                        comprobanteNode.AppendChild(xmlElem);

                        xmlElem = respSEW.CreateElement("msgerror");
                        xmlElem.AppendChild(respSEW.CreateTextNode(strError));
                        comprobanteNode.AppendChild(xmlElem);

                        sqlEngine.LogError(thisResponse.SQLID, "0", "File Engine", "Error: " + strError);

                        sqlEngine.UpdateCabeceraNombreObjetoSalida(thisResponse.SQLID, fileNameRespuesta);

                        sqlEngine.LogBatchEnd(thisResponse.SQLID, "Error", "", "");
                    }
                }
                else
                {
                    xmlElem = respSEW.CreateElement("comprobante");
                    comprobanteNode = rootNode.AppendChild(xmlElem);

                    xmlElem = respSEW.CreateElement("nro");
                    comprobanteNode.AppendChild(xmlElem);

                    xmlElem = respSEW.CreateElement("tipocodaut");
                    comprobanteNode.AppendChild(xmlElem);

                    xmlElem = respSEW.CreateElement("codaut");
                    comprobanteNode.AppendChild(xmlElem);

                    xmlElem = respSEW.CreateElement("vtocodaut");
                    comprobanteNode.AppendChild(xmlElem);

                    xmlElem = respSEW.CreateElement("Tipo_cbte");
                    comprobanteNode.AppendChild(xmlElem);

                    xmlElem = respSEW.CreateElement("Punto_vta");
                    comprobanteNode.AppendChild(xmlElem);

                    xmlElem = respSEW.CreateElement("estadocmp");
                    xmlElem.AppendChild(respSEW.CreateTextNode("E1"));
                    comprobanteNode.AppendChild(xmlElem);

                    xmlElem = respSEW.CreateElement("msgerror");
                    xmlElem.AppendChild(respSEW.CreateTextNode(strError));
                    comprobanteNode.AppendChild(xmlElem);

                    sqlEngine.LogError("0", "0", "File Engine", "Error: " + strError);
                }

                //Guardo la respuesta sino hay errores
                if (respSEW.SelectSingleNode("comprobantes/comprobante/nro") != null && respSEW.SelectSingleNode("comprobantes/comprobante/nro").InnerText != string.Empty &&
                    respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut") != null && respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut").InnerText != string.Empty &&
                    respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte").InnerText != string.Empty &&
                    respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta").InnerText != string.Empty)
                {
                    respSEW.Save(oSettings.Salida + "\\" + fileNameRespuesta.Replace(".txt", string.Empty));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("File Engine", "Error: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }
Beispiel #23
0
        protected void ddlEmpresa_SelectedIndexChanged(object sender, EventArgs e)
        {
            Settings oSettings = new Settings(ddlEmpresa.SelectedItem.Value);

            FillSucursales(oSettings.EmpresaID);
        }
Beispiel #24
0
        public AfipConnection(string serviceID, Settings oSettings)
        {
            UrlWsaaWsdl = oSettings.UrlAFIPwsaa;
            RutaCertSigner = oSettings.PathCertificate;

            RutaCertSigner = oSettings.PathCertificate;
            UrlWsaaWsdl = oSettings.UrlAFIPwsaa;
            IdServicioNegocio = serviceID;

            try
            {
                // Si el archivo con info de conexión no existe, lo creo
                if (!System.IO.File.Exists(oSettings.PathConnectionFiles + @"\" + IdServicioNegocio + ".XML"))
                {
                    this.Connect();
                    if (IsConnected)
                    {
                        string connectionTicket = ConnectionTicket;
                        // Grabar el archivo de salida
                        XmlDocument x_xmld = new XmlDocument();
                        x_xmld.LoadXml(connectionTicket);
                        x_xmld.Save(oSettings.PathConnectionFiles + @"\" + IdServicioNegocio + ".XML");
                    }
                }

                // Usar el token del archivo, si es que no está vencido
                if (System.IO.File.Exists(oSettings.PathConnectionFiles + @"\" + IdServicioNegocio + ".XML"))
                {
                    // #### Obtengo del tikcet de acceso TA.xml los campos token y sign ####
                    XmlDocument m_xmld;
                    XmlNodeList m_nodelist;
                    //XmlNode m_expiration_node;

                    m_xmld = new XmlDocument();
                    m_xmld.Load(oSettings.PathConnectionFiles + @"\" + IdServicioNegocio + ".XML"); // Debe indicar la Ruta de su Ticket de acceso
                    string stringExpirationTime = m_xmld.SelectSingleNode("/loginTicketResponse/header/expirationTime").FirstChild.Value;
                    DateTime expirationTime = Convert.ToDateTime(stringExpirationTime);
                    //Uso el ticket existente hasta que la fecha de vencimiento esté a 15 minutos de vencer
                    if (DateTime.Compare(expirationTime, DateTime.Now.AddMinutes(15)) > 0)
                    {
                        m_nodelist = m_xmld.SelectNodes("/loginTicketResponse/credentials");
                        // Loop through the nodes
                        foreach (XmlNode m_node in m_nodelist)
                        {
                            Token = m_node.ChildNodes.Item(0).InnerText;
                            Sign = m_node.ChildNodes.Item(1).InnerText;
                        }
                        XmlNode m_source = m_xmld.SelectSingleNode("/loginTicketResponse/header/destination").FirstChild;
                        Cuit = (long)Convert.ToDouble(m_source.Value.ToString().Substring(m_source.Value.ToString().IndexOf("CUIT ") + 5, 11));
                        IsConnected = true;
                    }
                    else
                    {
                        this.Connect();
                        if (IsConnected)
                        {
                            string connectionTicket = ConnectionTicket;
                            // Grabar el archivo de salida
                            XmlDocument x_xmld = new XmlDocument();
                            x_xmld.LoadXml(connectionTicket);
                            x_xmld.Save(oSettings.PathConnectionFiles + @"\" + IdServicioNegocio + ".XML");

                            // Setear las variables de la clase
                            stringExpirationTime = x_xmld.SelectSingleNode("/loginTicketResponse/header/expirationTime").FirstChild.Value;
                            expirationTime = Convert.ToDateTime(stringExpirationTime);
                            m_nodelist = x_xmld.SelectNodes("/loginTicketResponse/credentials");
                            // Loop through the nodes
                            foreach (XmlNode m_node in m_nodelist)
                            {
                                Token = m_node.ChildNodes.Item(0).InnerText;
                                Sign = m_node.ChildNodes.Item(1).InnerText;
                            }
                            XmlNode m_source = x_xmld.SelectSingleNode("/loginTicketResponse/header/destination").FirstChild;
                            Cuit = (long)Convert.ToDouble(m_source.Value.ToString().Substring(m_source.Value.ToString().IndexOf("CUIT ") + 5, 11));
                        }
                        else
                        {
                            string connectionErrorDescription = ConnectionErrorDescription;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
               sqlEngine.LogError("0", "0", "AFIP Connection", ex.Message);
            }
        }
Beispiel #25
0
        protected void btnGetCAE_Click(object sender, EventArgs e)
        {
            try
            {
                Settings oSettings = new Settings(ddlEmpresa.SelectedItem.Value);

                AfipConnection afipConnFex = new AfipConnection("wsfex", oSettings);
                AfipConnection afipConnFe = new AfipConnection("wsfe", oSettings);
                AfipConnection afipConnFeB = new AfipConnection("wsbfe", oSettings);

                wsfex.Service fexService = new wsfex.Service();
                fexService.Url = oSettings.UrlAFIPwsfex;

                wsfe.Service feService = new wsfe.Service();
                feService.Url = oSettings.UrlAFIPwsfe;

                wsfeb.Service febService = new wsfeb.Service();
                febService.Url = oSettings.UrlAFIPwsbfe;

                wsfex.ClsFEX_LastCMP afipLastEx = new wsfex.ClsFEX_LastCMP();
                wsfex.ClsFEXAuthRequest objFEXAuthRequest = new wsfex.ClsFEXAuthRequest();
                wsfex.FEXGetCMPResponse objFEXGetCMPResponse = new wsfex.FEXGetCMPResponse();
                wsfex.ClsFEXRequest objFEXRequest = new wsfex.ClsFEXRequest();
                wsfex.FEXResponseAuthorize fexResponse = new wsfex.FEXResponseAuthorize();

                wsfe.FEAuthRequest objFEAuthRequest = new wsfe.FEAuthRequest();
                wsfe.FECompConsultaReq objFERequest = new wsfe.FECompConsultaReq();
                wsfe.FECompConsultaResponse feResponse = new wsfe.FECompConsultaResponse();

                //wsfe.FELastCMPtype objFELastCMType = new wsfe.FELastCMPtype();
                //wsfe.FEConsultaCAEResponse objFEConsultaCAEResponse = new wsfe.FEConsultaCAEResponse();
                //wsfe.FEConsultaCAEReq objCMPFE = new wsfe.FEConsultaCAEReq();
                //wsfe.FEResponse feResponse = new wsfe.FEResponse();
                //wsfe.FERequest objFERequest = new wsfe.FERequest();

                wsfeb.BFEGetCMPResponse objBFEGetCMPResponse = new wsfeb.BFEGetCMPResponse();
                wsfeb.ClsBFEGetCMP objCMP = new wsfeb.ClsBFEGetCMP();
                wsfeb.ClsBFEAuthRequest objBFEAuthRequest = new wsfeb.ClsBFEAuthRequest();

                DataTable returnDTable = new DataTable();

                SQLEngine sqlEngine = new SQLEngine();

                switch (ddlTipoComprobanteCAE.SelectedValue)
                {
                    case "1":
                    case "2":
                    case "3":
                    case "6":
                    case "7":
                    case "8":
                        lblErrorMessages.Text = "";

                        if (afipConnFeB.ConnectionErrorDescription == string.Empty)
                        {
                            objBFEAuthRequest.Cuit = afipConnFeB.Cuit;
                            objBFEAuthRequest.Sign = afipConnFeB.Sign;
                            objBFEAuthRequest.Token = afipConnFeB.Token;

                            objCMP.Punto_vta = Convert.ToInt16(ddlSucursalCAE.SelectedValue);
                            objCMP.Tipo_cbte = Convert.ToInt16(ddlTipoComprobanteCAE.SelectedValue);
                            objCMP.Cbte_nro = Convert.ToInt64(txtNroComprobante.Text);

                            objBFEGetCMPResponse = febService.BFEGetCMP(objBFEAuthRequest, objCMP);

                            if (objBFEGetCMPResponse.BFEResultGet != null && objBFEGetCMPResponse.BFEResultGet.Fch_venc_Cae != null)
                            {
                                lblCAE.Text = objBFEGetCMPResponse.BFEResultGet.Cae;
                                lblVto.Text = objBFEGetCMPResponse.BFEResultGet.Fch_venc_Cae;//objBFEGetCMPResponse.BFEResultGet.Fch_venc_Cae.Substring(3, 2) + "/" + objBFEGetCMPResponse.BFEResultGet.Fch_venc_Cae.Substring(4, 2) + "/" + objBFEGetCMPResponse.BFEResultGet.Fch_venc_Cae.Substring(0, 4);
                            }
                            else
                            {
                                objFEAuthRequest.Cuit = afipConnFe.Cuit;
                                objFEAuthRequest.Sign = afipConnFe.Sign;
                                objFEAuthRequest.Token = afipConnFe.Token;

                                objFERequest.CbteNro = Convert.ToInt64(txtNroComprobante.Text);
                                objFERequest.CbteTipo = Convert.ToInt16(ddlTipoComprobanteCAE.SelectedValue);
                                objFERequest.PtoVta = Convert.ToInt16(ddlSucursalCAE.SelectedValue);

                                feResponse = feService.FECompConsultar(objFEAuthRequest, objFERequest);

                                if (feResponse.ResultGet != null && feResponse.ResultGet.CodAutorizacion != null)
                                {
                                    lblCAE.Text = feResponse.ResultGet.CodAutorizacion;
                                    lblVto.Text = feResponse.ResultGet.FchVto; //.Substring(6, 2) + "/" + feResponse.FecResp.fecha_cae.Substring(4, 2) + "/" + feResponse.FecResp.fecha_cae.Substring(0, 4); ;
                                }
                                else
                                {
                                    lblCAE.Text = "Comprobante inexistente.";
                                    lblVto.Text = "XX/XX/XXXX";
                                }

                                ////si es bienes y servicios hay que reprocesar para obtener CAE, lo busco en la base
                                //returnDTable = sqlEngine.GetItems("cbtecabecera", "*", "NroComprobanteDesde = '" + FillWithCeros(txtNroComprobante.Text) + "' and PuntoVenta = '" + ddlSucursalCAE.SelectedValue + "' and TipoComprobante = '" + ddlTipoComprobanteCAE.SelectedValue + "'", 0);

                                //if (returnDTable.Rows.Count > 0)
                                //{
                                //    if (returnDTable.Rows[0]["BatchUniqueId"].ToString() != string.Empty)
                                //    {
                                //        wsfe.FECabeceraRequest objFECabeceraRequest = new wsfe.FECabeceraRequest();
                                //        objFECabeceraRequest.cantidadreg = 0;
                                //        objFECabeceraRequest.id = Convert.ToInt64(returnDTable.Rows[0]["BatchUniqueId"].ToString());
                                //        objFECabeceraRequest.presta_serv = 0;

                                //        wsfe.FEDetalleRequest[] aObjFEDetalleRequest = new wsfe.FEDetalleRequest[1];

                                //        wsfe.FEDetalleRequest objFEDetalleRequest = new wsfe.FEDetalleRequest();
                                //        objFEDetalleRequest.tipo_doc = Convert.ToInt16(returnDTable.Rows[0]["CompradorCodigoDocumento"]);
                                //        objFEDetalleRequest.nro_doc = (long)Convert.ToDouble(returnDTable.Rows[0]["CompradorNroDocumento"]);
                                //        objFEDetalleRequest.tipo_cbte = Convert.ToInt16(returnDTable.Rows[0]["TipoComprobante"]);
                                //        objFEDetalleRequest.punto_vta = Convert.ToInt16(returnDTable.Rows[0]["PuntoVenta"]);
                                //        objFEDetalleRequest.cbt_desde = (long)Convert.ToDouble(returnDTable.Rows[0]["NroComprobanteDesde"]);
                                //        objFEDetalleRequest.cbt_hasta = (long)Convert.ToDouble(returnDTable.Rows[0]["NroComprobanteHasta"]);
                                //        objFEDetalleRequest.imp_total = Convert.ToDouble(returnDTable.Rows[0]["Importe"]);
                                //        objFEDetalleRequest.imp_tot_conc = Convert.ToDouble(returnDTable.Rows[0]["ImporteNoGravado"]);
                                //        objFEDetalleRequest.imp_neto = Convert.ToDouble(returnDTable.Rows[0]["ImporteGravado"]);
                                //        objFEDetalleRequest.impto_liq = Convert.ToDouble(returnDTable.Rows[0]["ImporteImpuestoLiquidado"]);
                                //        objFEDetalleRequest.impto_liq_rni = Convert.ToDouble(returnDTable.Rows[0]["ImporteRNI_Percepcion"]);
                                //        objFEDetalleRequest.imp_op_ex = Convert.ToDouble(returnDTable.Rows[0]["ImporteExento"]);

                                //        // Las fechas deben venir en formato "YYYY-MM-DD"
                                //        objFEDetalleRequest.fecha_cbte = Convert.ToDateTime(returnDTable.Rows[0]["FechaComprobante"]).ToString("yyyyMMdd");
                                //        objFEDetalleRequest.fecha_serv_desde = Convert.ToDateTime(returnDTable.Rows[0]["FechaDesdeServicioFacturado"]).ToString("yyyyMMdd");
                                //        objFEDetalleRequest.fecha_serv_hasta = Convert.ToDateTime(returnDTable.Rows[0]["FechaHastaServicioFacturado"]).ToString("yyyyMMdd");
                                //        objFEDetalleRequest.fecha_venc_pago = Convert.ToDateTime(returnDTable.Rows[0]["FechaVencimientoPago"]).ToString("yyyyMMdd");
                                //        aObjFEDetalleRequest[0] = objFEDetalleRequest;

                                //        objFERequest.Fecr = objFECabeceraRequest;
                                //        objFERequest.Fedr = aObjFEDetalleRequest;

                                //        feResponse = feService.FEAutRequest(objFEAuthRequest, objFERequest);

                                //        if (feResponse.FedResp != null && feResponse.FedResp[0].cae != null)
                                //        {
                                //            lblCAE.Text = feResponse.FedResp[0].cae;
                                //            lblVto.Text = feResponse.FedResp[0].fecha_vto; //.Substring(6, 2) + "/" + feResponse.FecResp.fecha_cae.Substring(4, 2) + "/" + feResponse.FecResp.fecha_cae.Substring(0, 4); ;
                                //        }
                                //        else
                                //        {
                                //            lblCAE.Text = "Comprobante inexistente.";
                                //            lblVto.Text = "XX/XX/XXXX";
                                //        }
                                //    }
                                //    else
                                //    {
                                //        lblCAE.Text = "Comprobante sin BatchUniqueId.";
                                //        lblVto.Text = "XX/XX/XXXX";
                                //    }
                                //}
                                //else
                                //{
                                //    lblCAE.Text = "Comprobante inexistente.";
                                //    lblVto.Text = "XX/XX/XXXX";
                                //}
                            }
                        }
                        else
                        {
                            lblNumCbte.Text = "XXXXXXXX";
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "alert('Error de login con AFIP, vuelva a intentar la operacion en unos minutos.')", true);
                        }
                        break;

                    case "19":
                    case "20":
                    case "21":

                        lblErrorMessages.Text = "";
                        if (afipConnFex.ConnectionErrorDescription == string.Empty)
                        {
                            //si es bienes y servicios hay que reprocesar para obtener CAE, lo busco en la base
                            returnDTable = sqlEngine.GetItems("cbtecabecera", "*", "NroComprobanteDesde = '" + FillWithCeros(txtNroComprobante.Text) + "' and PuntoVenta = '" + ddlSucursalCAE.SelectedValue + "' and TipoComprobante = '" + ddlTipoComprobanteCAE.SelectedValue + "' and BatchUniqueId IS NOT NULL", 0);

                            objFEXAuthRequest.Cuit = afipConnFex.Cuit;
                            objFEXAuthRequest.Sign = afipConnFex.Sign;
                            objFEXAuthRequest.Token = afipConnFex.Token;

                            if (returnDTable.Rows.Count > 0)
                            {
                                if (returnDTable.Rows[0]["BatchUniqueId"].ToString() != string.Empty)
                                {
                                    objFEXRequest.Id = (long)Convert.ToDouble(returnDTable.Rows[0]["BatchUniqueId"]);
                                    objFEXRequest.Tipo_cbte = Convert.ToInt16(returnDTable.Rows[0]["TipoComprobante"]);
                                    objFEXRequest.Punto_vta = Convert.ToInt16(returnDTable.Rows[0]["PuntoVenta"]);
                                    objFEXRequest.Cbte_nro = (long)Convert.ToDouble(returnDTable.Rows[0]["NroComprobanteDesde"]);
                                    objFEXRequest.Tipo_expo = Convert.ToInt16(returnDTable.Rows[0]["TipoExportacion"]);
                                    objFEXRequest.Permiso_existente = returnDTable.Rows[0]["PermisoExistente"].ToString();
                                    objFEXRequest.Dst_cmp = Convert.ToInt16(sqlEngine.ObtenerEquivalencia("EquivAFIPPais", ddlEmpresa.SelectedItem.Value, returnDTable.Rows[0]["PaisComprador"].ToString()));
                                    objFEXRequest.Cliente = returnDTable.Rows[0]["CompradorRazonSocial"].ToString();
                                    objFEXRequest.Domicilio_cliente = returnDTable.Rows[0]["CompradorDireccion"].ToString();
                                    objFEXRequest.Moneda_Id = returnDTable.Rows[0]["CodigoMoneda"].ToString();
                                    objFEXRequest.Moneda_ctz = Convert.ToDouble(returnDTable.Rows[0]["TasaCambio"]);
                                    objFEXRequest.Imp_total = Convert.ToDouble(returnDTable.Rows[0]["ImporteMonedaFacturacion"]);
                                    objFEXRequest.Idioma_cbte = Convert.ToInt16(returnDTable.Rows[0]["Idioma"]);
                                    objFEXRequest.Id_impositivo = returnDTable.Rows[0]["CompradorNroDocumento"].ToString();
                                    objFEXRequest.Fecha_cbte = Convert.ToDateTime(returnDTable.Rows[0]["FechaComprobante"]).ToString("yyyyMMdd");
                                    objFEXRequest.Forma_pago = returnDTable.Rows[0]["FormaPagoDescrip"].ToString();
                                    objFEXRequest.Obs = returnDTable.Rows[0]["Observaciones"].ToString();
                                    objFEXRequest.Obs_comerciales = returnDTable.Rows[0]["ObservacionesComerciales"].ToString();
                                    objFEXRequest.Incoterms = returnDTable.Rows[0]["IncoTerms"].ToString();

                                    fexResponse = fexService.FEXAuthorize(objFEXAuthRequest, objFEXRequest);

                                    if (fexResponse.FEXResultAuth != null && fexResponse.FEXResultAuth.Cae != null)
                                    {
                                        lblCAE.Text = fexResponse.FEXResultAuth.Cae;
                                        lblVto.Text = fexResponse.FEXResultAuth.Fch_venc_Cae;//.Substring(6, 2) + "/" + fexResponse.FEXResultAuth.Fch_venc_Cae.Substring(4, 2) + "/" + fexResponse.FEXResultAuth.Fch_venc_Cae.Substring(0, 4);
                                    }
                                    else
                                    {
                                        lblCAE.Text = "Comprobante inexistente.";
                                        lblVto.Text = "XX/XX/XXXX";
                                    }
                                }
                                else
                                {
                                    lblCAE.Text = "Comprobante sin BatchUniqueId.";
                                    lblVto.Text = "XX/XX/XXXX";
                                }
                            }
                            else
                            {
                                lblCAE.Text = "Comprobante inexistente.";
                                lblVto.Text = "XX/XX/XXXX";
                            }
                        }
                        else
                        {
                            lblNumCbte.Text = "XXXXXXXX";
                            Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "alert('Error de login con AFIP, vuelva a intentar la operacion en unos minutos.')", true);
                        }

                        break;
                }
                sqlEngine.Close();
            }
            catch (Exception ex)
            {
                lblNumCbte.Text = "XXXXXXXX";
                lblErrorMessages.Text = "Error: " + ex.Message;
            }
        }
Beispiel #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            EmpresaID = Request.QueryString["eid"];
            Settings oSettings = new Settings(EmpresaID);

            if (oSettings.SMTPServer != string.Empty)
            {
                LoadCbte();
            }
            else
            {
                lblErrors.Text = "El servidor SMTP no esta configurado.";
            }
        }
Beispiel #27
0
        public wsfex.FEXResponseAuthorize FEXAuthRequest(RequestBatch docBatch, Settings oSettings )
        {
            wsfex.ClsFEXRequest objFEXRequest = new wsfex.ClsFEXRequest();
            wsfex.FEXResponseAuthorize objFEXResponseAuthorize = new wsfex.FEXResponseAuthorize();
            wsfex.FEXResponse_LastID objFEXResponseLastID = null;

            DBEngine.SQLEngine sqlEngine = new FacturaElectronica.DBEngine.SQLEngine();

            int i = 0;

            try
            {
                //Debug Line
                Utils.Utils.DebugLine(Utils.Utils.SerializeObject(objFEXAuthRequest), oSettings.PathDebug + "\\ClsFEXAuthRequest-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                //Si no tiene identificador único hay que generarlo
                if (docBatch.BatchUniqueId == "AUTO")
                {
                    objFEXResponseLastID = GetLastBatchUniqueId();
                    if (objFEXResponseLastID.FEXResultGet == null)
                    {
                        sqlEngine.LogError(docBatch.RequestHeaders[0].SQLID, "0", "Autorización", "Error AFIP al obtener el último nro de requerimiento (" + objFEXResponseLastID.FEXErr.ErrCode + ") " + objFEXResponseLastID.FEXErr.ErrMsg);
                    }
                    else
                    {
                        objFEXResponseLastID.FEXResultGet.Id = objFEXResponseLastID.FEXResultGet.Id + 1;
                        docBatch.BatchUniqueId = (objFEXResponseLastID.FEXResultGet.Id).ToString();

                        //Guardar Unique Batch ID que luego se utilizara para reprocesos y obtener CAE
                        sqlEngine.UpdateCabeceraBatchUniqueId(docBatch.RequestHeaders[0].SQLID, docBatch.BatchUniqueId);
                    }
                }

                //Debug Line
                Utils.Utils.DebugLine(Utils.Utils.SerializeObject(docBatch), oSettings.PathDebug + "\\DocumentBatch-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                string fieldName = "";
                string seccionName = "";

                try
                {
                    seccionName = "Cabecera";
                    objFEXRequest.Id = (long)Convert.ToDouble(docBatch.BatchUniqueId);
                    objFEXRequest.Tipo_cbte = Convert.ToInt16(docBatch.RequestHeaders[0].TipoComprobante);
                    objFEXRequest.Punto_vta = Convert.ToInt16(docBatch.RequestHeaders[0].PuntoVenta);
                    objFEXRequest.Cbte_nro = (long)Convert.ToDouble(docBatch.RequestHeaders[0].NroComprobanteDesde);
                    objFEXRequest.Tipo_expo = Convert.ToInt16((docBatch.RequestHeaders[0].TipoExportacion == string.Empty) ? "1" : docBatch.RequestHeaders[0].TipoExportacion);

                    if (objFEXRequest.Tipo_cbte == 19)
                        objFEXRequest.Permiso_existente = (docBatch.RequestHeaders[0].PermisoExistente == string.Empty) ? "N" : docBatch.RequestHeaders[0].PermisoExistente;
                    else
                        objFEXRequest.Permiso_existente = string.Empty;

                    objFEXRequest.Dst_cmp = Convert.ToInt16(docBatch.RequestHeaders[0].CompradorPais);
                    objFEXRequest.Cliente = docBatch.RequestHeaders[0].CompradorRazonSocial;
                    objFEXRequest.Domicilio_cliente = docBatch.RequestHeaders[0].CompradorDireccion;
                    objFEXRequest.Moneda_Id = docBatch.RequestHeaders[0].CodigoMoneda;
                    objFEXRequest.Moneda_ctz = Convert.ToDouble(docBatch.RequestHeaders[0].TasaCambio);
                    objFEXRequest.Imp_total = Convert.ToDouble(docBatch.RequestHeaders[0].ImporteMonedaFacturacion);
                    objFEXRequest.Idioma_cbte = Convert.ToInt16((docBatch.RequestHeaders[0].Idioma == string.Empty) ? "01" : docBatch.RequestHeaders[0].Idioma);
                    objFEXRequest.Id_impositivo = docBatch.RequestHeaders[0].CompradorNroDocumento;
                    objFEXRequest.Fecha_cbte = Convert.ToDateTime(docBatch.RequestHeaders[0].FechaComprobante).ToString("yyyyMMdd");
                    objFEXRequest.Forma_pago = docBatch.RequestHeaders[0].FormaPagoDescripcion;
                    objFEXRequest.Obs = docBatch.RequestHeaders[0].Observaciones2;
                    objFEXRequest.Obs_comerciales = docBatch.RequestHeaders[0].Observaciones1;
                    objFEXRequest.Incoterms = docBatch.RequestHeaders[0].IncoTerms;

                    objFEXRequest.Items = new FacturaElectronica.WebServices.wsfex.Item[Convert.ToInt32(docBatch.RequestHeaders[0].CantidadRegistrosDetalle)];

                    for (i = 0; i < objFEXRequest.Items.Length; i++)
                    {
                        seccionName = "Línea " + i.ToString();
                        objFEXRequest.Items[i] = new wsfex.Item();
                        objFEXRequest.Items[i].Pro_codigo = docBatch.RequestHeaders[0].RequestLines[i].CodigoProductoEmpresa;
                        objFEXRequest.Items[i].Pro_ds = docBatch.RequestHeaders[0].RequestLines[i].Descripcion;
                        objFEXRequest.Items[i].Pro_umed = Convert.ToInt32(docBatch.RequestHeaders[0].RequestLines[i].UnidadMedida);
                        objFEXRequest.Items[i].Pro_qty = Convert.ToDouble(docBatch.RequestHeaders[0].RequestLines[i].Cantidad);
                        objFEXRequest.Items[i].Pro_precio_uni = Convert.ToDouble(docBatch.RequestHeaders[0].RequestLines[i].ImportePrecioUnitarioMonedaFacturacion);
                        objFEXRequest.Items[i].Pro_total_item = Convert.ToDouble(docBatch.RequestHeaders[0].RequestLines[i].ImporteSubtotalMonedaFacturacion);
                    }
                }
                catch (Exception ex)
                {
                    sqlEngine.LogError("0", "0", "Autorización", "Error al asignar el campo: " + seccionName + "." + fieldName + ", " + ex.Message);
                }

                //Debug Line
                Utils.Utils.DebugLine(Utils.Utils.SerializeObject(objFEXRequest), oSettings.PathDebug + "\\ClsFEXRequest-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                objFEXResponseAuthorize = fexService.FEXAuthorize(objFEXAuthRequest, objFEXRequest);
            }
            catch (Exception ex)
            {
                int iElement = 0;
                if (i > 0)
                    iElement = i - 1;
                else
                    iElement = 0;

                sqlEngine.LogError(docBatch.RequestHeaders[iElement].SQLID, "0", "Autorización", "Error no conocido: (AfipFEX) " + ex.Message);

                objFEXResponseAuthorize.FEXErr = new FacturaElectronica.WebServices.wsfex.ClsFEXErr();

                if (docBatch.BatchUniqueId == "AUTO" || objFEXResponseLastID.FEXResultGet == null)
                {
                    objFEXResponseAuthorize.FEXErr.ErrCode = 667;
                    objFEXResponseAuthorize.FEXErr.ErrMsg = ex.Message + "Error en AFIP al obtener el último nro de requerimiento (" + objFEXResponseLastID.FEXErr.ErrCode.ToString() + ") " + objFEXResponseLastID.FEXErr.ErrMsg;
                }
                else
                {
                    objFEXResponseAuthorize.FEXErr.ErrCode = 668;
                    objFEXResponseAuthorize.FEXErr.ErrMsg = ex.Message;
                    sqlEngine.LogError(docBatch.RequestHeaders[iElement].SQLID, "0", "Autorización", "Error no conocido: (AfipFEX) " + ex.Message);
                }
            }

            return objFEXResponseAuthorize;
        }
Beispiel #28
0
        protected void btnSend_Click(object sender, EventArgs e)
        {
            string strIds = Request.QueryString["ids"];
            string strId = string.Empty;

            MailMessage oMessage = null;
            Attachment oAttach = null;
            SmtpClient emailClient = null;
            System.Net.NetworkCredential SMTPUserInfo = null;

            FEPrint.FEPrintService FEPrintService = new FEPrint.FEPrintService();

            byte[] fileData = null;
            Stream oStream = null;

            DataTable dtCbte = new DataTable();
            DataTable dtUser = new DataTable();

            TableRow tbRow;
            TableCell tbCell;

            try
            {
                tblComprobantes.Rows.Clear();
                btnSend.Visible = false;

                EmpresaID = Request.QueryString["eid"];
                Settings oSettings = new Settings(EmpresaID);

                FEPrintService.Url = oSettings.UrlPrintWebService;
                FEPrintService.Credentials = System.Net.CredentialCache.DefaultCredentials;

                foreach (string strCbte in strIds.Split('|'))
                {
                    tbCell = new TableCell();
                    tbRow = new TableRow();

                    if (strCbte != string.Empty && strCbte.Split(';').Length == 2)
                    {
                        strId = strCbte.Split(';')[0];

                        dtCbte = GetComprobanteDataTable(strId);

                        if (dtCbte.Rows[0]["COMPRADORCODIGOCLIENTE"].ToString() != string.Empty)
                        {
                            dtUser = GetUserData(oSettings.Entrada.Split('\\')[0], oSettings.Entrada.Split('\\')[1], "IFMSFA_TERCEROS_AFIP", dtCbte.Rows[0]["COMPRADORCODIGOCLIENTE"].ToString());

                            if (dtUser.Rows.Count > 0)
                            {
                                if (dtUser.Rows[0]["CORREO"].ToString() != string.Empty)
                                {
                                    fileData = FEPrintService.GetCbte(EmpresaID, strId, FEPrint.TipoDeCopia.Original);

                                    oStream = new MemoryStream(fileData);
                                    oAttach = new Attachment(oStream, "Comprobante.pdf");

                                    oMessage = new MailMessage(oSettings.SMTPFrom, dtUser.Rows[0]["CORREO"].ToString(), oSettings.MailSubject, oSettings.MailMessage);
                                    oMessage.Attachments.Add(oAttach);

                                    if (oSettings.SMTPServer != string.Empty)
                                    {
                                        emailClient = new SmtpClient(oSettings.SMTPServer);

                                        if (oSettings.SMTPUser != string.Empty && oSettings.SMTPPassword != string.Empty)
                                        {
                                            SMTPUserInfo = new System.Net.NetworkCredential(oSettings.SMTPUser, oSettings.SMTPPassword);

                                            emailClient.UseDefaultCredentials = false;
                                            emailClient.Credentials = SMTPUserInfo;
                                        }

                                        emailClient.Send(oMessage);

                                        tbCell.Controls.Add(new LiteralControl(dtCbte.Rows[0]["nrocomprobantedesde"].ToString() + " - OK.<br>"));
                                    }
                                }
                                else
                                {
                                    tbCell.Controls.Add(new LiteralControl(dtCbte.Rows[0]["nrocomprobantedesde"].ToString() + " - El cliente no tiene correo.<br>"));
                                }
                            }
                            else
                            {
                                tbCell.Controls.Add(new LiteralControl(dtCbte.Rows[0]["nrocomprobantedesde"].ToString() + " - No hay información de Usuario para este cliente.<br>"));
                            }
                        }
                        else
                        {
                            tbCell.Controls.Add(new LiteralControl(dtCbte.Rows[0]["nrocomprobantedesde"].ToString() + " - El cliente no tiene un usuario creado.<br>"));
                        }
                    }

                    tbRow.Cells.Add(tbCell);

                    tblComprobantes.Rows.Add(tbRow);
                }
            }
            catch (Exception ex)
            {
                tblComprobantes.Rows.Clear();
                lblErrors.Text = "Error Enviando Correos. " + ex.Message;
            }
        }
Beispiel #29
0
        public wsbfe.BFEResponseAuthorize BFEAuthorize(RequestBatch docBatch, Settings oSettings)
        {
            wsbfe.ClsBFERequest objBFERequest = new wsbfe.ClsBFERequest();
            wsbfe.BFEResponseAuthorize objBFEResponseAuthorize = new wsbfe.BFEResponseAuthorize();
            wsbfe.BFEResponse_LastID objBFEResponseLastID = null;

            DBEngine.SQLEngine sqlEngine = new FacturaElectronica.DBEngine.SQLEngine();

            int i = 0;

            try
            {
                //DEBUG LINE
                if (Convert.ToBoolean(oSettings.ActivarDebug))
                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(objBFEAuthRequest), oSettings.PathDebug + "\\ClsBFEAuthRequest-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                //Si no tiene identificador único hay que generarlo
                if (docBatch.BatchUniqueId == "AUTO")
                {
                    objBFEResponseLastID = GetLastBatchUniqueId();
                    if (objBFEResponseLastID.BFEResultGet == null)
                    {
                        sqlEngine.LogError(docBatch.RequestHeaders[0].SQLID, "0", "Autorización", "Error AFIP al obtener el último nro de requerimiento (" + objBFEResponseLastID.BFEErr.ErrCode + ") " + objBFEResponseLastID.BFEErr.ErrMsg);
                    }
                    else
                    {
                        objBFEResponseLastID.BFEResultGet.Id = objBFEResponseLastID.BFEResultGet.Id + 1;
                        docBatch.BatchUniqueId = (objBFEResponseLastID.BFEResultGet.Id).ToString();

                        //Guardar Unique Batch ID que luego se utilizara para reprocesos y obtener CAE
                        sqlEngine.UpdateCabeceraBatchUniqueId(docBatch.RequestHeaders[0].SQLID, docBatch.BatchUniqueId);
                    }
                }

                //DEBUG LINE
                if (Convert.ToBoolean(oSettings.ActivarDebug))
                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(docBatch), oSettings.PathDebug + "\\DocumentBatch-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                string fieldName = "";
                string seccionName = "";

                try
                {
                    seccionName = "Cabecera";
                    fieldName = "BatchUniqueId";
                    objBFERequest.Id = (long)Convert.ToDouble(docBatch.BatchUniqueId);
                    fieldName = "TipoComprobante";
                    objBFERequest.Tipo_cbte = Convert.ToInt16(docBatch.RequestHeaders[0].TipoComprobante);
                    fieldName = "PuntoVenta";
                    objBFERequest.Punto_vta = Convert.ToInt16(docBatch.RequestHeaders[0].PuntoVenta);
                    fieldName = "NroComprobanteDesde";
                    objBFERequest.Cbte_nro = (long)Convert.ToDouble(docBatch.RequestHeaders[0].NroComprobanteDesde);
                    fieldName = "ImporteMonedaFacturacion";
                    objBFERequest.Imp_total = Convert.ToDouble(docBatch.RequestHeaders[0].ImporteMonedaFacturacion);
                    fieldName = "FechaComprobante";
                    objBFERequest.Fecha_cbte = Convert.ToDateTime(docBatch.RequestHeaders[0].FechaComprobante).ToString("yyyyMMdd");
                    fieldName = "ImportePercepcionIIBBMonedaFacturacion";
                    objBFERequest.Imp_iibb = Convert.ToDouble(docBatch.RequestHeaders[0].ImportePercepcionIIBBMonedaFacturacion);
                    fieldName = "ImporteImpuestosInternosMonedaFacturacion";
                    objBFERequest.Imp_internos = Convert.ToDouble(docBatch.RequestHeaders[0].ImporteImpuestosInternosMonedaFacturacion);
                    fieldName = "ImporteExentoMonedaFacturacion";
                    objBFERequest.Imp_op_ex = Convert.ToDouble(docBatch.RequestHeaders[0].ImporteExentoMonedaFacturacion);
                    fieldName = "ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion";
                    objBFERequest.Imp_perc = Convert.ToDouble(docBatch.RequestHeaders[0].ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion);
                    fieldName = "ImportePercepcionImpuestosMunicipalesMonedaFacturacion";
                    objBFERequest.Imp_perc_mun = Convert.ToDouble(docBatch.RequestHeaders[0].ImportePercepcionImpuestosMunicipalesMonedaFacturacion);
                    fieldName = "ImporteNoGravadoMonedaFacturacion";
                    objBFERequest.Imp_tot_conc = Convert.ToDouble(docBatch.RequestHeaders[0].ImporteNoGravadoMonedaFacturacion);
                    fieldName = "ImporteImpuestoLiquidadoMonedaFacturacion";
                    objBFERequest.Impto_liq = Convert.ToDouble(docBatch.RequestHeaders[0].ImporteImpuestoLiquidadoMonedaFacturacion);
                    fieldName = "CodigoDocumentoComprador";
                    objBFERequest.Tipo_doc = Convert.ToInt16(docBatch.RequestHeaders[0].CompradorCodigoDocumento);
                    fieldName = "NroDocumentoComprador";
                    objBFERequest.Nro_doc = Convert.ToInt64(docBatch.RequestHeaders[0].CompradorNroDocumento);
                    fieldName = "CodigoMoneda";
                    objBFERequest.Imp_moneda_Id = docBatch.RequestHeaders[0].CodigoMoneda;
                    fieldName = "TasaCambio";
                    objBFERequest.Imp_moneda_ctz = Convert.ToDouble(docBatch.RequestHeaders[0].TasaCambio);
                    fieldName = "ImporteRNI_PercepcionMonedaFacturacion";
                    objBFERequest.Impto_liq_rni = Convert.ToDouble(docBatch.RequestHeaders[0].ImporteRNI_PercepcionMonedaFacturacion);

                    objBFERequest.Zona = 1;

                    objBFERequest.Items = new wsbfe.Item[Convert.ToInt32(docBatch.RequestHeaders[0].CantidadRegistrosDetalle)];

                    for (i = 0; i < objBFERequest.Items.Length; i++)
                    {
                        seccionName = "Línea " + i.ToString();
                        objBFERequest.Items[i] = new wsbfe.Item();
                        fieldName = "CodigoProductoEmpresa";
                        objBFERequest.Items[i].Pro_codigo_sec = docBatch.RequestHeaders[0].RequestLines[i].CodigoProductoEmpresa;
                        fieldName = "CodigoProductoNCM";
                        objBFERequest.Items[i].Pro_codigo_ncm = docBatch.RequestHeaders[0].RequestLines[i].CodigoProductoNCM;
                        fieldName = "Descripcion";
                        objBFERequest.Items[i].Pro_ds = docBatch.RequestHeaders[0].RequestLines[i].Descripcion;
                        fieldName = "UnidadMedida";
                        objBFERequest.Items[i].Pro_umed = Convert.ToInt32(docBatch.RequestHeaders[0].RequestLines[i].UnidadMedida);
                        fieldName = "Cantidad";
                        objBFERequest.Items[i].Pro_qty = Convert.ToDouble(docBatch.RequestHeaders[0].RequestLines[i].Cantidad);
                        fieldName = "ImportePrecioUnitarioMonedaFacturacion";
                        objBFERequest.Items[i].Pro_precio_uni = Convert.ToDouble(docBatch.RequestHeaders[0].RequestLines[i].ImportePrecioUnitarioMonedaFacturacion);
                        fieldName = "ImporteSubtotalMonedaFacturacion";
                        objBFERequest.Items[i].Imp_total = Convert.ToDouble(docBatch.RequestHeaders[0].RequestLines[i].ImporteSubtotalMonedaFacturacion);
                        fieldName = "ImporteBonificacionMonedaFacturacion";
                        objBFERequest.Items[i].Imp_bonif = Convert.ToDouble(docBatch.RequestHeaders[0].RequestLines[i].ImporteBonificacionMonedaFacturacion);
                        fieldName = "AlicuotaIVA";
                        objBFERequest.Items[i].Iva_id = Convert.ToInt16(docBatch.RequestHeaders[0].RequestLines[i].AlicuotaIVA);
                    }
                }
                catch (Exception ex)
                {
                    sqlEngine.LogError("0", "0", "Autorización", "Error al asignar el campo: " + seccionName + "." + fieldName + ", " + ex.Message);
                }

                //DEBUG LINE
                if (Convert.ToBoolean(oSettings.ActivarDebug))
                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(objBFERequest), oSettings.PathDebug + "\\ClsBFERequest-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                try
                {
                    objBFEResponseAuthorize = bfeService.BFEAuthorize(objBFEAuthRequest, objBFERequest);

                    ////WORKAROUND FE BIENES DE CAPITAL
                    if ((objBFEResponseAuthorize == null || objBFEResponseAuthorize.BFEResultAuth == null || objBFEResponseAuthorize.BFEResultAuth.Fch_venc_Cae == null || objBFEResponseAuthorize.BFEResultAuth.Fch_venc_Cae == string.Empty) &&
                        (objBFEResponseAuthorize.BFEResultAuth.Obs == string.Empty) &&
                        (objBFEResponseAuthorize.BFEErr == null ))
                    {

                        //WORKAROUND FE BIENES DE CAPITAL, REINTENTO 3 VECES EN LAPSOS DE 40 SEGUNDOS
                        for (int iw = 0; iw < 5; iw++)
                        {
                            //espero 40 seg
                            System.Threading.Thread.Sleep(60000);

                            //consulto el cae
                            objBFEResponseAuthorize = ReprocessOnError(objBFEAuthRequest, objBFERequest);

                            //verifico si me devuelve el cae
                            if (objBFEResponseAuthorize != null && objBFEResponseAuthorize.BFEResultAuth != null && objBFEResponseAuthorize.BFEResultAuth.Fch_venc_Cae != null && objBFEResponseAuthorize.BFEResultAuth.Fch_venc_Cae != string.Empty)
                                break;
                        }
                    }
                }
                catch
                {
                    //WORKAROUND FE BIENES DE CAPITAL, REINTENTO 3 VECES EN LAPSOS DE 40 SEGUNDOS
                    for (int iw = 0; iw < 5; iw++)
                    {
                        //espero 40 seg
                        System.Threading.Thread.Sleep(60000);

                        //consulto el cae
                        objBFEResponseAuthorize = ReprocessOnError(objBFEAuthRequest, objBFERequest);

                        //verifico si me devuelve el cae
                        if (objBFEResponseAuthorize != null && objBFEResponseAuthorize.BFEResultAuth != null && objBFEResponseAuthorize.BFEResultAuth.Fch_venc_Cae != null && objBFEResponseAuthorize.BFEResultAuth.Fch_venc_Cae != string.Empty)
                            break;
                    }
                }

                //DEBUG LINE
                if (Convert.ToBoolean(oSettings.ActivarDebug))
                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(objBFEResponseAuthorize), oSettings.PathDebug + "\\BFEResponseAuthorize-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");
            }
            catch (Exception ex)
            {
                int iElement = 0;
                if (i > 0)
                    iElement = i - 1;
                else
                    iElement = 0;

                if (docBatch == null || (docBatch.RequestHeaders == null && docBatch.RequestHeaders.Count == 0))
                {
                    sqlEngine.LogError("0", "0", "Autorización", "Error: " + ex.Message);
                }
                else
                {
                    if(docBatch.RequestHeaders[iElement] != null)
                        sqlEngine.LogError(docBatch.RequestHeaders[iElement].SQLID, "0", "Autorización", "Error: " + ex.Message);
                    else
                        sqlEngine.LogError("0", "0", "Autorización", "Error: " + ex.Message);
                }

                objBFEResponseAuthorize.BFEErr = new FacturaElectronica.WebServices.wsbfe.ClsBFEErr();

                if (docBatch.BatchUniqueId == "AUTO" || objBFEResponseLastID.BFEResultGet == null)
                {
                    objBFEResponseAuthorize.BFEErr.ErrCode = 667;
                    objBFEResponseAuthorize.BFEErr.ErrMsg = ex.Message + "Error en AFIP al obtener el último nro de requerimiento (" + objBFEResponseLastID.BFEErr.ErrCode.ToString() + ") " + objBFEResponseLastID.BFEErr.ErrMsg;
                }
                else
                {
                    objBFEResponseAuthorize.BFEErr.ErrCode = 668;
                    objBFEResponseAuthorize.BFEErr.ErrMsg = ex.Message;
                    sqlEngine.LogError(docBatch.RequestHeaders[iElement].SQLID, "0", "Autorización", "Error no conocido: (AfipBFE) " + ex.Message);
                }
            }

            return objBFEResponseAuthorize;
        }
Beispiel #30
0
        //todo: hacer
        private void ProcessDownload(string EmpresaID)
        {
            Settings oSettings = new Settings(EmpresaID);

            FEPrint.FEPrintService FEPrintService = new FEPrint.FEPrintService();
            FEPrintService.Url = oSettings.UrlPrintWebService;
            FEPrintService.Credentials = System.Net.CredentialCache.DefaultCredentials;

            string strIds = Request.QueryString["ids"];
            string strId = string.Empty;
            string strTipoCbte = string.Empty;
            string strNumeroLegal = string.Empty;
            string strTipoCbteName = string.Empty;

            try
            {
                foreach (string strCbte in strIds.Split('|'))
                {
                    if (strCbte != string.Empty && strCbte.Split(';').Length == 3)
                    {
                        strId = strCbte.Split(';')[0];
                        strTipoCbte = strCbte.Split(';')[1];
                        strNumeroLegal = strCbte.Split(';')[2];

                        string fileName = oSettings.PathTemporales + @"\" + strNumeroLegal;

                        FEPrintService.GetCbte(EmpresaID, strId, FEPrint.TipoDeCopia.Original);//(byte[])sqlDReader["PDF" + strType];

                        if (!fiZip.EntryFileNames.Contains("Comprobantes/" + strNumeroLegal + "-" + strTipoCbteName + "-Original.pdf"))
                            fiZip.AddFile(fileName + "-" + strTipoCbteName + "-Original.pdf", "Comprobantes");

                        if (!fiZip.EntryFileNames.Contains("Comprobantes/" + strNumeroLegal + "-" + strTipoCbteName + "-Duplicado.pdf"))
                            fiZip.AddFile(fileName + "-" + strTipoCbteName + "-Duplicado.pdf", "Comprobantes");

                        if (!fiZip.EntryFileNames.Contains("Comprobantes/" + strNumeroLegal + "-" + strTipoCbteName + "-Triplicado.pdf"))
                            fiZip.AddFile(fileName + "-" + strTipoCbteName + "-Triplicado.pdf", "Comprobantes");
                    }
                }

                if (fiZip.Count > 0)
                {
                    LoadZipFile(fiZip);
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
                Response.End();
            }

            Page.ClientScript.RegisterStartupScript(this.GetType(), "Popup", "window.close();", true);
        }