Пример #1
0
        public wsbfe.BFEResponseAuthorize BFEAuthorize(RequestBatch docBatch, Settings oSettings)
        {
            wsbfe.ClsBFERequest objBFERequest = new wsbfe.ClsBFERequest();
            wsbfe.BFEResponseAuthorize objBFEResponseAuthorize = new wsbfe.BFEResponseAuthorize();
            wsbfe.BFEResponse_LastID objBFEResponseLastID = null;

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

            int i = 0;

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

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

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

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

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

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

                    objBFERequest.Zona = 1;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return objBFEResponseAuthorize;
        }
Пример #2
0
        private void ResponseError(RequestBatch docBatch, FileInfo fi, string TipoLote, string strError, Settings oSettings)
        {
            XmlDocument respSEW = new XmlDocument();
            XmlElement xmlElem = respSEW.CreateElement("comprobantes");
            XmlNode rootNode = respSEW.AppendChild(xmlElem);
            XmlNode detailsNode;

            XmlNode comprobanteNode = null;
            XmlAttribute comprobanteAttr = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        sqlEngine.UpdateCabeceraNombreObjetoSalida(thisResponse.SQLID, fileNameRespuesta);

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

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

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

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

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

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

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

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

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

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

                //Guardo la respuesta sino hay errores
                if (respSEW.SelectSingleNode("comprobantes/comprobante/nro") != null && respSEW.SelectSingleNode("comprobantes/comprobante/nro").InnerText != string.Empty &&
                    respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut") != null && respSEW.SelectSingleNode("comprobantes/comprobante/tipocodaut").InnerText != string.Empty &&
                    respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Tipo_cbte").InnerText != string.Empty &&
                    respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta") != null && respSEW.SelectSingleNode("comprobantes/comprobante/Punto_vta").InnerText != string.Empty)
                {
                    respSEW.Save(oSettings.Salida + "\\" + fileNameRespuesta.Replace(".txt", string.Empty));
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("File Engine", "Error: " + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
        }
Пример #3
0
        public wsfex.FEXResponseAuthorize FEXAuthRequest(RequestBatch docBatch, Settings oSettings )
        {
            wsfex.ClsFEXRequest objFEXRequest = new wsfex.ClsFEXRequest();
            wsfex.FEXResponseAuthorize objFEXResponseAuthorize = new wsfex.FEXResponseAuthorize();
            wsfex.FEXResponse_LastID objFEXResponseLastID = null;

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

            int i = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return objFEXResponseAuthorize;
        }
Пример #4
0
        public bool LogBatchStart(ref RequestBatch thisBatch)
        {
            SqlCommand dbQuery = null;

            string cmd = string.Empty;

            bool bResult = false;

            try
            {
                if (Open())
                {
                    foreach (RequestHeader thisHeader in thisBatch.RequestHeaders)
                    {
                        cmd = "insert into CbteCabecera (UniqueIdentifier, EmpresaID, EstadoTransaccion, TipoTransaccion, FechaComprobante, TipoComprobante, PuntoVenta, ";
                        cmd += "NroComprobanteDesde, NroComprobanteHasta, CompradorCodigoDocumento, CompradorNroDocumento, ";
                        cmd += "CompradorTipoResponsable, CompradorTipoResponsableDescripcion, CompradorRazonSocial, ";
                        cmd += "FechaDesdeServicioFacturado, FechaHastaServicioFacturado, FechaVencimientoPago, CondicionPago, ";
                        cmd += "CompradorDireccion, CompradorLocalidad, CompradorProvincia, CompradorPais, CompradorCodigoPostal, ";
                        cmd += "CompradorNroIIBB, CompradorCodigoCliente, CompradorNroReferencia, CompradorEmail, ";
                        cmd += "NroRemito, Importe, ImporteComprobanteB, ImporteNoGravado, ImporteGravado, AlicuotaIVA, ImporteImpuestoLiquidado, ";
                        cmd += "ImporteRNI_Percepcion, ImporteExento, ImportePercepciones_PagosCuentaImpuestosNacionales, ";
                        cmd += "ImportePercepcionIIBB, TasaIIBB, CodigoJurisdiccionIIBB, ImportePercepcionImpuestosMunicipales, ";
                        cmd += "JurisdiccionImpuestosMunicipales, ImporteImpuestosInternos, ImporteMonedaFacturacion, ImporteMonedaFacturacionComprobanteB, ImporteNoGravadoMonedaFacturacion, ";
                        cmd += "ImporteGravadoMonedaFacturacion, ImporteImpuestoLiquidadoMonedaFacturacion, ImporteRNI_PercepcionMonedaFacturacion, ";
                        cmd += "ImporteExentoMonedaFacturacion, ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion, ";
                        cmd += "ImportePercepcionIIBBMonedaFacturacion, ImportePercepcionImpuestosMunicipalesMonedaFacturacion, ";
                        cmd += "ImporteImpuestosInternosMonedaFacturacion, CantidadAlicuotasIVA, CodigoOperacion, TasaCambio, ";
                        cmd += "CodigoMoneda, ImporteEscrito, CantidadRegistrosDetalle, CodigoMecanismoDistribucion, TipoExportacion, ";
                        cmd += "PermisoExistente, FormaPagoDescripcion, IncoTerms, Idioma, Observaciones1, ";
                        cmd += "Observaciones2, Observaciones3, LetraComprobante, NroInternoERP, ";
                        cmd += "EmisorRazonSocial, EmisorDireccion, EmisorCalle, EmisorCP, EmisorLocalidad, ";
                        cmd += "EmisorProvincia, EmisorPais, EmisorTelefonos, EmisorEMail, OficinaVentas, RapiPago, ObservacionRapiPago, PagoFacil, ";
                        cmd += "OPER, NOPER, DAGRUF, FACTORI, FACTORI_FORMATEADO,USUARIO, FECPG1_FORMATEADO, FECPG2_FORMATEADO, CUOTAIVA105, CUOTAIVA21)";

                        cmd += "values (@NroInternoERP, @EmpresaID, @Iniciada, @TipoTransaccion, @FechaComprobante, @TipoComprobante, @PuntoVenta, ";
                        cmd += "@NroComprobanteDesde, @NroComprobanteHasta, @CompradorCodigoDocumento, @CompradorNroDocumento, ";
                        cmd += "@CompradorTipoResponsable, @CompradorTipoResponsableDescripcion, @CompradorRazonSocial, ";
                        cmd += "@FechaDesdeServicioFacturado, @FechaHastaServicioFacturado, @FechaVencimientoPago, @CondicionPago, ";
                        cmd += "@CompradorDireccion, @CompradorLocalidad, @CompradorProvincia, @CompradorPais, @CompradorCodigoPostal, ";
                        cmd += "@CompradorNroIIBB, @CompradorCodigoCliente, @CompradorNroReferencia, @CompradorEmail, ";
                        cmd += "@NroRemito, @Importe, @ImporteComprobanteB, @ImporteNoGravado, @ImporteGravado, @AlicuotaIVA, @ImporteImpuestoLiquidado, ";
                        cmd += "@ImporteRNI_Percepcion, @ImporteExento, @ImportePercepciones_PagosCuentaImpuestosNacionales, ";
                        cmd += "@ImportePercepcionIIBB, @TasaIIBB, @CodigoJurisdiccionIIBB, @ImportePercepcionImpuestosMunicipales, ";
                        cmd += "@JurisdiccionImpuestosMunicipales, @ImporteImpuestosInternos, @ImporteMonedaFacturacion, @ImporteMonedaFacturacionComprobanteB, @ImporteNoGravadoMonedaFacturacion, ";
                        cmd += "@ImporteGravadoMonedaFacturacion, @ImporteImpuestoLiquidadoMonedaFacturacion, @ImporteRNI_PercepcionMonedaFacturacion, ";
                        cmd += "@ImporteExentoMonedaFacturacion, @ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion, ";
                        cmd += "@ImportePercepcionIIBBMonedaFacturacion, @ImportePercepcionImpuestosMunicipalesMonedaFacturacion, ";
                        cmd += "@ImporteImpuestosInternosMonedaFacturacion, @CantidadAlicuotasIVA, @CodigoOperacion, @TasaCambio, ";
                        cmd += "@CodigoMoneda, @ImporteEscrito, @CantidadRegistrosDetalle, @CodigoMecanismoDistribucion, @TipoExportacion, ";
                        cmd += "@PermisoExistente, @FormaPagoDescripcion, @IncoTerms, @Idioma, @Observaciones1, ";
                        cmd += "@Observaciones2, @Observaciones3, @LetraComprobante, @NroInternoERP, ";
                        cmd += "@EmisorRazonSocial, @EmisorDireccion, @EmisorCalle, @EmisorCP, @EmisorLocalidad, ";
                        cmd += "@EmisorProvincia, @EmisorPais, @EmisorTelefonos, @EmisorEMail, @OficinaVentas, @RapiPago, @ObservacionRapiPago, @PagoFacil, ";
                        cmd += "@OPER, @NOPER, @DAGRUF, @FACTORI, @FACTORI_FORMATEADO, @USUARIO, @FECPG1_FORMATEADO, @FECPG2_FORMATEADO, @CUOTAIVA105, @CUOTAIVA21) ";

                        cmd += "SET @CabeceraID = SCOPE_IDENTITY()";

                        dbQuery = new SqlCommand();
                        dbQuery.Connection = dbConnection;
                        dbQuery.CommandText = cmd;

                        dbQuery.Parameters.Add(new SqlParameter("@CabeceraID", System.Data.SqlDbType.Int));
                        dbQuery.Parameters["@CabeceraID"].Direction = System.Data.ParameterDirection.Output;

                        dbQuery.Parameters.Add(new SqlParameter("@NroInternoERP", thisHeader.NroInternoERP));
                        dbQuery.Parameters.Add(new SqlParameter("@EmpresaID", Convert.ToInt16(thisHeader.EmpresaID)));
                        dbQuery.Parameters.Add(new SqlParameter("@Iniciada", "Iniciada"));
                        dbQuery.Parameters.Add(new SqlParameter("@TipoTransaccion", thisHeader.TipoTransaccion));
                        dbQuery.Parameters.Add(new SqlParameter("@FechaComprobante", Convert.ToDateTime(thisHeader.FechaComprobante)));
                        dbQuery.Parameters.Add(new SqlParameter("@TipoComprobante", thisHeader.TipoComprobante));
                        dbQuery.Parameters.Add(new SqlParameter("@PuntoVenta", thisHeader.PuntoVenta));

                        dbQuery.Parameters.Add(new SqlParameter("@NroComprobanteDesde", thisHeader.NroComprobanteDesde));
                        dbQuery.Parameters.Add(new SqlParameter("@NroComprobanteHasta", thisHeader.NroComprobanteHasta));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorCodigoDocumento", thisHeader.CompradorCodigoDocumento));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorNroDocumento", thisHeader.CompradorNroDocumento));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorTipoResponsable", thisHeader.CompradorTipoResponsable));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorTipoResponsableDescripcion", thisHeader.CompradorTipoResponsableDescripcion));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorRazonSocial", thisHeader.CompradorRazonSocial));
                        dbQuery.Parameters.Add(new SqlParameter("@FechaDesdeServicioFacturado", Convert.ToDateTime(thisHeader.FechaDesdeServicioFacturado)));
                        dbQuery.Parameters.Add(new SqlParameter("@FechaHastaServicioFacturado", Convert.ToDateTime(thisHeader.FechaHastaServicioFacturado)));
                        dbQuery.Parameters.Add(new SqlParameter("@FechaVencimientoPago", Convert.ToDateTime(thisHeader.FechaVencimientoPago)));
                        dbQuery.Parameters.Add(new SqlParameter("@CondicionPago", thisHeader.CondicionPago));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorDireccion", thisHeader.CompradorDireccion));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorLocalidad", thisHeader.CompradorLocalidad));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorProvincia", thisHeader.CompradorProvincia));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorPais", thisHeader.CompradorPais));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorCodigoPostal", thisHeader.CompradorCodigoPostal));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorNroIIBB", thisHeader.CompradorNroIIBB));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorCodigoCliente", thisHeader.CompradorCodigoCliente));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorNroReferencia", thisHeader.CompradorNroReferencia));
                        dbQuery.Parameters.Add(new SqlParameter("@CompradorEmail", thisHeader.CompradorEmail));
                        dbQuery.Parameters.Add(new SqlParameter("@NroRemito", thisHeader.NroRemito));
                        dbQuery.Parameters.Add(new SqlParameter("@CodigoJurisdiccionIIBB", thisHeader.CodigoJurisdiccionIIBB));
                        dbQuery.Parameters.Add(new SqlParameter("@TasaIIBB", thisHeader.TasaIIBB));
                        dbQuery.Parameters.Add(new SqlParameter("@JurisdiccionImpuestosMunicipales", thisHeader.JurisdiccionImpuestosMunicipales));

                        thisHeader.Importe = GetFormatedFloat( thisHeader.Importe);
                        dbQuery.Parameters.Add(new SqlParameter("@Importe", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@Importe"].Value = thisHeader.Importe;

                        thisHeader.ImporteComprobanteB  = GetFormatedFloat( thisHeader.ImporteComprobanteB);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteComprobanteB", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteComprobanteB"].Value = thisHeader.ImporteComprobanteB;

                        thisHeader.ImporteNoGravado = GetFormatedFloat( thisHeader.ImporteNoGravado);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteNoGravado", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteNoGravado"].Value = thisHeader.ImporteNoGravado;

                        thisHeader.ImporteGravado = GetFormatedFloat( thisHeader.ImporteGravado);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteGravado", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteGravado"].Value = thisHeader.ImporteGravado;

                        thisHeader.AlicuotaIVA = GetFormatedFloat( thisHeader.AlicuotaIVA);
                        dbQuery.Parameters.Add(new SqlParameter("@AlicuotaIVA", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@AlicuotaIVA"].Value = thisHeader.AlicuotaIVA;

                        thisHeader.ImporteImpuestoLiquidado = GetFormatedFloat( thisHeader.ImporteImpuestoLiquidado);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteImpuestoLiquidado", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteImpuestoLiquidado"].Value = thisHeader.ImporteImpuestoLiquidado;

                        thisHeader.ImporteRNI_Percepcion = GetFormatedFloat( thisHeader.ImporteRNI_Percepcion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteRNI_Percepcion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteRNI_Percepcion"].Value = thisHeader.ImporteRNI_Percepcion;

                        thisHeader.ImporteExento = GetFormatedFloat( thisHeader.ImporteExento );
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteExento", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteExento"].Value = thisHeader.ImporteExento;

                        thisHeader.ImportePercepciones_PagosCuentaImpuestosNacionales = GetFormatedFloat( thisHeader.ImportePercepciones_PagosCuentaImpuestosNacionales);
                        dbQuery.Parameters.Add(new SqlParameter("@ImportePercepciones_PagosCuentaImpuestosNacionales", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImportePercepciones_PagosCuentaImpuestosNacionales"].Value = thisHeader.ImportePercepciones_PagosCuentaImpuestosNacionales;

                        thisHeader.ImportePercepcionIIBB = GetFormatedFloat(thisHeader.ImportePercepcionIIBB);
                        dbQuery.Parameters.Add(new SqlParameter("@ImportePercepcionIIBB", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImportePercepcionIIBB"].Value = thisHeader.ImportePercepcionIIBB;

                        thisHeader.ImportePercepcionImpuestosMunicipales = GetFormatedFloat( thisHeader.ImportePercepcionImpuestosMunicipales);
                        dbQuery.Parameters.Add(new SqlParameter("@ImportePercepcionImpuestosMunicipales", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImportePercepcionImpuestosMunicipales"].Value = thisHeader.ImportePercepcionImpuestosMunicipales;

                        thisHeader.ImporteImpuestosInternos = GetFormatedFloat( thisHeader.ImporteImpuestosInternos);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteImpuestosInternos", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteImpuestosInternos"].Value = thisHeader.ImporteImpuestosInternos;

                        thisHeader.ImporteMonedaFacturacion = GetFormatedFloat( thisHeader.ImporteMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteMonedaFacturacion"].Value = thisHeader.ImporteMonedaFacturacion;

                        thisHeader.ImporteMonedaFacturacionComprobanteB = GetFormatedFloat( thisHeader.ImporteMonedaFacturacionComprobanteB);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteMonedaFacturacionComprobanteB", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteMonedaFacturacionComprobanteB"].Value = thisHeader.ImporteMonedaFacturacionComprobanteB;

                        thisHeader.ImporteNoGravadoMonedaFacturacion = GetFormatedFloat( thisHeader.ImporteNoGravadoMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteNoGravadoMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteNoGravadoMonedaFacturacion"].Value = thisHeader.ImporteNoGravadoMonedaFacturacion;

                        thisHeader.ImporteGravadoMonedaFacturacion = GetFormatedFloat( thisHeader.ImporteGravadoMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteGravadoMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteGravadoMonedaFacturacion"].Value = thisHeader.ImporteGravadoMonedaFacturacion;

                        thisHeader.ImporteImpuestoLiquidadoMonedaFacturacion = GetFormatedFloat( thisHeader.ImporteImpuestoLiquidadoMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteImpuestoLiquidadoMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteImpuestoLiquidadoMonedaFacturacion"].Value = thisHeader.ImporteImpuestoLiquidadoMonedaFacturacion;

                        thisHeader.ImporteRNI_PercepcionMonedaFacturacion = GetFormatedFloat( thisHeader.ImporteRNI_PercepcionMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteRNI_PercepcionMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteRNI_PercepcionMonedaFacturacion"].Value = thisHeader.ImporteRNI_PercepcionMonedaFacturacion;

                        thisHeader.ImporteExentoMonedaFacturacion = GetFormatedFloat( thisHeader.ImporteExentoMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteExentoMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteExentoMonedaFacturacion"].Value = thisHeader.ImporteExentoMonedaFacturacion;

                        thisHeader.ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion = GetFormatedFloat( thisHeader.ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion"].Value = thisHeader.ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion;

                        thisHeader.ImportePercepcionIIBBMonedaFacturacion = GetFormatedFloat( thisHeader.ImportePercepcionIIBBMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImportePercepcionIIBBMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImportePercepcionIIBBMonedaFacturacion"].Value = thisHeader.ImportePercepcionIIBBMonedaFacturacion;

                        thisHeader.ImportePercepcionImpuestosMunicipalesMonedaFacturacion = GetFormatedFloat( thisHeader.ImportePercepcionImpuestosMunicipalesMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImportePercepcionImpuestosMunicipalesMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImportePercepcionImpuestosMunicipalesMonedaFacturacion"].Value = thisHeader.ImportePercepcionImpuestosMunicipalesMonedaFacturacion;

                        thisHeader.ImporteImpuestosInternosMonedaFacturacion = GetFormatedFloat( thisHeader.ImporteImpuestosInternosMonedaFacturacion);
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteImpuestosInternosMonedaFacturacion", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@ImporteImpuestosInternosMonedaFacturacion"].Value = thisHeader.ImporteImpuestosInternosMonedaFacturacion;

                        thisHeader.CantidadAlicuotasIVA = GetFormatedFloat( thisHeader.CantidadAlicuotasIVA);
                        dbQuery.Parameters.Add(new SqlParameter("@CantidadAlicuotasIVA", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@CantidadAlicuotasIVA"].Value = thisHeader.CantidadAlicuotasIVA;

                        thisHeader.TasaCambio = GetFormatedFloat( thisHeader.TasaCambio);
                        dbQuery.Parameters.Add(new SqlParameter("@TasaCambio", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@TasaCambio"].Value = thisHeader.TasaCambio;

                        thisHeader.CantidadRegistrosDetalle = GetFormatedFloat( thisHeader.CantidadRegistrosDetalle);
                        dbQuery.Parameters.Add(new SqlParameter("@CantidadRegistrosDetalle", System.Data.SqlDbType.Int));
                        dbQuery.Parameters["@CantidadRegistrosDetalle"].Value = thisHeader.CantidadRegistrosDetalle;

                        dbQuery.Parameters.Add(new SqlParameter("@CodigoMoneda", thisHeader.CodigoMoneda));
                        dbQuery.Parameters.Add(new SqlParameter("@ImporteEscrito", thisHeader.ImporteEscrito));
                        dbQuery.Parameters.Add(new SqlParameter("@CodigoOperacion", thisHeader.CodigoOperacion));
                        dbQuery.Parameters.Add(new SqlParameter("@CodigoMecanismoDistribucion", thisHeader.CodigoMecanismoDistribucion));
                        dbQuery.Parameters.Add(new SqlParameter("@TipoExportacion", thisHeader.TipoExportacion));
                        dbQuery.Parameters.Add(new SqlParameter("@PermisoExistente", thisHeader.PermisoExistente));
                        dbQuery.Parameters.Add(new SqlParameter("@FormaPagoDescripcion", thisHeader.FormaPagoDescripcion));
                        dbQuery.Parameters.Add(new SqlParameter("@IncoTerms", thisHeader.IncoTerms));
                        dbQuery.Parameters.Add(new SqlParameter("@Idioma", thisHeader.Idioma));
                        dbQuery.Parameters.Add(new SqlParameter("@Observaciones1", thisHeader.Observaciones1));
                        dbQuery.Parameters.Add(new SqlParameter("@Observaciones2", thisHeader.Observaciones2));
                        dbQuery.Parameters.Add(new SqlParameter("@Observaciones3", thisHeader.Observaciones3));
                        dbQuery.Parameters.Add(new SqlParameter("@LetraComprobante", thisHeader.LetraComprobante));
                        dbQuery.Parameters.Add(new SqlParameter("@EmisorRazonSocial", thisHeader.EmisorRazonSocial));
                        dbQuery.Parameters.Add(new SqlParameter("@EmisorDireccion", thisHeader.EmisorDireccion));
                        dbQuery.Parameters.Add(new SqlParameter("@EmisorCalle", thisHeader.EmisorCalle));
                        dbQuery.Parameters.Add(new SqlParameter("@EmisorCP", thisHeader.EmisorCP));
                        dbQuery.Parameters.Add(new SqlParameter("@EmisorLocalidad", thisHeader.EmisorLocalidad));
                        dbQuery.Parameters.Add(new SqlParameter("@EmisorProvincia", thisHeader.EmisorProvincia));
                        dbQuery.Parameters.Add(new SqlParameter("@EmisorPais", thisHeader.EmisorPais));
                        dbQuery.Parameters.Add(new SqlParameter("@EmisorTelefonos", thisHeader.EmisorTelefonos));
                        dbQuery.Parameters.Add(new SqlParameter("@EmisorEMail", thisHeader.EmisorEMail));
                        dbQuery.Parameters.Add(new SqlParameter("@OficinaVentas", thisHeader.OficinaVentas));
                        dbQuery.Parameters.Add(new SqlParameter("@RapiPago", thisHeader.RapiPago));
                        dbQuery.Parameters.Add(new SqlParameter("@ObservacionRapiPago", thisHeader.ObservacionRapiPago));
                        dbQuery.Parameters.Add(new SqlParameter("@PagoFacil", thisHeader.PagoFacil));
                        dbQuery.Parameters.Add(new SqlParameter("@OPER", thisHeader.OPER));
                        dbQuery.Parameters.Add(new SqlParameter("@NOPER", thisHeader.NOPER));
                        dbQuery.Parameters.Add(new SqlParameter("@DAGRUF", thisHeader.DAGRUF));
                        dbQuery.Parameters.Add(new SqlParameter("@FACTORI", thisHeader.FACTORI));
                        dbQuery.Parameters.Add(new SqlParameter("@FACTORI_FORMATEADO", thisHeader.FACTORI_FORMATEADO));
                        dbQuery.Parameters.Add(new SqlParameter("@USUARIO", thisHeader.USUARIO));
                        dbQuery.Parameters.Add(new SqlParameter("@FECPG1_FORMATEADO", thisHeader.FECPG1_FORMATEADO));
                        dbQuery.Parameters.Add(new SqlParameter("@FECPG2_FORMATEADO", thisHeader.FECPG2_FORMATEADO));

                        thisHeader.CUOTAIVA105 = GetFormatedFloat(  thisHeader.CUOTAIVA105);
                        dbQuery.Parameters.Add(new SqlParameter("@CUOTAIVA105", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@CUOTAIVA105"].Value = thisHeader.CUOTAIVA105;

                        thisHeader.CUOTAIVA21 = GetFormatedFloat( thisHeader.CUOTAIVA21);
                        dbQuery.Parameters.Add(new SqlParameter("@CUOTAIVA21", System.Data.SqlDbType.Float));
                        dbQuery.Parameters["@CUOTAIVA21"].Value = thisHeader.CUOTAIVA21;

                        dbQuery.ExecuteNonQuery();

                        thisHeader.SQLID = dbQuery.Parameters["@CabeceraID"].SqlValue.ToString();

                        foreach (RequestLine thisLine in thisHeader.RequestLines)
                        {
                            cmd = "insert into CbteLinea (CbteID, CodigoProductoEmpresa, CodigoProductoNCM, CodigoProductoSecretaria, ";
                            cmd += "Descripcion, Cantidad, UnidadMedida, ImportePrecioUnitario, ImporteBonificacion, ImporteAjuste, ";
                            cmd += "ImporteSubtotal, ImportePrecioUnitarioMonedaFacturacion, ImporteBonificacionMonedaFacturacion, ";
                            cmd += "ImporteAjusteMonedaFacturacion, ImporteSubtotalMonedaFacturacion, ImporteSubtotalMonedaFacturacionConIVA, ";
                            cmd += "AlicuotaIVA, IndicadorExentoGravadoNoGravado, Observaciones, MesPrestacion ) ";

                            cmd += "values (@cabeceraIdentity, @CodigoProductoEmpresa, @CodigoProductoNCM, @CodigoProductoSecretaria, ";
                            cmd += "@Descripcion, @Cantidad, @UnidadMedida, @ImportePrecioUnitario, @ImporteBonificacion, @ImporteAjuste, ";
                            cmd += "@ImporteSubtotal, @ImportePrecioUnitarioMonedaFacturacion, @ImporteBonificacionMonedaFacturacion, ";
                            cmd += "@ImporteAjusteMonedaFacturacion, @ImporteSubtotalMonedaFacturacion, @ImporteSubtotalMonedaFacturacionConIVA, ";
                            cmd += "@AlicuotaIVA, @IndicadorExentoGravadoNoGravado, @Observaciones, @MesPrestacion ) ";

                            cmd += "SET @LineaID = SCOPE_IDENTITY()";

                            dbQuery = new SqlCommand();
                            dbQuery.Connection = dbConnection;
                            dbQuery.CommandText = cmd;

                            dbQuery.Parameters.Add(new SqlParameter("@LineaID", System.Data.SqlDbType.Int));
                            dbQuery.Parameters["@LineaID"].Direction = System.Data.ParameterDirection.Output;

                            dbQuery.Parameters.Add(new SqlParameter("@cabeceraIdentity", Convert.ToInt32(thisHeader.SQLID)));
                            dbQuery.Parameters.Add(new SqlParameter("@CodigoProductoEmpresa", thisLine.CodigoProductoEmpresa));
                            dbQuery.Parameters.Add(new SqlParameter("@CodigoProductoNCM", thisLine.CodigoProductoNCM));
                            dbQuery.Parameters.Add(new SqlParameter("@CodigoProductoSecretaria", thisLine.CodigoProductoSecretaria));
                            dbQuery.Parameters.Add(new SqlParameter("@Descripcion", thisLine.Descripcion));
                            dbQuery.Parameters.Add(new SqlParameter("@UnidadMedida", thisLine.UnidadMedida));

                            thisLine.Cantidad = GetFormatedFloat(thisLine.Cantidad);
                            dbQuery.Parameters.Add(new SqlParameter("@Cantidad", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@Cantidad"].Value = thisLine.Cantidad;

                            thisLine.ImportePrecioUnitario = GetFormatedFloat(thisLine.ImportePrecioUnitario);
                            dbQuery.Parameters.Add(new SqlParameter("@ImportePrecioUnitario", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@ImportePrecioUnitario"].Value = thisLine.ImportePrecioUnitario;

                            thisLine.ImporteBonificacion = GetFormatedFloat(thisLine.ImporteBonificacion);
                            dbQuery.Parameters.Add(new SqlParameter("@ImporteBonificacion", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@ImporteBonificacion"].Value = thisLine.ImporteBonificacion;

                            thisLine.ImporteAjuste = GetFormatedFloat(thisLine.ImporteAjuste);
                            dbQuery.Parameters.Add(new SqlParameter("@ImporteAjuste", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@ImporteAjuste"].Value = thisLine.ImporteAjuste;

                            thisLine.ImporteSubtotal = GetFormatedFloat(thisLine.ImporteSubtotal);
                            dbQuery.Parameters.Add(new SqlParameter("@ImporteSubtotal", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@ImporteSubtotal"].Value = thisLine.ImporteSubtotal;

                            thisLine.ImportePrecioUnitarioMonedaFacturacion = GetFormatedFloat(thisLine.ImportePrecioUnitarioMonedaFacturacion);
                            dbQuery.Parameters.Add(new SqlParameter("@ImportePrecioUnitarioMonedaFacturacion", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@ImportePrecioUnitarioMonedaFacturacion"].Value = thisLine.ImportePrecioUnitarioMonedaFacturacion;

                            thisLine.ImporteBonificacionMonedaFacturacion = GetFormatedFloat(thisLine.ImporteBonificacionMonedaFacturacion);
                            dbQuery.Parameters.Add(new SqlParameter("@ImporteBonificacionMonedaFacturacion", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@ImporteBonificacionMonedaFacturacion"].Value = thisLine.ImporteBonificacionMonedaFacturacion;

                            thisLine.ImporteAjusteMonedaFacturacion = GetFormatedFloat(thisLine.ImporteAjusteMonedaFacturacion);
                            dbQuery.Parameters.Add(new SqlParameter("@ImporteAjusteMonedaFacturacion", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@ImporteAjusteMonedaFacturacion"].Value = thisLine.ImporteAjusteMonedaFacturacion;

                            thisLine.ImporteSubtotalMonedaFacturacion = GetFormatedFloat(thisLine.ImporteSubtotalMonedaFacturacion);
                            dbQuery.Parameters.Add(new SqlParameter("@ImporteSubtotalMonedaFacturacion", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@ImporteSubtotalMonedaFacturacion"].Value = thisLine.ImporteSubtotalMonedaFacturacion;

                            thisLine.ImporteSubtotalMonedaFacturacionConIVA = GetFormatedFloat(thisLine.ImporteSubtotalMonedaFacturacionConIVA);
                            dbQuery.Parameters.Add(new SqlParameter("@ImporteSubtotalMonedaFacturacionConIVA", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@ImporteSubtotalMonedaFacturacionConIVA"].Value = thisLine.ImporteSubtotalMonedaFacturacionConIVA;

                            thisLine.AlicuotaIVA = GetFormatedFloat(thisLine.AlicuotaIVA);
                            dbQuery.Parameters.Add(new SqlParameter("@AlicuotaIVA", System.Data.SqlDbType.Float));
                            dbQuery.Parameters["@AlicuotaIVA"].Value = thisLine.AlicuotaIVA;

                            dbQuery.Parameters.Add(new SqlParameter("@IndicadorExentoGravadoNoGravado", thisLine.IndicadorExentoGravadoNoGravado));
                            dbQuery.Parameters.Add(new SqlParameter("@Observaciones ", thisLine.Observaciones));
                            dbQuery.Parameters.Add(new SqlParameter("@MesPrestacion ", thisLine.MesPrestacion));

                            dbQuery.ExecuteNonQuery();

                            thisLine.SQLID = dbQuery.Parameters["@LineaID"].SqlValue.ToString();
                        }

                        if (thisHeader.RequestAlicuotas != null)
                        {
                            foreach (RequestAlicuota thisAlicuota in thisHeader.RequestAlicuotas)
                            {
                                cmd = "insert into CbteImpuesto (CbteID, Id, Tipo, BaseImp, ";
                                cmd += "Importe, ImporteMonedaFacturacion, Descripcion, Codigo ) ";

                                cmd += "values (@CbteID, @Id, @Tipo, @BaseImp, ";
                                cmd += "@Importe, @ImporteMonedaFacturacion, @Descripcion, @Codigo) ";

                                cmd += "SET @ImpuestoID = SCOPE_IDENTITY()";

                                dbQuery = new SqlCommand();
                                dbQuery.Connection = dbConnection;
                                dbQuery.CommandText = cmd;

                                dbQuery.Parameters.Add(new SqlParameter("@ImpuestoID", System.Data.SqlDbType.Int));
                                dbQuery.Parameters["@ImpuestoID"].Direction = System.Data.ParameterDirection.Output;

                                dbQuery.Parameters.Add(new SqlParameter("@CbteID", Convert.ToInt32(thisHeader.SQLID)));

                                thisAlicuota.Id = ObtenerEquivalenciaImpuesto("EquivAFIPImpuesto",
                                    thisHeader.EmpresaID, thisAlicuota.Codigo, ref thisAlicuota.Descripcion, false);

                                if (thisAlicuota.Id != string.Empty)
                                {
                                    dbQuery.Parameters.Add(new SqlParameter("@Id", Convert.ToInt32(thisAlicuota.Id)));

                                    dbQuery.Parameters.Add(new SqlParameter("@Tipo", thisAlicuota.Tipo));

                                    dbQuery.Parameters.Add(new SqlParameter("@Codigo", thisAlicuota.Codigo));

                                    thisAlicuota.BaseImp = GetFormatedFloat(thisAlicuota.BaseImp);
                                    dbQuery.Parameters.Add(new SqlParameter("@BaseImp", System.Data.SqlDbType.Float));
                                    dbQuery.Parameters["@BaseImp"].Value = thisAlicuota.BaseImp;

                                    thisAlicuota.Importe = GetFormatedFloat(thisAlicuota.Importe);
                                    dbQuery.Parameters.Add(new SqlParameter("@Importe", System.Data.SqlDbType.Float));
                                    dbQuery.Parameters["@Importe"].Value = thisAlicuota.Importe;

                                    thisAlicuota.ImporteMonedaFacturacion = GetFormatedFloat(thisAlicuota.ImporteMonedaFacturacion);
                                    dbQuery.Parameters.Add(new SqlParameter("@ImporteMonedaFacturacion", System.Data.SqlDbType.Float));
                                    dbQuery.Parameters["@ImporteMonedaFacturacion"].Value = thisAlicuota.ImporteMonedaFacturacion;

                                    dbQuery.Parameters.Add(new SqlParameter("@Descripcion", thisAlicuota.Descripcion));

                                    dbQuery.ExecuteNonQuery();

                                    thisAlicuota.ImpuestoID = dbQuery.Parameters["@ImpuestoID"].SqlValue.ToString();
                                }
                                else
                                {
                                    this.LogError("0", "0", "SQLEngine", "Error (Alicuota) de Equivalencia Alicuota(" + thisAlicuota.Codigo + ")");

                                    return false;
                                }
                            }
                        }

                        if (thisHeader.RequestTributos != null)
                        {
                            foreach (RequestTributo thisTributo in thisHeader.RequestTributos)
                            {
                                cmd = "insert into CbteImpuesto (CbteID, Id, Tipo, BaseImp, ";
                                cmd += "Importe, ImporteMonedaFacturacion, Descripcion, Codigo ) ";

                                cmd += "values (@CbteID, @Id, @Tipo, @BaseImp, ";
                                cmd += "@Importe, @ImporteMonedaFacturacion, @Descripcion, @Codigo ) ";

                                cmd += "SET @ImpuestoID = SCOPE_IDENTITY()";

                                dbQuery = new SqlCommand();
                                dbQuery.Connection = dbConnection;
                                dbQuery.CommandText = cmd;

                                dbQuery.Parameters.Add(new SqlParameter("@ImpuestoID", System.Data.SqlDbType.Int));
                                dbQuery.Parameters["@ImpuestoID"].Direction = System.Data.ParameterDirection.Output;

                                dbQuery.Parameters.Add(new SqlParameter("@CbteID", Convert.ToInt32(thisHeader.SQLID)));

                                TablaAfipImpuesto tafipimp = ObtenerEquivalenciaTributo(thisHeader.EmpresaID, thisTributo.Codigo, false);
                                thisTributo.Id = tafipimp.CodigoAFIP;
                                thisTributo.Descripcion = tafipimp.Descripcion;
                                //thisTributo.Id = ObtenerEquivalenciaImpuesto("EquivAFIPImpuesto", thisHeader.EmpresaID, thisTributo.Codigo, ref thisTributo.Descripcion, false);

                                if (thisTributo.Id != string.Empty)
                                {
                                    dbQuery.Parameters.Add(new SqlParameter("@Id", Convert.ToInt32(thisTributo.Id)));

                                    dbQuery.Parameters.Add(new SqlParameter("@Tipo", thisTributo.Tipo));

                                    dbQuery.Parameters.Add(new SqlParameter("@Codigo", thisTributo.Codigo));

                                    thisTributo.BaseImp = GetFormatedFloat(thisTributo.BaseImp);
                                    dbQuery.Parameters.Add(new SqlParameter("@BaseImp", System.Data.SqlDbType.Float));
                                    dbQuery.Parameters["@BaseImp"].Value = thisTributo.BaseImp;

                                    thisTributo.Importe = GetFormatedFloat(thisTributo.Importe);
                                    dbQuery.Parameters.Add(new SqlParameter("@Importe", System.Data.SqlDbType.Float));
                                    dbQuery.Parameters["@Importe"].Value = thisTributo.Importe;

                                    thisTributo.ImporteMonedaFacturacion = GetFormatedFloat(thisTributo.ImporteMonedaFacturacion);
                                    dbQuery.Parameters.Add(new SqlParameter("@ImporteMonedaFacturacion", System.Data.SqlDbType.Float));
                                    dbQuery.Parameters["@ImporteMonedaFacturacion"].Value = thisTributo.ImporteMonedaFacturacion;

                                    dbQuery.Parameters.Add(new SqlParameter("@Descripcion", thisTributo.Descripcion));

                                    thisTributo.Alic = GetFormatedFloat(tafipimp.Porcentaje);

                                    dbQuery.ExecuteNonQuery();

                                    thisTributo.ImpuestoID = dbQuery.Parameters["@ImpuestoID"].SqlValue.ToString();
                                }
                                else
                                {
                                    this.LogError("0", "0", "SQLEngine", "Error (Tributo) de Equivalencia Tributos(" + thisTributo.Codigo + ")");
                                    return false;
                                }
                            }
                        }
                        bResult = true;
                    }
                    Close();
                }
            }
            catch (Exception ex)
            {
                this.LogError("0", "0", "SQLEngine", "Error Data :" + ex.Message);
                bResult = false;
            }

            return bResult;
        }
Пример #5
0
        private RequestBatch ProcesarLoteComprobantes(FileInfo fi, Settings oSettings)
        {
            RequestBatch requestBatch = new RequestBatch();

            string filePath = fi.FullName;
            string line;

            bool bProcessOK = true;

            StreamReader fileInput = null;

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

            int qtyComprobantes = 0;

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

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

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

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

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

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

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

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

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

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

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

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

            return requestBatch;
        }
Пример #6
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;
        }
Пример #7
0
        public bool LoadXMLString(string xmlString)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xmlString);

            RequestBatch rqb = new RequestBatch();

            rqb.BatchUniqueId = ValidXMLValue(xmlDoc, "/RequestBatch/BatchUniqueId");
            rqb.SonServicios = ValidXMLValue(xmlDoc, "/RequestBatch/SonServicios");
            rqb.Periodo = ValidXMLValue(xmlDoc, "/RequestBatch/Periodo");
            rqb.CantidadComprobantes = ValidXMLValue(xmlDoc, "/RequestBatch/CantidadComprobantes");
            rqb.CUITInformante = ValidXMLValue(xmlDoc, "/RequestBatch/CUITInformante");
            rqb.Total = ValidXMLValue(xmlDoc, "/RequestBatch/Total");
            rqb.TotalComprobanteB = ValidXMLValue(xmlDoc, "/RequestBatch/TotalComprobanteB");
            rqb.TotalNoGravado = ValidXMLValue(xmlDoc, "/RequestBatch/TotalNoGravado");
            rqb.TotalGravado = ValidXMLValue(xmlDoc, "/RequestBatch/TotalGravado");
            rqb.TotalImpuestoLiquidado = ValidXMLValue(xmlDoc, "/RequestBatch/TotalImpuestoLiquidado");
            rqb.TotalRNI_Percepcion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalRNI_Percepcion");
            rqb.TotalExento = ValidXMLValue(xmlDoc, "/RequestBatch/TotalExento");
            rqb.TotalPercepciones_PagosCuentaImpuestosNacionales = ValidXMLValue(xmlDoc, "/RequestBatch/TotalPercepciones_PagosCuentaImpuestosNacionales");
            rqb.TotalPercepcionIIBB = ValidXMLValue(xmlDoc, "/RequestBatch/TotalPercepcionIIBB");
            rqb.TotalPercepcionImpuestosMunicipales = ValidXMLValue(xmlDoc, "/RequestBatch/TotalPercepcionImpuestosMunicipales");
            rqb.TotalImpuestosInternos = ValidXMLValue(xmlDoc, "/RequestBatch/TotalImpuestosInternos");
            rqb.TotalMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalMonedaFacturacion");
            rqb.TotalMonedaFacturacionComprobanteB = ValidXMLValue(xmlDoc, "/RequestBatch/TotalMonedaFacturacionComprobanteB");
            rqb.TotalNoGravadoMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalNoGravadoMonedaFacturacion");
            rqb.TotalGravadoMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalGravadoMonedaFacturacion");
            rqb.TotalImpuestoLiquidadoMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalImpuestoLiquidadoMonedaFacturacion");
            rqb.TotalRNI_PercepcionMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalRNI_PercepcionMonedaFacturacion");
            rqb.TotalExentoMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalExentoMonedaFacturacion");
            rqb.TotalPercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalPercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion");
            rqb.TotalPercepcionIIBBMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalPercepcionIIBBMonedaFacturacion");
            rqb.TotalPercepcionImpuestosMunicipalesMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalPercepcionImpuestosMunicipalesMonedaFacturacion");
            rqb.TotalImpuestosInternosMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/TotalImpuestosInternosMonedaFacturacion");

            //Agrego todos los comprobantes
            for (int i = 0; i < xmlDoc.SelectNodes("/RequestBatch/Comprobante").Count; i++)
            {
                RequestHeader thisHeader = new RequestHeader();
                thisHeader.AlicuotaIVA = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "AlicuotaIVA", i);
                thisHeader.CantidadAlicuotasIVA = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CantidadAlicuotasIVA", i);
                thisHeader.CantidadRegistrosDetalle = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CantidadRegistrosDetalle", i);
                thisHeader.CompradorCodigoCliente = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorCodigoCliente", i);
                thisHeader.CompradorCodigoDocumento = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorCodigoDocumento", i);
                thisHeader.CodigoJurisdiccionIIBB = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CodigoJurisdiccionIIBB", i);
                thisHeader.LetraComprobante = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "LetraComprobante", i);
                thisHeader.CodigoMecanismoDistribucion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CodigoMecanismoDistribucion", i);
                thisHeader.CodigoMoneda = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CodigoMoneda", i);
                thisHeader.CodigoOperacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CodigoOperacion", i);
                thisHeader.CompradorCodigoPostal = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorCodigoPostal", i);
                thisHeader.CondicionPago = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CondicionPago", i);
                thisHeader.CompradorDireccion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorDireccion", i);
                thisHeader.CompradorEmail = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorEmail", i);
                thisHeader.FechaComprobante = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "FechaComprobante", i);
                thisHeader.FechaDesdeServicioFacturado = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "FechaDesdeServicioFacturado", i);
                thisHeader.FechaHastaServicioFacturado = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "FechaHastaServicioFacturado", i);
                thisHeader.FechaVencimientoPago = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "FechaVencimientoPago", i);
                thisHeader.FormaPagoDescripcion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "FormaPagoDescripcion", i);
                thisHeader.Idioma = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "Idioma", i);
                thisHeader.Importe = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "Importe", i);
                thisHeader.ImporteComprobanteB = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteComprobanteB", i);
                thisHeader.ImporteEscrito = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteEscrito", i);
                thisHeader.ImporteExento = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteExento", i);
                thisHeader.ImporteExentoMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteExentoMonedaFacturacion", i);
                thisHeader.ImporteGravado = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteGravado", i);
                thisHeader.ImporteGravadoMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteGravadoMonedaFacturacion", i);
                thisHeader.ImporteImpuestoLiquidado = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteImpuestoLiquidado", i);
                thisHeader.ImporteImpuestoLiquidadoMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteImpuestoLiquidadoMonedaFacturacion", i);
                thisHeader.ImporteImpuestosInternos = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteImpuestosInternos", i);
                thisHeader.ImporteImpuestosInternosMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteImpuestosInternosMonedaFacturacion", i);
                thisHeader.ImporteMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteMonedaFacturacion", i);
                thisHeader.ImporteMonedaFacturacionComprobanteB = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteMonedaFacturacionComprobanteB", i);
                thisHeader.ImporteNoGravado = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteNoGravado", i);
                thisHeader.ImporteNoGravadoMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteNoGravadoMonedaFacturacion", i);
                thisHeader.ImportePercepciones_PagosCuentaImpuestosNacionales = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImportePercepciones_PagosCuentaImpuestosNacionales", i);
                thisHeader.ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion", i);
                thisHeader.ImportePercepcionImpuestosMunicipales = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImportePercepcionImpuestosMunicipales", i);
                thisHeader.ImportePercepcionImpuestosMunicipalesMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImportePercepcionImpuestosMunicipalesMonedaFacturacion", i);
                thisHeader.ImportePercepcionIIBB = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImportePercepcionIIBB", i);
                thisHeader.ImportePercepcionIIBBMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImportePercepcionIIBBMonedaFacturacion", i);
                thisHeader.ImporteRNI_Percepcion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteRNI_Percepcion", i);
                thisHeader.ImporteRNI_PercepcionMonedaFacturacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ImporteRNI_PercepcionMonedaFacturacion", i);
                thisHeader.IncoTerms = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "IncoTerms", i);
                thisHeader.JurisdiccionImpuestosMunicipales = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "JurisdiccionImpuestosMunicipales", i);
                thisHeader.CompradorLocalidad = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorLocalidad", i);
                thisHeader.NroComprobanteDesde = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "NroComprobanteDesde", i);
                thisHeader.NroComprobanteHasta = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "NroComprobanteHasta", i);
                thisHeader.CompradorNroDocumento = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorNroDocumento", i);
                thisHeader.CompradorNroIIBB = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorNroIIBB", i);
                thisHeader.CompradorNroReferencia = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorNroReferencia", i);
                thisHeader.NroRemito = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "NroRemito", i);
                thisHeader.Observaciones1 = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "Observaciones1", i);
                thisHeader.Observaciones2 = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "Observaciones2", i);
                thisHeader.Observaciones3 = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "Observaciones3", i);
                thisHeader.CompradorPais = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorPais", i);
                thisHeader.PermisoExistente = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "PermisoExistente", i);
                thisHeader.CompradorProvincia = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorProvincia", i);
                thisHeader.PuntoVenta = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "PuntoVenta", i);
                thisHeader.CompradorRazonSocial = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorRazonSocial", i);
                thisHeader.TasaCambio = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "TasaCambio", i);
                thisHeader.TasaIIBB = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "TasaIIBB", i);
                thisHeader.TipoComprobante = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "TipoComprobante", i);
                thisHeader.TipoExportacion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "TipoExportacion", i);
                thisHeader.CompradorTipoResponsable = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorTipoResponsable", i);
                thisHeader.CompradorTipoResponsableDescripcion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CompradorTipoResponsableDescripcion", i);
                thisHeader.TipoTransaccion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "TipoTransaccion", i);
                thisHeader.NroInternoERP = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "NroInternoERP", i);
                thisHeader.EmisorDireccion = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "EmisorDireccion", i);
                thisHeader.EmisorCalle = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "EmisorCalle", i);
                thisHeader.EmisorCP = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "EmisorCP", i);
                thisHeader.EmisorLocalidad = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "EmisorLocalidad", i);
                thisHeader.EmisorProvincia = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "EmisorProvincia", i);
                thisHeader.EmisorPais = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "EmisorPais", i);
                thisHeader.EmisorTelefonos = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "EmisorTelefonos", i);
                thisHeader.EmisorEMail = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "EmisorEMail", i);
                thisHeader.OficinaVentas = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "OficinaVentas", i);
                thisHeader.EmpresaID = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "EmpresaID", i);
                thisHeader.SQLID = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "SQLID", i);
                thisHeader.PagoFacil = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "PagoFacil", i);
                thisHeader.RapiPago = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "RapiPago", i);
                thisHeader.ObservacionRapiPago = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "ObservacionRapiPago", i);
                thisHeader.OPER = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "OPER", i);
                thisHeader.NOPER = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "NOPER", i);
                thisHeader.DAGRUF = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "DAGRUF", i);
                thisHeader.FACTORI = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "FACTORI", i);
                thisHeader.FACTORI_FORMATEADO = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "FACTORI_FORMATEADO", i);
                thisHeader.USUARIO = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "USUARIO", i);
                thisHeader.FECPG1_FORMATEADO = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "FECPG1_FORMATEADO", i);
                thisHeader.FECPG2_FORMATEADO = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "FECPG2_FORMATEADO", i);
                //thisHeader.CUOTAIVA105 = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CUOTAIVA105", i);
                //thisHeader.CUOTAIVA21 = ValidXMLValue(xmlDoc, "/RequestBatch/Comprobante", "CUOTAIVA21", i);

                rqb.RequestHeaders.Add(thisHeader);

                XmlDocument xmlLines = new XmlDocument();
                xmlLines.LoadXml(xmlDoc.SelectNodes("/RequestBatch/Comprobante")[i].OuterXml);

                //Agrego todas las líneas
                for (int j = 0; j < xmlLines.SelectNodes("/Comprobante/Linea").Count; j++)
                {
                    RequestLine thisLine = new RequestLine();

                    thisLine.AlicuotaIVA = ValidXMLValue(xmlLines, "/Comprobante/Linea", "AlicuotaIVA", j);
                    thisLine.Cantidad = ValidXMLValue(xmlLines, "/Comprobante/Linea", "Cantidad", j);
                    thisLine.CodigoProductoEmpresa = ValidXMLValue(xmlLines, "/Comprobante/Linea", "CodigoProductoEmpresa", j);
                    thisLine.CodigoProductoNCM = ValidXMLValue(xmlLines, "/Comprobante/Linea", "CodigoProductoNCM", j);
                    thisLine.CodigoProductoSecretaria = ValidXMLValue(xmlLines, "/Comprobante/Linea", "CodigoProductoSecretaria", j);
                    thisLine.Descripcion = ValidXMLValue(xmlLines, "/Comprobante/Linea", "Descripcion", j);
                    thisLine.ImporteAjuste = ValidXMLValue(xmlLines, "/Comprobante/Linea", "ImporteAjuste", j);
                    thisLine.ImporteAjusteMonedaFacturacion = ValidXMLValue(xmlLines, "/Comprobante/Linea", "ImporteAjusteMonedaFacturacion", j);
                    thisLine.ImporteBonificacion = ValidXMLValue(xmlLines, "/Comprobante/Linea", "ImporteBonificacion", j);
                    thisLine.ImporteBonificacionMonedaFacturacion = ValidXMLValue(xmlLines, "/Comprobante/Linea", "ImporteBonificacionMonedaFacturacion", j);
                    thisLine.ImportePrecioUnitario = ValidXMLValue(xmlLines, "/Comprobante/Linea", "ImportePrecioUnitario", j);
                    thisLine.ImportePrecioUnitarioMonedaFacturacion = ValidXMLValue(xmlLines, "/Comprobante/Linea", "ImportePrecioUnitarioMonedaFacturacion", j);
                    thisLine.ImporteSubtotal = ValidXMLValue(xmlLines, "/Comprobante/Linea", "ImporteSubtotal", j);
                    thisLine.ImporteSubtotalMonedaFacturacion = ValidXMLValue(xmlLines, "/Comprobante/Linea", "ImporteSubtotalMonedaFacturacion", j);
                    thisLine.ImporteSubtotalMonedaFacturacionConIVA = ValidXMLValue(xmlLines, "/Comprobante/Linea", "ImporteSubtotalMonedaFacturacionConIVA", j);
                    thisLine.IndicadorExentoGravadoNoGravado = ValidXMLValue(xmlLines, "/Comprobante/Linea", "IndicadorExentoGravadoNoGravado", j);
                    thisLine.Observaciones = ValidXMLValue(xmlLines, "/Comprobante/Linea", "Observaciones", j);
                    thisLine.MesPrestacion = ""; //ValidXMLValue(xmlLines, "/Comprobante/Linea", "MesPrestacion", j);
                    thisLine.UnidadMedida = ValidXMLValue(xmlLines, "/Comprobante/Linea", "UnidadMedida", j);
                    thisLine.SQLID = ValidXMLValue(xmlLines, "/Comprobante/Linea", "SQLID", j);

                    thisHeader.RequestLines.Add(thisLine);
                }

                //Agrego todas las alicuotas
                for (int j = 0; j < xmlLines.SelectNodes("/Comprobante/Alicuota").Count; j++)
                {
                    RequestAlicuota thisTAlicuota = new RequestAlicuota();

                    thisTAlicuota.Id = ValidXMLValue(xmlLines, "/Comprobante/Alicuota", "Id", j);
                    thisTAlicuota.Descripcion = ValidXMLValue(xmlLines, "/Comprobante/Alicuota", "Descripcion", j);
                    thisTAlicuota.Importe = ValidXMLValue(xmlLines, "/Comprobante/Alicuota", "Importe", j);
                    thisTAlicuota.BaseImp = ValidXMLValue(xmlLines, "/Comprobante/Alicuota", "BaseImp", j);
                    thisTAlicuota.Tipo = ValidXMLValue(xmlLines, "/Comprobante/Alicuota", "Tipo", j);
                    thisTAlicuota.Codigo = ValidXMLValue(xmlLines, "/Comprobante/Alicuota", "Codigo", j);
                    thisTAlicuota.CbteID = thisHeader.SQLID;

                    thisHeader.RequestAlicuotas.Add(thisTAlicuota);
                }

                //Agrego todos los tributos
                for (int j = 0; j < xmlLines.SelectNodes("/Comprobante/Tributo").Count; j++)
                {
                    RequestTributo thisTributo = new RequestTributo();

                    thisTributo.Id = ValidXMLValue(xmlLines, "/Comprobante/Tributo", "Id", j);
                    thisTributo.Descripcion = ValidXMLValue(xmlLines, "/Comprobante/Tributo", "Descripcion", j);
                    thisTributo.Importe = ValidXMLValue(xmlLines, "/Comprobante/Tributo", "Importe", j);
                    thisTributo.BaseImp = ValidXMLValue(xmlLines, "/Comprobante/Tributo", "BaseImp", j);
                    thisTributo.Tipo = ValidXMLValue(xmlLines, "/Comprobante/Tributo", "Tipo", j);
                    thisTributo.Codigo = ValidXMLValue(xmlLines, "/Comprobante/Tributo", "Codigo", j);
                    thisTributo.Alic = ValidXMLValue(xmlLines, "/Comprobante/Tributo", "Alic", j);
                    thisTributo.CbteID = thisHeader.SQLID;

                    thisHeader.RequestTributos.Add(thisTributo);
                }
            }

            return true;
        }
