private void InserirClientes(SAPbobsCOM.Company company, OrderIntegraCommerce pedido)
        {
            try
            {
                BusinessPartnersDAL bpDAL = new BusinessPartnersDAL();

                string errorMessage;

                bpDAL.InserirBusinessPartner(company, pedido, out errorMessage);
            }
            catch (Exception e)
            {
                this.log.WriteLogPedido("Exception inserirClientes " + e.Message);
                throw;
            }
        }
        public void IniciarIntegracaoPedido(SAPbobsCOM.Company oCompany)
        {
            try
            {
                Repositorio          repositorioPedido     = new Repositorio();
                List <OrderQueues>   listaOrders           = new List <OrderQueues>();
                OrderIntegraCommerce _orderIntegraCommerce = new OrderIntegraCommerce();
                String document = String.Empty;

                Task <HttpResponseMessage> responsePedido = repositorioPedido.ConsultarFilaDeEventos();

                if (responsePedido.Result.IsSuccessStatusCode)
                {
                    var jsonResponseOrderQueue = responsePedido.Result.Content.ReadAsStringAsync().Result;

                    var _orderQueue = JsonConvert.DeserializeObject <OrderQueue>(jsonResponseOrderQueue);

                    listaOrders = _orderQueue.OrderQueues;

                    if (listaOrders.Count > 0)
                    {
                        string pedidosARemover   = string.Empty;
                        string pedidosARemoverML = string.Empty;
                        //Validando evento do pedido
                        foreach (OrderQueues order in listaOrders)
                        {
                            //Se o evento do pedido for Pronto para Manuseio (ready-for-handling)
                            if (order.OrderStatus.Equals("APPROVED"))
                            {
                                Task <HttpResponseMessage> responseOrder = repositorioPedido.BuscarPedido(order.IdOrder);

                                if (responseOrder.Result.IsSuccessStatusCode)
                                {
                                    var jsonPedido = responseOrder.Result.Content.ReadAsStringAsync().Result;

                                    _orderIntegraCommerce = JsonConvert.DeserializeObject <OrderIntegraCommerce>(jsonPedido);

                                    if (!_orderIntegraCommerce.OrderStatus.Equals("PROCESSING"))
                                    {
                                        if (!String.IsNullOrEmpty(_orderIntegraCommerce.CustomerPfCpf))
                                        {
                                            document = _orderIntegraCommerce.CustomerPfCpf;
                                        }
                                        else
                                        {
                                            document = _orderIntegraCommerce.CustomerPjCnpj;
                                        }

                                        if (document != null)
                                        {
                                            this.InserirClientes(oCompany, _orderIntegraCommerce);
                                        }
                                        else
                                        {
                                            this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, "", EnumStatusIntegracao.Erro, "Cliente não cadastrado pois o número do Documento é inválido.");
                                        }

                                        //Inserir Pedido de venda
                                        //this.InserirPedidoVenda(oCompany, _orderIntegraCommerce, order);
                                        this.InserirPedidoVenda(oCompany, _orderIntegraCommerce, order.Id);

                                        /*if (_orderIntegraCommerce.origin.Equals("Fulfillment"))
                                         * {
                                         *  Cliente clienteMkt = new Cliente();
                                         *  Endereco enderecoMkt = new Endereco();
                                         *
                                         *  this.InserirClientes(oCompany, clienteMkt, enderecoMkt, _orderIntegraCommerce);
                                         * }*/
                                        DateTime diaAnterior = DateTime.Now.AddDays(-1);

                                        /*if (_orderIntegraCommerce.OrderStatus.Equals("APPROVED") && _orderIntegraCommerce.PurchasedDate.CompareTo(diaAnterior) == 1)
                                         * {
                                         *
                                         * }
                                         * else {
                                         *  pedidosARemover += order.Id + ",";
                                         *  pedidosARemoverML += order.IdOrder + ",";
                                         *  continue;
                                         * }*/
                                        /*if (!_orderIntegraCommerce.OrderStatus.Equals("APPROVED") || _orderIntegraCommerce.PurchasedDate.Day >= diaAnterior && !_orderIntegraCommerce.PurchasedDate.Year.ToString().Equals(DateTime.Now.Year.ToString()))
                                         * {
                                         *  pedidosARemover += order.Id + ",";
                                         *  pedidosARemoverML += order.IdOrder + ",";
                                         *  continue;
                                         * }*/
                                    }
                                }
                            }
                        }
                        //this.log.WriteLogPedido(pedidosARemover);
                        //this.log.WriteLogPedido(pedidosARemoverML);
                    }
                }
                else
                {
                    this.log.WriteLogPedido("Não foi possível consultar OrderQueue IntegraCommerce" + responsePedido.Result.ReasonPhrase);
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }
            catch (Exception e)
            {
                this.log.WriteLogPedido("Exception IniciarIntegracaoPedido " + e.Message);
                throw;
            }
        }
        private int InserirPedidoVenda(SAPbobsCOM.Company oCompany, OrderIntegraCommerce pedido, int idOrderQueue)
        {
            try
            {
                if (oCompany.Connected)
                {
                    OrdersDAL order        = new OrdersDAL(oCompany);
                    string    messageError = "";
                    int       oOrderNum    = 0;
                    Boolean   inserir      = true;

                    /*foreach (ItemVtex item in pedido.items)
                     * {
                     *  if (item.refId == null && inserir)
                     *  {
                     *      this.log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.orderId, "", EnumStatusIntegracao.Erro, "Um ou mais item(s) do pedido está com o código de referência inválido.");
                     *      //throw new ArgumentException("Não foi possível criar o Pedido de Venda para o pedido "+pedidoVtex.orderId+" pois um ou mais item(s) do pedido está com o código de referência inválido.");
                     *      inserir = false;
                     *  }
                     * }*/

                    if (inserir)
                    {
                        oOrderNum = order.InsertOrder(pedido, out messageError);

                        if (oOrderNum == 0)
                        {
                            Repositorio repositorio = new Repositorio();

                            //Pedido inserido no SAP, removendo pedido da fila de enventos(Feed), para não ser mais processado.

                            Task <HttpResponseMessage> response = repositorio.AtualizaFilaEnvetoPedido(idOrderQueue);

                            if (response.Result.IsSuccessStatusCode)
                            {
                                this.log.WriteLogPedido("Pedido " + pedido.IdOrder + " removido de OrderQueue");
                            }
                            else
                            {
                                this.log.WriteLogPedido("Não foi possível remover o pedido " + pedido.IdOrder + " de OrderQueue" + response.Result.ReasonPhrase);
                            }

                            //Alterar status para Processing
                            if (!pedido.OrderStatus.Equals("INVOICED"))
                            {
                                Task <HttpResponseMessage> responseIniciarManuseio = repositorio.AlterarStatusPedido(pedido.IdOrder);

                                if (responseIniciarManuseio.Result.IsSuccessStatusCode)
                                {
                                    this.log.WriteLogPedido("Alterado status do pedido " + pedido.IdOrder + " para Iniciar PROCESSING.");
                                }
                                else
                                {
                                    this.log.WriteLogPedido("Não foi possível alterar o status do pedido " + pedido.IdOrder + " para PROCESSING." + response.Result.ReasonPhrase);
                                }
                            }
                        }
                    }
                }

                return(0);
            }
            catch (Exception e)
            {
                this.log.WriteLogPedido("Exception InserirPedidoVenda " + e.Message);
                throw;
            }
        }
        public int InsertOrder(OrderIntegraCommerce pedido, out string messageError)
        {
            this.log = new Log();
            try
            {
                int oOrderNum = 0;

                log.WriteLogPedido("Inserindo Pedido de Venda " + pedido.IdOrder);

                SAPbobsCOM.Documents oOrder = (SAPbobsCOM.Documents)oCompany.GetBusinessObject(SAPbobsCOM.BoObjectTypes.oOrders);

                int    filial         = Convert.ToInt32(ConfigurationManager.AppSettings["Empresa"]);
                string usage          = ConfigurationManager.AppSettings["Usage"];
                string WhsCode        = ConfigurationManager.AppSettings["WhsCode"];
                int    SlpCode        = Convert.ToInt32(ConfigurationManager.AppSettings["SlpCode"]);
                string comments       = ConfigurationManager.AppSettings["Comments"];
                string plataforma     = ConfigurationManager.AppSettings["Plataforma"];
                string carrier        = ConfigurationManager.AppSettings["Carrier"];
                string packDesc       = ConfigurationManager.AppSettings["PackDesc"];
                int    qoP            = Convert.ToInt32(ConfigurationManager.AppSettings["QoP"]);
                int    expnsCode      = Convert.ToInt32(ConfigurationManager.AppSettings["ExpnsCode"]);
                string expnsTax       = ConfigurationManager.AppSettings["ExpnsTax"];
                string cardCodePrefix = ConfigurationManager.AppSettings["CardCodePrefix"];
                string pickRemark     = ConfigurationManager.AppSettings["PickRemark"];
                string document       = String.Empty;

                oOrder.BPL_IDAssignedToInvoice = filial;
                oOrder.NumAtCard       = pedido.IdOrder;
                oOrder.SalesPersonCode = SlpCode;
                oOrder.Comments        = comments;
                oOrder.UserFields.Fields.Item("U_PLATF").Value     = plataforma;
                oOrder.UserFields.Fields.Item("U_NumPedEXT").Value = pedido.IdOrder;
                oOrder.TaxExtension.Carrier         = carrier;
                oOrder.TaxExtension.PackDescription = packDesc;
                oOrder.TaxExtension.PackQuantity    = qoP;
                oOrder.Expenses.ExpenseCode         = expnsCode;
                oOrder.Expenses.TaxCode             = expnsTax;

                if (!String.IsNullOrEmpty(pedido.CustomerPjCnpj))
                {
                    document = pedido.CustomerPjCnpj;
                }
                else if (!String.IsNullOrEmpty(pedido.CustomerPfCpf))
                {
                    document = pedido.CustomerPfCpf;
                }

                oOrder.CardCode = cardCodePrefix + document;

                if (!string.IsNullOrEmpty(pedido.ShippedEstimatedDelivery))
                {
                    oOrder.DocDueDate = DateTime.Parse(pedido.ShippedEstimatedDelivery);
                }
                else
                {
                    oOrder.DocDueDate = DateTime.Today.AddDays(5);
                }

                if (!String.IsNullOrEmpty(pedido.ShippedCarrierName))
                {
                    oOrder.PickRemark = pedido.ShippedCarrierName;
                }

                /*
                 * double _valorFrete = 0.00;
                 * double _valorDescont = 0.00;
                 * double _valorTaxa = 0.00;
                 *
                 * despesas adicionais
                 * if (pedido.totals.Length > 0)
                 * {
                 *  foreach (Total total in pedido.totals)
                 *  {
                 *      if (total.id.Equals("Discounts"))
                 *      {
                 *          if (total.value != 0)
                 *          {
                 *              _valorDescont = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ","));
                 *          }
                 *      }
                 *      if (total.id.Equals("Shipping"))
                 *      {
                 *          if (total.value != 0)
                 *          {
                 *              _valorFrete = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ","));
                 *          }
                 *      }
                 *      if (total.id.Equals("Tax"))
                 *      {
                 *          if (total.value != 0)
                 *          {
                 *              _valorTaxa = Convert.ToDouble(total.value.ToString().Insert(total.value.ToString().Length - 2, ","));
                 *          }
                 *      }
                 *  }
                 * }
                 * oOrder.Expenses.LineGross = _valorFrete;
                 */

                //DocumentLines
                if (pedido.Products.Length > 0)
                {
                    //_valorFrete.ToString().Insert(1,".");
                    int _lineNum = 0;

                    foreach (Product item in pedido.Products)
                    {
                        if (!String.IsNullOrEmpty(item.IdSku))
                        {
                            //Recuperar Item

                            Repositorio repositorio = new Repositorio();

                            Task <HttpResponseMessage> responseSku = repositorio.BuscarItemPorSKU(item.IdSku, this.oCompany);

                            if (responseSku.Result.IsSuccessStatusCode)
                            {
                                string jsonResponseSku = responseSku.Result.Content.ReadAsStringAsync().Result;

                                var itemResponseSku = JsonConvert.DeserializeObject <Item>(jsonResponseSku);

                                if (!String.IsNullOrEmpty(itemResponseSku.IdSkuErp))
                                {
                                    oOrder.Lines.ItemCode = itemResponseSku.IdSkuErp;
                                }
                            }

                            oOrder.Lines.Quantity      = item.Quantity;
                            oOrder.Lines.WarehouseCode = WhsCode;
                            oOrder.Lines.Usage         = usage;
                            oOrder.Lines.SetCurrentLine(_lineNum);
                            oOrder.Lines.Add();
                        }

                        _lineNum++;
                    }
                }

                oOrderNum = oOrder.Add();

                if (oOrderNum != 0)
                {
                    messageError = oCompany.GetLastErrorDescription();
                    log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.IdOrder, "", EnumStatusIntegracao.Erro, messageError);
                    log.WriteLogPedido("InsertOrder error SAP: " + messageError);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oOrder);
                    return(oOrderNum);
                }
                else
                {
                    messageError = "";
                    string docNum = oCompany.GetNewObjectKey();
                    log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.IdOrder, docNum, EnumStatusIntegracao.Sucesso, "Pedido de venda inserido com sucesso.");
                    log.WriteLogPedido("Pedido de venda inserido com sucesso.");
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oOrder);
                    return(oOrderNum);
                }
            }
            catch (Exception e)
            {
                log.WriteLogTable(oCompany, EnumTipoIntegracao.PedidoVenda, pedido.IdOrder, "", EnumStatusIntegracao.Erro, e.Message);
                log.WriteLogPedido("Excpetion InsertOrder. " + e.Message);

                throw;
            }
        }
        public void InserirBusinessPartner(SAPbobsCOM.Company company, OrderIntegraCommerce pedido, out string messageError)
        {
            int addBPNumber = 0;

            string  document    = string.Empty;
            Boolean isCorporate = false;

            //Boolean marketPlace = false;

            if (!String.IsNullOrEmpty(pedido.CustomerPjCnpj))
            {
                document    = pedido.CustomerPjCnpj;
                isCorporate = true;
            }
            else if (!String.IsNullOrEmpty(pedido.CustomerPfCpf))
            {
                document = pedido.CustomerPfCpf;
            }

            try
            {
                CountyDAL countyDAL = new CountyDAL();

                this.oCompany = company;

                int    _groupCode            = Convert.ToInt32(ConfigurationManager.AppSettings["GroupCode"]);
                int    _splCode              = Convert.ToInt32(ConfigurationManager.AppSettings["SlpCode"]);
                int    _QoP                  = Convert.ToInt32(ConfigurationManager.AppSettings["QoP"]);
                int    groupNum              = Convert.ToInt32(ConfigurationManager.AppSettings["GroupNum"]);
                string indicadorIE           = ConfigurationManager.AppSettings["IndicadorIE"];
                string indicadorOpConsumidor = ConfigurationManager.AppSettings["IndicadorOpConsumidor"];
                string gerente               = ConfigurationManager.AppSettings["Gerente"];
                int    priceList             = Convert.ToInt32(ConfigurationManager.AppSettings["PriceList"]);
                string cardCodePrefix        = ConfigurationManager.AppSettings["CardCodePrefix"];
                int    categoriaCliente      = Convert.ToInt32(ConfigurationManager.AppSettings["CategoriaCliente"]);

                this.log.WriteLogPedido("Inserindo Cliente " + cardCodePrefix + document);

                BusinessPartners oBusinessPartner = null;
                oBusinessPartner = (SAPbobsCOM.BusinessPartners)oCompany.GetBusinessObject(BoObjectTypes.oBusinessPartners);

                BusinessPartners oBusinessPartnerUpdateTest = null;
                oBusinessPartnerUpdateTest = (SAPbobsCOM.BusinessPartners)oCompany.GetBusinessObject(BoObjectTypes.oBusinessPartners);

                if (oBusinessPartnerUpdateTest.GetByKey(cardCodePrefix + document))
                {
                    oBusinessPartner = oBusinessPartnerUpdateTest;
                }

                //Setando campos padrões
                oBusinessPartner.CardCode = cardCodePrefix + document;

                if (isCorporate)
                {
                    oBusinessPartner.CardName = pedido.CustomerPjCorporatename;
                }
                else
                {
                    oBusinessPartner.CardName = pedido.CustomerPfName;
                }

                //oBusinessPartner.EmailAddress = cliente.email;

                oBusinessPartner.CardType        = BoCardTypes.cCustomer;
                oBusinessPartner.GroupCode       = _groupCode;
                oBusinessPartner.SalesPersonCode = _splCode;
                oBusinessPartner.PayTermsGrpCode = groupNum;
                oBusinessPartner.PriceListNum    = priceList;
                //oBusinessPartner.CardForeignName = "Teste";

                //Setando campos de usuário
                oBusinessPartner.UserFields.Fields.Item("U_TX_IndIEDest").Value     = indicadorIE;
                oBusinessPartner.UserFields.Fields.Item("U_TX_IndFinal").Value      = indicadorOpConsumidor;
                oBusinessPartner.UserFields.Fields.Item("U_Gerente").Value          = gerente;
                oBusinessPartner.UserFields.Fields.Item("U_CategoriaCliente").Value = gerente;


                //removendo o +55
                if (!String.IsNullOrEmpty(pedido.TelephoneMainNumber))
                {
                    if (pedido.TelephoneMainNumber.Length >= 9)
                    {
                        oBusinessPartner.Phone1 = pedido.TelephoneMainNumber.Substring(2);
                    }
                    else
                    {
                        //oBusinessPartner.Phone1 = cliente.homePhone.Substring(2);
                        oBusinessPartner.Phone1 = pedido.TelephoneMainNumber;
                    }
                }
                else if (!String.IsNullOrEmpty(pedido.TelephoneBusinessNumber))
                {
                    if (pedido.TelephoneBusinessNumber.Length >= 9)
                    {
                        //oBusinessPartner.Phone1 = cliente.homePhone.Substring(2);
                        oBusinessPartner.Phone1 = pedido.TelephoneBusinessNumber.Substring(2);
                    }
                    else
                    {
                        //oBusinessPartner.Phone1 = cliente.homePhone.Substring(2);
                        oBusinessPartner.Phone1 = pedido.TelephoneBusinessNumber;
                    }
                }
                if (!String.IsNullOrEmpty(pedido.TelephoneSecundaryNumber))
                {
                    oBusinessPartner.Cellular = pedido.TelephoneSecundaryNumber;
                }

                string codMunicipio = string.Empty;

                codMunicipio = countyDAL.RecuperarCodigoMunicipio(pedido.DeliveryAddressCity, this.oCompany);

                ///Inserindo endereços
                //COBRANÇA
                oBusinessPartner.Addresses.SetCurrentLine(0);
                oBusinessPartner.Addresses.AddressType = BoAddressType.bo_BillTo;
                oBusinessPartner.Addresses.AddressName = "COBRANCA";

                oBusinessPartner.Addresses.City = pedido.DeliveryAddressCity;

                if (!String.IsNullOrEmpty(pedido.DeliveryAddressAdditionalInfo) && pedido.DeliveryAddressAdditionalInfo.Length <= 100)
                {
                    oBusinessPartner.Addresses.BuildingFloorRoom = pedido.DeliveryAddressAdditionalInfo;
                }
                else if (!String.IsNullOrEmpty(pedido.DeliveryAddressReference) && pedido.DeliveryAddressReference.Length <= 100)
                {
                    oBusinessPartner.Addresses.BuildingFloorRoom = pedido.DeliveryAddressReference;
                }

                //oBusinessPartner.Addresses.Country = "1058";
                oBusinessPartner.Addresses.Block    = pedido.DeliveryAddressNeighborhood;
                oBusinessPartner.Addresses.StreetNo = pedido.DeliveryAddressNumber;
                oBusinessPartner.Addresses.ZipCode  = pedido.DeliveryAddressZipcode;
                oBusinessPartner.Addresses.State    = pedido.DeliveryAddressState;
                oBusinessPartner.Addresses.Street   = pedido.DeliveryAddressStreet;
                oBusinessPartner.Addresses.County   = codMunicipio;
                //oBusinessPartner.Addresses.Country = "br";

                //FATURAMENTO
                oBusinessPartner.Addresses.SetCurrentLine(1);
                oBusinessPartner.Addresses.AddressType = BoAddressType.bo_ShipTo;
                oBusinessPartner.Addresses.AddressName = "FATURAMENTO";

                oBusinessPartner.Addresses.City = pedido.DeliveryAddressCity;

                if (!String.IsNullOrEmpty(pedido.DeliveryAddressAdditionalInfo) && pedido.DeliveryAddressAdditionalInfo.Length <= 100)
                {
                    oBusinessPartner.Addresses.BuildingFloorRoom = pedido.DeliveryAddressAdditionalInfo;
                }
                else if (!String.IsNullOrEmpty(pedido.DeliveryAddressReference) && pedido.DeliveryAddressReference.Length <= 100)
                {
                    oBusinessPartner.Addresses.BuildingFloorRoom = pedido.DeliveryAddressReference;
                }

                //oBusinessPartner.Addresses.Country = "1058";
                oBusinessPartner.Addresses.Block    = pedido.DeliveryAddressNeighborhood;
                oBusinessPartner.Addresses.StreetNo = pedido.DeliveryAddressNumber;
                oBusinessPartner.Addresses.ZipCode  = pedido.DeliveryAddressZipcode;
                oBusinessPartner.Addresses.State    = pedido.DeliveryAddressState;
                oBusinessPartner.Addresses.Street   = pedido.DeliveryAddressStreet;
                oBusinessPartner.Addresses.County   = codMunicipio;
                //oBusinessPartner.Addresses.Country = "br";


                #region ENDEREÇO FOR

                /*
                 * for (int i = 0; i < 2; i++)
                 * {
                 *  if (i > 0)
                 *  {
                 *      oBusinessPartner.Addresses.SetCurrentLine(i);
                 *      oBusinessPartner.Addresses.AddressType = BoAddressType.bo_ShipTo;
                 *      oBusinessPartner.Addresses.AddressName = "FATURAMENTO";
                 *  }
                 *  else
                 *  {
                 *      oBusinessPartner.Addresses.SetCurrentLine(i);
                 *      oBusinessPartner.Addresses.AddressType = BoAddressType.bo_BillTo;
                 *      oBusinessPartner.Addresses.AddressName = "COBRANCA";
                 *
                 *      if (!oBusinessPartnerUpdateTest.GetByKey(cardCodePrefix + document))
                 *      {
                 *          oBusinessPartner.Addresses.Add();
                 *      }
                 *  }
                 *
                 *  oBusinessPartner.Addresses.City = pedido.DeliveryAddressCity;
                 *
                 *  if (!String.IsNullOrEmpty(pedido.DeliveryAddressAdditionalInfo) && pedido.DeliveryAddressAdditionalInfo.Length <= 100)
                 *  {
                 *      oBusinessPartner.Addresses.BuildingFloorRoom = pedido.DeliveryAddressAdditionalInfo;
                 *  }
                 *  else if (!String.IsNullOrEmpty(pedido.DeliveryAddressReference) && pedido.DeliveryAddressReference.Length <= 100)
                 *  {
                 *      oBusinessPartner.Addresses.BuildingFloorRoom = pedido.DeliveryAddressReference;
                 *  }
                 *
                 *  //oBusinessPartner.Addresses.Country = "1058";
                 *  oBusinessPartner.Addresses.Block = pedido.DeliveryAddressNeighborhood;
                 *  oBusinessPartner.Addresses.StreetNo = pedido.DeliveryAddressNumber;
                 *  oBusinessPartner.Addresses.ZipCode = pedido.DeliveryAddressZipcode;
                 *  oBusinessPartner.Addresses.State = pedido.DeliveryAddressState;
                 *  oBusinessPartner.Addresses.Street = pedido.DeliveryAddressStreet;
                 *  oBusinessPartner.Addresses.County = codMunicipio;
                 *  //oBusinessPartner.Addresses.Country = "br";
                 *
                 * }*/
                #endregion

                oBusinessPartner.BilltoDefault = "COBRANCA";
                oBusinessPartner.ShipToDefault = "FATURAMENTO";

                BusinessPartners oBusinessPartnerUpdate = null;
                oBusinessPartnerUpdate = (SAPbobsCOM.BusinessPartners)oCompany.GetBusinessObject(BoObjectTypes.oBusinessPartners);

                if (oBusinessPartnerUpdate.GetByKey(cardCodePrefix + document))
                {
                    addBPNumber = oBusinessPartner.Update();

                    if (addBPNumber != 0)
                    {
                        messageError = oCompany.GetLastErrorDescription();
                        this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, cardCodePrefix + document, EnumStatusIntegracao.Erro, messageError);
                    }
                    else
                    {
                        messageError = "";
                        this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, cardCodePrefix + document, EnumStatusIntegracao.Sucesso, "Cliente atualizado com sucesso.");

                        System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartner);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartnerUpdate);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartnerUpdateTest);
                    }
                }
                else
                {
                    //Setando informações Fiscais
                    //oBusinessPartner.FiscalTaxID.SetCurrentLine(0);
                    if (isCorporate)
                    {
                        oBusinessPartner.FiscalTaxID.TaxId0 = document;
                    }
                    else
                    {
                        oBusinessPartner.FiscalTaxID.TaxId4 = document;
                        oBusinessPartner.FiscalTaxID.TaxId1 = "Isento";
                    }
                    //oBusinessPartner.FiscalTaxID.Address = "FATURAMENTO";
                    //oBusinessPartner.FiscalTaxID.Add();

                    addBPNumber = oBusinessPartner.Add();

                    if (addBPNumber != 0)
                    {
                        messageError = oCompany.GetLastErrorDescription();
                        this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, "", EnumStatusIntegracao.Erro, messageError);
                    }
                    else
                    {
                        string CardCode = oCompany.GetNewObjectKey();
                        this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, CardCode, EnumStatusIntegracao.Sucesso, "Cliente inserido com sucesso.");
                        messageError = "";
                    }
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartner);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartnerUpdateTest);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBusinessPartnerUpdate);
            }
            catch (Exception e)
            {
                this.log.WriteLogTable(oCompany, EnumTipoIntegracao.Cliente, document, "", EnumStatusIntegracao.Erro, e.Message);
                this.log.WriteLogPedido("InserirBusinessPartner Exception: " + e.Message);
                throw;
            }
        }