/// <summary> /// Inserir pedido no ERP /// </summary> /// <param name="token">Token autenticado</param> /// <param name="order">Objeto do pedido</param> /// <returns></returns> public async Task <HttpResponseMessage> InsertOrderAsync(string token, AicOrderInsertModel order) { HttpClient _client = new HttpClient(); _client.BaseAddress = AppSettings.Apis.AicBrasilApi; _client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return(await new HttpClientHelper(_client) .SetEndpoint($"api/orders") .AddHeader("Authorization", $"Bearer {token}") .WithContentSerialized(order) .PostAsync()); }
/// <summary> /// Insere o Pedido no ERP /// </summary> /// <param name="token">token</param> /// <param name="order">Pedido</param> /// <returns></returns> public AicOrderReturnModel InsertOrderAsync(string token, AicOrderInsertModel order) { try { _logger.LogInformation("Inserir Pedido AIC: Enviando requisição para a API"); var response = _aicBrasilApi.InsertOrderAsync(token, order).Result; if (!response.IsSuccessStatusCode) { var contentResult = response.Content.ReadAsStringAsync().Result; _logger.LogError($"Inserir Pedido AIC: API retornou erro :( - {response.StatusCode}-{response.ReasonPhrase} -> {contentResult}"); if (((int)response.StatusCode) >= 400 && ((int)response.StatusCode) < 500) return null; } _logger.LogInformation("inserir Pedido AIC: API retornou sucesso :)"); var json = response.Content.ReadAsStringAsync().Result; return Task.Factory.StartNew(() => JsonConvert.DeserializeObject<AicOrderReturnModel>(json)).Result; } catch (Exception) { _logger.LogError($"Inserir Pedido AIC: API retornou erro :("); return null; } }
/// <summary> /// Iniciar a integração do serviço - Pedidos /// </summary> public void RunIntegrationOrder(string tokenAicBrasil) { _logger.LogInformation($"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} - RunIntegrationOrder em execução."); _logger.LogInformation($"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} - RunIntegrationProductsAndBrands- Token AIC : {tokenAicBrasil}"); if (string.IsNullOrWhiteSpace(tokenAicBrasil)) { return; } /* autenticação na idealeWare*/ var token = _HttpTransferAutenthicateApi.Login(AppSettings.GetUserIdealeware()); if (token == null) { return; } //Busca os pedidos nao integrados do ecommerce var ordersNotIntegrated = _HttpTransferOrder.GetOrdersNotIntegrated(token.AccessToken); if (ordersNotIntegrated == null) { return; } //Loop nos pedidos foreach (var order in ordersNotIntegrated) { try { //Verifico se o cliente existe var customersAicBrasil = _HttpTransferAicBrasilApi.GetCustomersByCpfAsync(tokenAicBrasil, order.Customer.Cpf_Cnpj); if (!customersAicBrasil.customers.Any()) { var resultInsertCustumer = _HttpTransferAicBrasilApi.InsertCustomerAsync(tokenAicBrasil, new CustomerInsertAicBrasil { customers = new List <CustomerCreateAicBrasil> { new CustomerCreateAicBrasil { code = order.Customer.Id.ToString(), cpfcnpj = order.Customer.Cpf_Cnpj, email = order.Customer.Email, firstname = order.Customer.Firstname_Companyname, lastname = order.Customer.Lastname_Tradingname, ie = order.Customer.Rg_Ie, phone = order.Customer.Phone, billingaddress = new BillingAddressAicBrasil { address1 = order.BillingAddress.AddressLine1, address2 = order.BillingAddress.AddressLine2, city = order.BillingAddress.City, country = "BR", district = order.BillingAddress.District, number = Convert.ToInt32(order.BillingAddress.Number), state = order.BillingAddress.State, zipCode = order.BillingAddress.ZipCode }, shippingaddress = new ShippingAddressAicBrasil { address1 = order.DeliveryAddress.AddressLine1, address2 = order.DeliveryAddress.AddressLine2, city = order.DeliveryAddress.City, country = "BR", district = order.DeliveryAddress.District, number = Convert.ToInt32(order.DeliveryAddress.Number), state = order.DeliveryAddress.State, zipcode = order.DeliveryAddress.ZipCode } } } }); order.Customer.Id = resultInsertCustumer.customers.FirstOrDefault().code; } else { order.Customer.Id = customersAicBrasil.customers?.FirstOrDefault()?.code ?? order.Customer.Id; } _logger.LogInformation($"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} -Number {order.OrderNumber} - Iniciando integração do pedido."); //Preenche informaçoes basicas do pedido var orderAic = new AicOrderModel() { orderTotal = order.OrderPrice, orderDiscount = order.TotalDiscountPrice, destinationtype = "VendaUsuarioFinal", shippingtype = "PorContaDoDestinatarioRemetente", customercode = order.Customer.Id.ToString(), }; switch (order.Payment.PaymentMethods.FirstOrDefault().Type) { case enPaymentMethodType.CreditCard: orderAic.billingtype = "CreditCard"; orderAic.installments = order.Payment.PaymentMethods.FirstOrDefault().CreditCardInstallmentCount; break; case enPaymentMethodType.BankSlip: orderAic.billingtype = "Boleto"; orderAic.installments = 1; break; case enPaymentMethodType.Money: orderAic.billingtype = "Money"; orderAic.installments = 1; break; case enPaymentMethodType.Other: orderAic.billingtype = "Money"; orderAic.installments = 1; break; } //Loop nos produtos do pedido orderAic.orderitens = new List <AicItemOrderModel>(); foreach (var item in order.Products) { orderAic.orderitens.Add(new AicItemOrderModel() { code = item.Sku.Code, }); } var orderInsert = new AicOrderInsertModel { orders = new List <AicOrderModel> { orderAic } }; //Inserir o pedido no ERP var orderAicIntegrated = _HttpTransferAicBrasilApi.InsertOrderAsync(tokenAicBrasil, orderInsert); if (orderAicIntegrated == null) { continue; } //Atualiza o pedido para integrado no ecommerce var orderIntregrated = _HttpTransferOrder.UpdateOrderIntegrated(token.AccessToken, order.Id.ToString()); if (orderIntregrated == null) { continue; } _logger.LogInformation($"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} -Pedido {order.OrderNumber} - Finalizado Integração com sucesso"); } catch (Exception ex) { _logger.LogError($"{DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")} -Pedido {order.OrderNumber} - RunIntegrationOrder ERRO {ex.Message}."); continue; } } }