Пример #8
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();
        }
Пример #9
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;
        }
Пример #10
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();
        }
Пример #11
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();
        }
Пример #12
0
        private bool BuscarEquivalencias(ref RequestBatch loteDocs, Settings oSettings, ref string strEquivalenciaErrorFields)
        {
            string resultado = string.Empty;
            string strSQLID = string.Empty;

            bool bEquivalenciaError = false;

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

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

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

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

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

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

                    //SOLO PARA TRANSACCIONES 3 (EXPORTACION)
                    if (thisHeader.TipoTransaccion == "3")
                    {
                        resultado = sqlEngine.ObtenerEquivalencia("EquivAFIPIncoterms", oSettings.EmpresaID, thisHeader.IncoTerms);
                        if (resultado == "")
                        {
                            bEquivalenciaError = true;
                            strEquivalenciaErrorFields += "Incoterms(" + thisHeader.IncoTerms + "); ";
                            sqlEngine.LogError(thisHeader.SQLID, "0", "Equivalencias", "No se encontró la equivalencia con AFIP del incoterms (" + thisHeader.IncoTerms + ")");
                        }
                        else
                        {
                            thisHeader.IncoTerms = resultado;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                sqlEngine.LogError(strSQLID, "0", "Equivalencias", "Error no identificado: " + ex.Message);
                bEquivalenciaError = true;
            }
            return bEquivalenciaError;
        }
Пример #13
0
        public RequestBatch ProcessData(DataRow drCabecera, DataTable dtLineas, DataTable dtImpuestos, Settings oSettings)
        {
            RequestBatch requestBatch = new RequestBatch();
            RequestLine thisLine = new RequestLine();
            RequestAlicuota requestAlicuota = new RequestAlicuota();
            RequestTributo requestTributo = new RequestTributo();

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

            int qtyComprobantes = 0;

            try
            {
                if(drCabecera != null)
                {
                    //DEBUG LINE
                    if (Convert.ToBoolean(oSettings.ActivarDebug))
                        drCabecera.Table.WriteXml(oSettings.PathDebug + "\\" + GetDataRowString(drCabecera["NROCOMPROBANTE"]) + "-Cabecera-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                    //DEBUG LINE
                    if (Convert.ToBoolean(oSettings.ActivarDebug))
                        dtLineas.WriteXml(oSettings.PathDebug + "\\" + GetDataRowString(drCabecera["NROCOMPROBANTE"]) + "-Lineas-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                    RequestHeader thisDocument = new RequestHeader();

                    thisDocument.SQLID = string.Empty;
                    thisDocument.EmpresaID = oSettings.EmpresaID;
                    thisDocument.TipoTransaccion = GetDataRowString(drCabecera["TIPOTRANSACCION"]);
                    thisDocument.FechaComprobante = GetDataRowString(drCabecera["FECHACOMPROBANTE"]);
                    thisDocument.FechaDesdeServicioFacturado = GetDataRowString(drCabecera["FECHACOMPROBANTE"]);
                    thisDocument.FechaHastaServicioFacturado = GetDataRowString(drCabecera["FECHACOMPROBANTE"]);
                    thisDocument.TipoComprobante = GetDataRowString(drCabecera["TIPOCOMPROBANTE"]);
                    thisDocument.PuntoVenta = GetDataRowString(drCabecera["PUNTOVENTA"]);
                    thisDocument.LetraComprobante = GetDataRowString(drCabecera["LETRACOMPROBANTE"]);
                    thisDocument.NroComprobanteDesde = GetDataRowString(drCabecera["NROCOMPROBANTE"]);
                    thisDocument.NroComprobanteHasta = GetDataRowString(drCabecera["NROCOMPROBANTE"]);
                    thisDocument.NroInternoERP = GetDataRowString(drCabecera["IDREGISTROCABECERA"]);
                    thisDocument.FechaVencimientoPago = GetDataRowString(drCabecera["FECHAVENCIMIENTOPAGO"]);
                    thisDocument.CondicionPago = GetDataRowString(drCabecera["CONDICIONPAGO"]);
                    thisDocument.CompradorCodigoDocumento = GetDataRowString(drCabecera["CODIGODOCUMENTOCOMPRADOR"]);
                    thisDocument.CompradorNroDocumento = GetDataRowString(drCabecera["NRODOCUMENTOCOMPRADOR"]);
                    thisDocument.CompradorTipoResponsable = GetDataRowString(drCabecera["TIPORESPONSABLECOMPRADOR"]);
                    thisDocument.CompradorTipoResponsableDescripcion = GetDataRowString(drCabecera["TIPORESPONSABLECOMPRADORDESCRIPCION"]);
                    thisDocument.CompradorRazonSocial = GetDataRowString(drCabecera["RAZONSOCIALCOMPRADOR"]);
                    thisDocument.CompradorDireccion = GetDataRowString(drCabecera["DIRECCIONCOMPRADOR"]);
                    thisDocument.CompradorLocalidad = GetDataRowString(drCabecera["LOCALIDADCOMPRADOR"]);
                    thisDocument.CompradorProvincia = GetDataRowString(drCabecera["PROVINCIACOMPRADOR"]);
                    thisDocument.CompradorPais = GetDataRowString(drCabecera["PAISCOMPRADOR"]);
                    thisDocument.CompradorCodigoPostal = GetDataRowString(drCabecera["CODIGOPOSTALCOMPRADOR"]);
                    thisDocument.CompradorNroIIBB = GetDataRowString(drCabecera["NROIIBBCOMPRADOR"]);
                    thisDocument.CompradorCodigoCliente = GetDataRowString(drCabecera["CODIGOCLIENTECOMPRADOR"]);
                    thisDocument.CompradorNroReferencia = string.Empty;
                    thisDocument.CompradorEmail = string.Empty;
                    thisDocument.NroRemito = string.Empty;
                    thisDocument.Importe = GetDataRowString(drCabecera["IMPORTE"]);
                    thisDocument.ImporteComprobanteB = "0";
                    thisDocument.ImporteNoGravado = GetDataRowString(drCabecera["IMPORTENOGRAVADO"]);
                    thisDocument.ImporteGravado = GetDataRowString(drCabecera["IMPORTEGRAVADO"]);
                    thisDocument.AlicuotaIVA = "0";
                    thisDocument.ImporteImpuestoLiquidado = GetDataRowString(drCabecera["IMPORTEIMPUESTOLIQUIDADO"]);
                    thisDocument.ImporteRNI_Percepcion = GetDataRowString(drCabecera["IMPORTERNI_PERCEPCION"]);
                    thisDocument.ImporteExento = GetDataRowString(drCabecera["IMPORTEEXENTO"]);
                    thisDocument.ImportePercepciones_PagosCuentaImpuestosNacionales = GetDataRowString(drCabecera["IMPORTEPERCEPCIONES_PAGOSCUENTAIMPUESTOSNACIONALES"]);
                    thisDocument.ImportePercepcionIIBB = GetDataRowString(drCabecera["IMPORTEPERCEPCIONIIBB"]);
                    thisDocument.TasaIIBB = GetDataRowString(drCabecera["TASAIIBB"]);
                    thisDocument.CodigoJurisdiccionIIBB = GetDataRowString(drCabecera["CODIGOJURISDICCIONIIBB"]);
                    thisDocument.ImportePercepcionImpuestosMunicipales = GetDataRowString(drCabecera["IMPORTEPERCEPCIONIMPUESTOSMUNICIPALES"]);
                    thisDocument.JurisdiccionImpuestosMunicipales = GetDataRowString(drCabecera["JURISDICCIONIMPUESTOSMUNICIPALES"]);
                    thisDocument.ImporteImpuestosInternos = GetDataRowString(drCabecera["IMPORTEIMPUESTOSINTERNOS"]);
                    thisDocument.ImporteMonedaFacturacion = GetDataRowString(drCabecera["IMPORTEMONEDAFACTURACION"]);
                    thisDocument.ImporteMonedaFacturacionComprobanteB = "0";
                    thisDocument.ImporteNoGravadoMonedaFacturacion = GetDataRowString(drCabecera["IMPORTENOGRAVADOMONEDAFACTURACION"]);
                    thisDocument.ImporteGravadoMonedaFacturacion = GetDataRowString(drCabecera["IMPORTEGRAVADOMONEDAFACTURACION"]);
                    thisDocument.ImporteImpuestoLiquidadoMonedaFacturacion = GetDataRowString(drCabecera["IMPORTEIMPUESTOLIQUIDADOMONEDAFACTURACION"]);
                    thisDocument.ImporteRNI_PercepcionMonedaFacturacion = GetDataRowString(drCabecera["IMPORTERNI_PERCEPCIONMONEDAFACTURACION"]);
                    thisDocument.ImporteExentoMonedaFacturacion = GetDataRowString(drCabecera["IMPORTEEXENTOMONEDAFACTURACION"]);
                    thisDocument.ImportePercepciones_PagosCuentaImpuestosNacionalesMonedaFacturacion = GetDataRowString(drCabecera["IMPORTEPERCEPCIONES_PAGOSCUENTAIMPUESTOSNACIONALESMONEDAFACTURACION"]);
                    thisDocument.ImportePercepcionIIBBMonedaFacturacion = GetDataRowString(drCabecera["IMPORTEPERCEPCIONIIBBMONEDAFACTURACION"]);
                    thisDocument.ImportePercepcionImpuestosMunicipalesMonedaFacturacion = GetDataRowString(drCabecera["IMPORTEPERCEPCIONIMPUESTOSMUNICIPALESMONEDAFACTURACION"]);
                    thisDocument.ImporteImpuestosInternosMonedaFacturacion = GetDataRowString(drCabecera["IMPORTEIMPUESTOSINTERNOSMONEDAFACTURACION"]);
                    thisDocument.CantidadAlicuotasIVA = GetDataRowString(drCabecera["CANTIDADALICUOTASIVA"]);
                    thisDocument.CodigoOperacion = GetDataRowString(drCabecera["CODIGOOPERACION"]);
                    thisDocument.TasaCambio = GetDataRowString(drCabecera["TASACAMBIO"]);
                    thisDocument.CodigoMoneda = GetDataRowString(drCabecera["CODIGOMONEDA"]);
                    thisDocument.ImporteEscrito = GetDataRowString(drCabecera["IMPORTEESCRITO"]);
                    thisDocument.CantidadRegistrosDetalle = dtLineas.Rows.Count.ToString();
                    thisDocument.CodigoMecanismoDistribucion = string.Empty;
                    thisDocument.TipoExportacion = string.Empty;
                    thisDocument.PermisoExistente = string.Empty;
                    thisDocument.FormaPagoDescripcion = string.Empty;
                    thisDocument.IncoTerms = GetDataRowString(drCabecera["INCOTERMS"]);
                    thisDocument.Idioma = string.Empty;
                    thisDocument.Observaciones1 = GetDataRowString(drCabecera["OBSERVACIONCABECERA"]);
                    thisDocument.Observaciones2 = GetDataRowString(drCabecera["INFOADIC"]);
                    thisDocument.Observaciones3 = GetDataRowString(drCabecera["OBSERVACIONPIE"]);
                    thisDocument.EmisorDireccion = string.Empty;
                    thisDocument.EmisorCalle = GetDataRowString(drCabecera["EMISORCALLE"]);
                    thisDocument.EmisorCP = GetDataRowString(drCabecera["EMISORCP"]);
                    thisDocument.EmisorLocalidad = GetDataRowString(drCabecera["EMISORLOCALIDAD"]);
                    thisDocument.EmisorProvincia = GetDataRowString(drCabecera["EMISORPROVINCIA"]);
                    thisDocument.EmisorPais = GetDataRowString(drCabecera["EMISORPAIS"]);
                    thisDocument.EmisorTelefonos = GetDataRowString(drCabecera["EMISORTELEFONOS"]);
                    thisDocument.EmisorEMail = GetDataRowString(drCabecera["EMISOREMAIL"]);
                    thisDocument.OficinaVentas = string.Empty;
                    //thisDocument.PagoFacil = GetDataRowString(drCabecera["PagoFacil"]);
                    thisDocument.RapiPago = GetDataRowString(drCabecera["RapiPago"]);
                    thisDocument.ObservacionRapiPago = GetDataRowString(drCabecera["ObservacionRapiPago"]);
                    thisDocument.OPER = GetDataRowString(drCabecera["OPER"]);
                    thisDocument.NOPER = GetDataRowString(drCabecera["NOPER"]);
                    thisDocument.FACTORI = GetDataRowString(drCabecera["FACTORI"]);
                    thisDocument.FACTORI_FORMATEADO = GetDataRowString(drCabecera["FACTORI_FORMATEADO"]);
                    thisDocument.DAGRUF = GetDataRowString(drCabecera["DAGRUF"]);
                    thisDocument.USUARIO = GetDataRowString(drCabecera["USUARIO"]);

                    thisDocument.FECPG1_FORMATEADO = GetDataRowString(drCabecera["FECPG1_FORMATEADO"]);
                    thisDocument.FECPG2_FORMATEADO = GetDataRowString(drCabecera["FECPG2_FORMATEADO"]);

                    thisDocument.CUOTAIVA105 = GetDataRowString(drCabecera["CUOTAIVA105"]);
                    thisDocument.CUOTAIVA21 = GetDataRowString(drCabecera["CUOTAIVA21"]);

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

                    //proceso las lineas
                    foreach (DataRow drLine in dtLineas.Rows)
                    {
                        thisLine = new RequestLine();

                        thisLine.CodigoProductoEmpresa = GetDataRowString(drLine["CODIGOPRODUCTOEMPRESA"]);
                        thisLine.CodigoProductoNCM = string.Empty;
                        thisLine.CodigoProductoSecretaria = string.Empty;
                        thisLine.Descripcion = GetDataRowString(drLine["DESCRIPCION"]);
                        thisLine.Cantidad = GetDataRowString(drLine["CANTIDAD"]);
                        thisLine.UnidadMedida = GetDataRowString(drLine["UNIDADMEDIDA"]);
                        thisLine.ImportePrecioUnitario = GetDataRowString(drLine["IMPORTEPRECIOUNITARIO"]);
                        thisLine.ImporteBonificacion = GetDataRowString(drLine["IMPORTEBONIFICACION"]);
                        thisLine.ImporteAjuste = "0";
                        thisLine.ImporteSubtotal = GetDataRowString(drLine["IMPORTESUBTOTAL"]);
                        thisLine.ImportePrecioUnitarioMonedaFacturacion = GetDataRowString(drLine["IMPORTEPRECIOUNITARIOMONEDAFACTURACION"]);
                        thisLine.ImporteBonificacionMonedaFacturacion = GetDataRowString(drLine["IMPORTEBONIFICACIONMONEDAFACTURACION"]);
                        thisLine.ImporteAjusteMonedaFacturacion = GetDataRowString(drLine["IMPORTEAJUSTEMONEDAFACTURACION"]);
                        thisLine.ImporteSubtotalMonedaFacturacion = GetDataRowString(drLine["IMPORTESUBTOTALMONEDAFACTURACION"]);
                        thisLine.ImporteSubtotalMonedaFacturacionConIVA = GetDataRowString(drLine["IMPORTESUBTOTALMONEDAFACTURACIONCONIVA"]);
                        thisLine.AlicuotaIVA = GetDataRowString(drLine["ALICUOTAIVA"]);
                        thisLine.IndicadorExentoGravadoNoGravado = GetDataRowString(drLine["INDICADOREXENTOGRAVADONOGRAVADO"]);
                        thisLine.Observaciones = GetDataRowString(drLine["OBSERVACIONES"]); ;
                        thisLine.MesPrestacion = GetDataRowString(drLine["MESPRESTACION"]); ;

                        thisDocument.RequestLines.Add(thisLine);
                    }

                    //proceso los impuestos (Alicuotas y Tributos)
                    foreach (DataRow drImpuesto in dtImpuestos.Rows)
                    {
                        switch(GetDataRowString(drImpuesto["TIPO"]))
                        {
                            case "Alicuota":
                                requestAlicuota = new RequestAlicuota();

                                requestAlicuota.Id = GetDataRowString(drImpuesto["ID"]);
                                requestAlicuota.CbteID = GetDataRowString(drImpuesto["CBTEID"]);
                                requestAlicuota.Importe = GetDataRowString(drImpuesto["IMPORTE"]);
                                requestAlicuota.BaseImp = GetDataRowString(drImpuesto["BASEIMP"]);
                                requestAlicuota.Tipo = GetDataRowString(drImpuesto["TIPO"]);
                                requestAlicuota.Descripcion = GetDataRowString(drImpuesto["DESCRIPCION"]);

                                thisDocument.RequestAlicuotas.Add(requestAlicuota);
                                break;

                            case "Tributo":
                                requestTributo = new RequestTributo();

                                requestTributo.Id = GetDataRowString(drImpuesto["ID"]);
                                requestTributo.CbteID = GetDataRowString(drImpuesto["CBTEID"]);
                                requestTributo.Importe = GetDataRowString(drImpuesto["IMPORTE"]);
                                requestTributo.BaseImp = GetDataRowString(drImpuesto["BASEIMP"]);
                                requestTributo.Tipo = GetDataRowString(drImpuesto["TIPO"]);
                                requestTributo.Descripcion = GetDataRowString(drImpuesto["DESCRIPCION"]);
                                requestTributo.Alic = GetDataRowString(drImpuesto["ALIC"]);

                                thisDocument.RequestTributos.Add(requestTributo);
                                break;
                        }
                    }

                    requestBatch.RequestHeaders.Add(thisDocument);

                    qtyComprobantes++;

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

                    //TODO: Lote automático donde configurarlo?
                    requestBatch.BatchUniqueId = "AUTO";
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Servicio Factura Electronica", "ProcessData.Error:" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
            }
            return requestBatch;
        }
Пример #14
0
        public wsfe.FECAEResponse FEAuthRequest(RequestBatch docBatch, Settings oSettings)
        {
            wsfe.FECAECabRequest objFECabeceraRequest = new wsfe.FECAECabRequest();
            wsfe.FECAEDetRequest objFEDetalleRequest = new wsfe.FECAEDetRequest();
            wsfe.FECAERequest objFERequest = new wsfe.FECAERequest();
            wsfe.FECAEResponse objFEResponse = new wsfe.FECAEResponse();
            wsfe.AlicIva objIva = null;
            wsfe.Tributo objTributo = null;

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

            int i = 0;
            int iIvaItems = 0;
            int iTributosItems = 0;

            try
            {
                objFECabeceraRequest.CantReg = Convert.ToInt16(docBatch.CantidadComprobantes);
                objFECabeceraRequest.PtoVta = Convert.ToInt16(docBatch.RequestHeaders[0].PuntoVenta);
                objFECabeceraRequest.CbteTipo = Convert.ToInt16(docBatch.RequestHeaders[0].TipoComprobante);

                wsfe.FECAEDetRequest[] aObjFEDetalleRequest = new wsfe.FECAEDetRequest[Convert.ToInt16(objFECabeceraRequest.CantReg)];

                int arrayIndex = 0;
                for (i = 0; i < objFECabeceraRequest.CantReg; i++)
                {
                    objFEDetalleRequest = new wsfe.FECAEDetRequest();

                    //Si el numero de documento viene vacio asumo que es un consumidor final 99
                    if (docBatch.RequestHeaders[i].CompradorNroDocumento == string.Empty)
                    {
                        docBatch.RequestHeaders[i].CompradorCodigoDocumento = "99";
                        docBatch.RequestHeaders[i].CompradorNroDocumento = "0";
                    }

                    objFEDetalleRequest.DocTipo = Convert.ToInt16(docBatch.RequestHeaders[i].CompradorCodigoDocumento);
                    objFEDetalleRequest.DocNro = (long)Convert.ToDouble(docBatch.RequestHeaders[i].CompradorNroDocumento);

                    objFEDetalleRequest.CbteDesde = (long)Convert.ToDouble(docBatch.RequestHeaders[i].NroComprobanteDesde);
                    objFEDetalleRequest.CbteHasta = (long)Convert.ToDouble(docBatch.RequestHeaders[i].NroComprobanteHasta);
                    objFEDetalleRequest.ImpTotal = Convert.ToDouble(docBatch.RequestHeaders[i].Importe);
                    objFEDetalleRequest.ImpTotConc = Convert.ToDouble(docBatch.RequestHeaders[i].ImporteNoGravado);
                    objFEDetalleRequest.ImpNeto = Convert.ToDouble(docBatch.RequestHeaders[i].ImporteGravado);
                    //objFEDetalleRequest.impto_liq_rni = Convert.ToDouble(docBatch.RequestHeaders[i].ImporteRNI_Percepcion);????
                    //objFEDetalleRequest.ImpIVA = Convert.ToDouble(docBatch.RequestHeaders[i].ImporteImpuestoLiquidado);

                    objFEDetalleRequest.ImpOpEx = Convert.ToDouble(docBatch.RequestHeaders[i].ImporteExento);

                    //Agrego todas las alicuotas en array
                    //1 No gravado
                    //2 Exento
                    //3 0%
                    //4 10.5%
                    //5 21%
                    //6 27%
                    if (docBatch.RequestHeaders[i].RequestAlicuotas.Count > 0)
                    {
                        objFEDetalleRequest.Iva = new wsfe.AlicIva[docBatch.RequestHeaders[i].RequestAlicuotas.Count];
                        iIvaItems = 0;
                        foreach (RequestAlicuota alic in docBatch.RequestHeaders[i].RequestAlicuotas)
                        {
                            if (alic != null)
                            {
                                objIva = new wsfe.AlicIva();
                                objIva.Id = Convert.ToInt32(alic.Id);
                                objIva.BaseImp = Convert.ToDouble(String.Format("{0:0.00}", alic.BaseImp));
                                objIva.Importe = Convert.ToDouble(String.Format("{0:0.00}", alic.Importe));

                                objFEDetalleRequest.Iva[iIvaItems] = objIva;

                                iIvaItems++;

                                //Agrego importe al total de alicuotas de IVA
                                objFEDetalleRequest.ImpIVA += objIva.Importe;
                            }
                        }
                    }
                    objFEDetalleRequest.ImpIVA = Convert.ToDouble(String.Format("{0:0.00}", objFEDetalleRequest.ImpIVA));

                    //Agrego todos los tributos en array
                    //1	Impuestos nacionales
                    //2	Impuestos provinciales
                    //3	Impuestos municipales
                    //4	Impuestos internos
                    //99 Otros
                    if (docBatch.RequestHeaders[i].RequestTributos.Count > 0)
                    {
                        objFEDetalleRequest.Tributos = new wsfe.Tributo[docBatch.RequestHeaders[i].RequestTributos.Count];
                        iTributosItems = 0;
                        foreach (RequestTributo trib in docBatch.RequestHeaders[i].RequestTributos)
                        {
                            if (trib != null)
                            {
                                objTributo = new wsfe.Tributo();
                                objTributo.Id = Convert.ToInt16(trib.Id);
                                objTributo.BaseImp = Convert.ToDouble(String.Format("{0:0.00}", trib.BaseImp));
                                objTributo.Importe = Convert.ToDouble(String.Format("{0:0.00}", trib.Importe));
                                objTributo.Alic = Convert.ToDouble(String.Format("{0:#,##0.00}", trib.Alic));

                                objFEDetalleRequest.Tributos[iTributosItems] = objTributo;

                                iTributosItems++;

                                //Agrego importe al total de tributos
                                objFEDetalleRequest.ImpTrib += objTributo.Importe;
                            }
                        }
                    }

                    // Las fechas deben venir en formato "YYYY-MM-DD"
                    objFEDetalleRequest.CbteFch = Convert.ToDateTime(docBatch.RequestHeaders[i].FechaComprobante).ToString("yyyyMMdd");

                    //Es 1 si son productos 2 servicios, 3 productos y servicios
                    if (docBatch.SonServicios == "1")
                        objFEDetalleRequest.Concepto = 3;
                    else
                        objFEDetalleRequest.Concepto = 1;

                    if (objFEDetalleRequest.Concepto == 3)
                    {
                        objFEDetalleRequest.FchServDesde = Convert.ToDateTime(docBatch.RequestHeaders[i].FechaDesdeServicioFacturado).ToString("yyyyMMdd");
                        objFEDetalleRequest.FchServHasta = Convert.ToDateTime(docBatch.RequestHeaders[i].FechaHastaServicioFacturado).ToString("yyyyMMdd");
                        objFEDetalleRequest.FchVtoPago = Convert.ToDateTime(docBatch.RequestHeaders[i].FechaVencimientoPago).ToString("yyyyMMdd");
                    }

                    objFEDetalleRequest.MonId = docBatch.RequestHeaders[i].CodigoMoneda;
                    objFEDetalleRequest.MonCotiz = 1;

                    aObjFEDetalleRequest[arrayIndex] = objFEDetalleRequest;
                    arrayIndex += 1;
                }

                objFERequest.FeCabReq = objFECabeceraRequest;
                objFERequest.FeDetReq = aObjFEDetalleRequest;

                //DEBUG LINE
                if (Convert.ToBoolean(oSettings.ActivarDebug))
                    Utils.Utils.DebugLine(Utils.Utils.SerializeObject(objFERequest), oSettings.PathDebug + "\\" + docBatch.RequestHeaders[0].SQLID + "-P2.FERequest-" + DateTime.Now.Hour.ToString("00") + DateTime.Now.Minute.ToString("00") + DateTime.Now.Second.ToString("00") + DateTime.Now.Millisecond.ToString("000") + ".xml");

                objFEResponse = feService.FECAESolicitar(objFEAuthRequest, objFERequest);
            }
            catch (Exception ex)
            {
                int iElement = 0;
                if(i > 0)
                    iElement = i - 1;
                else
                    iElement = 0;

                objFEResponse.Errors = new wsfe.Err[1];
                objFEResponse.Errors[0] = new wsfe.Err();
                objFEResponse.Errors[0].Code = 668;
                objFEResponse.Errors[0].Msg = ex.Message;

                string url = oSettings.UrlFEWebService;
                sqlEngine.LogError(docBatch.RequestHeaders[iElement].SQLID, "0", "Autorización", "Error no conocido: (AfipFE) " + ex.Message);
            }

            return objFEResponse;
        }