Ejemplo n.º 1
0
        public string ReprocesarLoteFacturasExportacion(string EmpresaID, RequestBatch documentBatch)
        {
            ResponseBatch responseBatch = new ResponseBatch();
            try
            {
                string result = ProcesarLoteFacturasBienesServicios(EmpresaID, documentBatch.GetXMLString());
                responseBatch.LoadXMLString(result);
            }
            catch (Exception ex)
            {
                responseBatch.MensajeError = ex.Message;
            }

            return string.Empty;
        }
Ejemplo n.º 2
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.");
            }
        }
Ejemplo n.º 3
0
        public ResponseBatch ProcesarLoteFacturasExportacionObj(string EmpresaID, RequestBatch documentBatch)
        {
            ResponseBatch responseBatch = new ResponseBatch();
            try
            {
                string result = ProcesarLoteFacturasExportacion(EmpresaID, documentBatch.GetXMLString());
                responseBatch.LoadXMLString(result);
            }
            catch (Exception ex)
            {
                responseBatch.MensajeError = ex.Message;
            }

            return responseBatch;
        }
Ejemplo n.º 4
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();
        }
Ejemplo n.º 5
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();
        }
Ejemplo n.º 6
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();
        }
Ejemplo n.º 7
0
        public void ProcessResponse(ResponseBatch responseBatch, Settings oSettings)
        {
            XmlDocument xmlResponse = new XmlDocument();
            XmlDocument xmlError = new XmlDocument();

            string[] FieldNames = null;
            string[] FieldTypes = null;
            string[] FieldValues = null;

            string ErrorCod = string.Empty;
            string ErrorMsg = string.Empty;

            string SqlID = "0";

            try
            {
                if (responseBatch != null && responseBatch.ResponseHeaders != null && responseBatch.ResponseHeaders.Count > 0)
                {
                    SqlID = responseBatch.ResponseHeaders[0].SQLID;

                    FieldNames = new string[] { "ESTADO", "CAE", "FECHAVENCCAE", "RESULTADO", "ERRCOD", "ERRMNG" };

                    //TODO: usar enum del SqlType
                    FieldTypes = new string[] { "NVarChar", "NVarChar", "SmallDateTime", "NVarChar", "NVarChar", "NVarChar" };

                    if (responseBatch != null && responseBatch.ResponseHeaders != null && responseBatch.ResponseHeaders.Count > 0)
                    {
                        if (responseBatch.Reproceso == "s" && responseBatch.ResponseHeaders[0].Resultado == "R")
                        {
                            ErrorCod = "12";
                            ErrorMsg = "El rango informado se encuentra autorizado con anterioridad para la misma CUIT, Tipo de Comprobante y Punto de Venta.";
                        }
                        else
                        {
                            if (responseBatch.ResponseHeaders[0].Observaciones.Count > 0)
                            {
                                foreach (ResponseHeaderObs obs in responseBatch.ResponseHeaders[0].Observaciones)
                                {
                                    ErrorCod += obs.Codigo + ";";
                                    ErrorMsg += obs.Msg + ";";
                                }
                            }
                            else
                            {
                                if (responseBatch.ResponseHeaders[0].Motivo != string.Empty)
                                {
                                    ErrorCod = responseBatch.ResponseHeaders[0].Motivo;
                                }
                                else
                                {
                                    ErrorCod = responseBatch.CodigoError;
                                }

                                if (responseBatch.ResponseHeaders[0].MotivoDescripcion != string.Empty)
                                {
                                    ErrorMsg = responseBatch.ResponseHeaders[0].MotivoDescripcion;
                                }
                                else
                                {
                                    ErrorMsg = responseBatch.MotivoDescripcion;
                                }
                            }
                        }
                        FieldValues = new string[] { "PROCESADO", responseBatch.ResponseHeaders[0].CAE, responseBatch.ResponseHeaders[0].FechaVencimiento, responseBatch.Resultado, ErrorCod, ErrorMsg };
                    }
                    else
                    {
                        ErrorCod = responseBatch.CodigoError;
                        ErrorMsg = responseBatch.MotivoDescripcion;

                        FieldValues = new string[] { "PROCESADO", "", "", responseBatch.Resultado, ErrorCod, ErrorMsg };
                    }

                    if (ErrorCod != string.Empty || ErrorMsg != string.Empty)
                    {
                        sqlEngine.LogError(SqlID, "0", ErrorCod, ErrorMsg);
                    }

                    try
                    {
                        //modifico base intermedia
                        SetData(oSettings.Entrada.Split('\\')[0], oSettings.Entrada.Split('\\')[1], oSettings.Entrada.Split('\\')[2], oSettings.Entrada.Split('\\')[3], responseBatch.ResponseHeaders[0].NroInternoERP, FieldNames, FieldTypes, FieldValues);

                        if (Convert.ToBoolean(oSettings.ActivarDebug))
                            Utils.Utils.DebugLine("<DBResult><Accion>MODIFICAR BASE INTERMEDIA(SetData)</Accion><Resultado>OK</Resultado></DBResult>", oSettings.PathDebug + "\\" + SqlID + "-P5.DBUPDATE-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");
                    }
                    catch (Exception ex)
                    {
                        if (Convert.ToBoolean(oSettings.ActivarDebug))
                            Utils.Utils.DebugLine("<DBResult><Accion>MODIFICAR BASE INTERMEDIA(SetData)</Accion><Resultado>Error: " + ex.Message + "</Resultado></DBResult>", oSettings.PathDebug + "\\" + SqlID + "-P5.DBUPDATE-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                        sqlEngine.LogError(SqlID, "0", "ProcessResponse. Modificar en Base Intermedia.", "Exeption1: " + ex.Message);
                    }
                }
                else
                {
                    if (Convert.ToBoolean(oSettings.ActivarDebug))
                        Utils.Utils.DebugLine("<DBResult><Accion>MODIFICAR BASE INTERMEDIA</Accion><Resultado>Error: responseBatch esta vacio.</Resultado></DBResult>", oSettings.PathDebug + "\\" + SqlID + "-P5.DBUPDATE-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");
                }
            }
            catch(Exception ex)
            {
                if (Convert.ToBoolean(oSettings.ActivarDebug))
                    Utils.Utils.DebugLine("<DBResult><Accion>MODIFICAR BASE INTERMEDIA</Accion><Resultado>Error: " + ex.Message + "</Resultado></DBResult>", oSettings.PathDebug + "\\" + SqlID + "-P5.DBUPDATE-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                sqlEngine.LogError(SqlID, "0", "ProcessResponse. Modificar en Base Intermedia.", "Exeption2: " + ex.Message);
            }
        }