示例#1
0
        public bool LoadXMLString(string xmlString)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xmlString);

                BatchUniqueId = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/BatchUniqueId");
                CUITInformante = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/CUITInformante");
                FechaCAE = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/FechaCAE");
                CantidadComprobantes = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/CantidadComprobantes");
                Resultado = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Resultado");
                Motivo = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Motivo");
                MotivoDescripcion = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/MotivoDescripcion");
                Reproceso = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Reproceso");
                SonServicios = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/SonServicios");

                CodigoError = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Error/CodigoError");
                MensajeError = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Error/MensajeError");

                //Agrego todos los comprobantes
                for (int i = 0; i < xmlDoc.SelectNodes("/RespuestaLoteComprobantes/Comprobante").Count; i++)
                {
                    ResponseHeader thisHeader = new ResponseHeader();
                    thisHeader.CodigoDocumentoComprador = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "CodigoDocumentoComprador", i);
                    thisHeader.NroDocumentoComprador = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "NroDocumentoComprador", i);
                    thisHeader.TipoComprobante = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "TipoComprobante", i);
                    thisHeader.PuntoVenta = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "PuntoVenta", i);
                    thisHeader.LetraComprobante = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "LetraComprobante", i);
                    thisHeader.NroComprobanteDesde = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "NroComprobanteDesde", i);
                    thisHeader.NroComprobanteHasta = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "NroComprobanteHasta", i);
                    thisHeader.Importe = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "Importe", i);
                    thisHeader.ImporteNoGravado = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "ImporteNoGravado", i);
                    thisHeader.ImporteGravado = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "ImporteGravado", i);
                    thisHeader.ImporteImpuestoLiquidado = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "ImporteImpuestoLiquidado", i);
                    thisHeader.ImporteRNI_Percepcion = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "ImporteRNI_Percepcion", i);
                    thisHeader.ImporteExento = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "ImporteExento", i);
                    thisHeader.Resultado = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "Resultado", i);
                    thisHeader.CAE = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "CAE", i);
                    thisHeader.FechaComprobante = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "FechaComprobante", i);
                    thisHeader.FechaVencimiento = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "FechaVencimiento", i);
                    thisHeader.Motivo = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "Motivo", i);
                    thisHeader.MotivoDescripcion = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "MotivoDescripcion", i);
                    thisHeader.FechaDesdeServicioFacturado = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "FechaDesdeServicioFacturado", i);
                    thisHeader.FechaHastaServicioFacturado = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "FechaHastaServicioFacturado", i);
                    thisHeader.FechaVencimientoPago = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "FechaVencimientoPago", i);
                    thisHeader.UltimoIDUsado = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "UltimoIDUsado", i);
                    thisHeader.UltimoNroComprobanteUsado = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "UltimoNroComprobanteUsado", i);
                    thisHeader.NroInternoERP = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "NroInternoERP", i);
                    thisHeader.SQLID = ValidXMLValue(xmlDoc, "/RespuestaLoteComprobantes/Comprobante", "SQLID", i);

                    //NUEVO DESDE LA VERSION 1 DE AFIP
                    //Agrego las observaciones por comprobante
                    foreach (XmlNode ObsNode in xmlDoc.SelectNodes("/RespuestaLoteComprobantes/Comprobante")[i].SelectNodes("Observaciones/Obs"))
                    {
                        ResponseHeaderObs Obs = new ResponseHeaderObs();
                        Obs.Codigo = ObsNode["Codigo"].InnerText;
                        Obs.Msg = ObsNode["Msg"].InnerText;

                        thisHeader.Observaciones.Add(Obs);
                    }

                    ResponseHeaders.Add(thisHeader);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("FacturaElectronica", ex.Message, System.Diagnostics.EventLogEntryType.Error);
                return false;
            }

            return true;
        }
示例#2
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();
        }