예제 #1
0
        public void InsertCustomer(CustomerContaAzul customerContaAzul)
        {
            if (customerContaAzul == null)
            {
                throw new ArgumentNullException("customerContaAzul");
            }

            _customerContaAzulRepository.Insert(customerContaAzul);
        }
        public void Execute()
        {
            _contaAzulService.RefreshToken();

            var customers = _customerService.GetAllCustomers();

            // var storeScope = GetActiveStoreScopeConfiguration(_storeService, _workContext);
            CustomerResponse[] GetCustomerResponse = null;
            CustomerResponse   CustomerResponse    = null;
            var ContaAzulMiscSettings = _settingService.LoadSetting <ContaAzulMiscSettings>();

            var number     = string.Empty;
            var complement = string.Empty;
            var cpfCnpj    = string.Empty;

            foreach (var item in customers)
            {
                var customer = new CustomerMessage();

                new AddressHelper(_addressAttributeParser, _workContext).GetCustomNumberAndComplement(item.BillingAddress != null ? item.BillingAddress.CustomAttributes : null,
                                                                                                      out number, out complement, out cpfCnpj);

                customer.name = item.BillingAddress != null?AddressHelper.GetFullName(item.BillingAddress) : null;

                customer.companyName           = item.BillingAddress != null ? item.BillingAddress.Company : null;
                customer.email                 = item.Email;
                customer.personType            = "NATURAL";
                customer.stateRegistrationType = "NO_CONTRIBUTOR";
                customer.mobilePhone           = item.BillingAddress != null ? item.BillingAddress.PhoneNumber : null;
                customer.address.city.name     = item.BillingAddress != null ? item.BillingAddress.City : null;
                customer.address.state.name    = item.BillingAddress != null ? item.BillingAddress.StateProvince != null ? item.BillingAddress.StateProvince.Name : null : null;
                customer.address.zipCode       = item.BillingAddress != null ? item.BillingAddress.ZipPostalCode : null;
                customer.address.street        = item.BillingAddress != null ? item.BillingAddress.Address1 : null;
                customer.address.complement    = complement;
                customer.address.number        = number;
                customer.document              = cpfCnpj == "" ? null : cpfCnpj;

                try
                {
                    var filtro = "?search=";
                    if (cpfCnpj == string.Empty)
                    {
                        filtro = filtro + item.Email;
                    }
                    else
                    {
                        filtro = filtro + cpfCnpj;
                    }
                    using (var getcustomer = new GetCustomer(ContaAzulMiscSettings.UseSandbox))
                        GetCustomerResponse = getcustomer.CreateAsync(null, ContaAzulMiscSettings.access_token, filtro).ConfigureAwait(false).GetAwaiter().GetResult();
                    //busca por cpf conta azul, se existir, verifica se já foi adicionado na tabela do banco
                    if (GetCustomerResponse.Count() > 0)
                    {
                        var customerTable = _contaAzulCustomerService.GetCustomer(GetCustomerResponse[0]);
                        //caso ele não exista na tabela relacional do banco, insere e atualiza no conta azul
                        if (customerTable == null)
                        {
                            var customerContaAzul = new CustomerContaAzul();

                            customerContaAzul.ContaAzulId = GetCustomerResponse[0].id;
                            customerContaAzul.CustomerId  = item.Id;
                            customerContaAzul.DataCriacao = DateTime.Now;
                            _contaAzulCustomerService.InsertCustomer(customerContaAzul);

                            customer.id = customerTable.ContaAzulId.ToString();
                            customer.address.city.name = null;

                            var data1 = JsonConvert.SerializeObject(GetCustomerResponse[0]);
                            var data2 = JsonConvert.SerializeObject(customer);


                            // var data = data2.Equals(data1);

                            if (!data1.Equals(data2))
                            {
                                //se ele já existe na tabela, só faz o update no conta azul
                                using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                    CustomerResponse = customerCreation.CreateAsyncUpdate(customer, GetCustomerResponse[0].id.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
                            }
                        }
                        else
                        {
                            customer.id = customerTable.ContaAzulId.ToString();
                            customer.address.city.name = null;

                            var data1 = JsonConvert.SerializeObject(GetCustomerResponse[0]);
                            var data2 = JsonConvert.SerializeObject(customer);


                            var data = data2.Equals(data1);

                            if (!data1.Equals(data2))
                            {
                                //se ele já existe na tabela, só faz o update no conta azul
                                using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                    CustomerResponse = customerCreation.CreateAsyncUpdate(customer, customerTable.ContaAzulId.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
                            }
                        }
                    }
                    else
                    {//caso ele não exista no conta azul, faz a inserção dele no conta azul e no banco de dados
                        var data2 = JsonConvert.SerializeObject(customer);
                        using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                            CustomerResponse = customerCreation.CreateAsync(customer, ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();

                        if (CustomerResponse != null)
                        {
                            var customerContaAzul = new CustomerContaAzul();

                            customerContaAzul.ContaAzulId = CustomerResponse.id;
                            customerContaAzul.CustomerId  = item.Id;
                            customerContaAzul.DataCriacao = DateTime.Now;
                            _contaAzulCustomerService.InsertCustomer(customerContaAzul);
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message, ex);
                }
            }
        }
        public void SincronizaContatos()
        {
            var customers  = _customerService.GetAllCustomers();
            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);

            CustomerResponse[] GetCustomerResponse = null;
            CustomerResponse   CustomerResponse    = null;
            var ContaAzulMiscSettings = _settingService.LoadSetting <ContaAzulMiscSettings>(storeScope);


            var number     = string.Empty;
            var complement = string.Empty;
            var cpfCnpj    = string.Empty;

            foreach (var item in customers)
            {
                var customer = new CustomerMessage();

                new AddressHelper(_addressAttributeParser, _workContext).GetCustomNumberAndComplement(item.BillingAddress != null ? item.BillingAddress.CustomAttributes : null,
                                                                                                      out number, out complement, out cpfCnpj);

                customer.name = item.BillingAddress != null?AddressHelper.GetFullName(item.BillingAddress) : null;

                customer.companyName        = item.BillingAddress != null ? item.BillingAddress.Company : null;
                customer.email              = item.Email;
                customer.personType         = "NATURAL";
                customer.mobilePhone        = item.BillingAddress != null ? item.BillingAddress.PhoneNumber : null;
                customer.address.city.name  = item.BillingAddress != null ? item.BillingAddress.City : null;
                customer.address.state.name = item.BillingAddress != null ? item.BillingAddress.StateProvince != null ? item.BillingAddress.StateProvince.Name : null : null;
                // customer.address.zipCode = item.BillingAddress != null ? item.BillingAddress.ZipPostalCode : null;
                customer.address.street     = item.BillingAddress != null ? item.BillingAddress.Address1 : null;
                customer.address.complement = complement;
                customer.address.number     = number;
                customer.document           = cpfCnpj;

                try
                {
                    var filtro = "?search=" + cpfCnpj;
                    using (var getcustomer = new GetCustomer(ContaAzulMiscSettings.UseSandbox))
                        GetCustomerResponse = getcustomer.CreateAsync(null, ContaAzulMiscSettings.access_token, filtro).ConfigureAwait(false).GetAwaiter().GetResult();
                    //busca por cpf conta azul, se existir, verifica se já foi adicionado na tabela do banco
                    if (GetCustomerResponse != null)
                    {
                        var customerPayPalPlus = _contaAzulCustomerService.GetCustomer(GetCustomerResponse[0]);
                        //caso ele não exista na tabela relacional do banco, insere e atualiza no conta azul
                        if (customerPayPalPlus == null)
                        {
                            using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                CustomerResponse = customerCreation.CreateAsyncUpdate(customer, GetCustomerResponse[0].id.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();

                            if (CustomerResponse != null)
                            {
                                var customerContaAzul = new CustomerContaAzul();

                                customerContaAzul.ContaAzulId = CustomerResponse.id;
                                customerContaAzul.CustomerId  = item.Id;
                                customerContaAzul.DataCriacao = DateTime.Now;
                                _contaAzulCustomerService.InsertCustomer(customerContaAzul);
                            }
                        }
                        else
                        {
                            //se ele já existe na tabela, só faz o update no conta azul
                            using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                                CustomerResponse = customerCreation.CreateAsyncUpdate(customer, customerPayPalPlus.ContaAzulId.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
                        }
                    }
                    else
                    {//caso ele não exista no conta azul, faz a inserção dele no conta azul e no banco de dados
                        using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                            CustomerResponse = customerCreation.CreateAsync(customer, ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();

                        if (CustomerResponse != null)
                        {
                            var customerContaAzul = new CustomerContaAzul();

                            customerContaAzul.ContaAzulId = CustomerResponse.id;
                            customerContaAzul.CustomerId  = item.Id;
                            customerContaAzul.DataCriacao = DateTime.Now;
                            _contaAzulCustomerService.InsertCustomer(customerContaAzul);
                        }
                    }
                }
                catch (Exception ex)
                {
                    try
                    {
                        var retorno = JsonConvert.DeserializeObject <MiscExecutitionResponse>(ex.Message, ConverterPaymentExecution.Settings);

                        if (retorno.StatusCode == "401")
                        {
                            RefreshToken();
                            _logger.Error("Token expirado " + ContaAzulMiscSettings.access_token, ex);
                        }
                        else
                        {
                            _logger.Error(ex.Message, ex);
                        }
                    }
                    catch (Exception erro)
                    {
                        _logger.Error(erro.Message, erro);

                        throw;
                    }

                    // ErrorNotification("O Customer com id " + item.Id + " não foi encontrado" );
                }
            }
        }