Exemplo n.º 1
0
        public void TestCreateNewCustomer(int?id, string name, string phoneNo,
                                          string email, CustomerCreation creationResult, string expectedExceptionMessage)
        {
            bool   isExceptionThrown = false;
            string exceptionMessage  = "";

            try
            {
                Customer c = new Customer(id, name, phoneNo, email);
            }
            catch (DomainException ex)
            {
                isExceptionThrown = true;
                exceptionMessage  = ex.Message;
            }

            if (creationResult == CustomerCreation.Failed)
            {
                Assert.IsTrue(isExceptionThrown, "isExceptionThrown");
                Assert.AreEqual(expectedExceptionMessage, exceptionMessage, "exceptionMessage");
            }
            else
            {
                Assert.IsFalse(isExceptionThrown, "isExceptionThrown");
            }
        }
        public CustomerResponse UpdateCustomer()
        {
            var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
            CustomerResponse CustomerResponse = null;
            var ContaAzulMiscSettings         = _settingService.LoadSetting <ContaAzulMiscSettings>(storeScope);

            var customer           = _customerService.GetCustomerById(_workContext.CurrentCustomer.Id);
            var customerPayPalPlus = _contaAzulCustomerService.GetCustomerContaAzul(customer);
            var customerMessage    = new CustomerMessage();

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

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

            try
            {
                using (var customerCreation = new CustomerCreation(ContaAzulMiscSettings.UseSandbox))
                    CustomerResponse = customerCreation.CreateAsyncUpdate(customerMessage, customerPayPalPlus.ContaAzulId.ToString(), ContaAzulMiscSettings.access_token).ConfigureAwait(false).GetAwaiter().GetResult();
            }
            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;
                }
            }

            return(CustomerResponse);
        }
Exemplo n.º 3
0
        public Tuple <bool, List <CustomerCreation> > CreateCustomer(CustomerCreation Customer)
        {
            try
            {
                //var duplicate = ValidateDuplicateEnrollment(Customer.BVN);
                //if (duplicate)
                //{
                //    List<CustomerCreation> lt = new List<CustomerCreation>();
                //    return Tuple.Create(false, lt);
                //}
                MSQconn con = new MSQconn(ConString);
                if (Customer.MaxAmount < 0)
                {
                    Customer.MaxAmount = Convert.ToDecimal(ConfigurationManager.AppSettings["DefaultMaxAmount"]);
                }
                Customer.CreatedBy = "TeamDaze Admin";
                string sql = @"insert into Customer (FirstName,LastName,BVN,PhoneNumber,EmailAddress,PanicFinger,CreatedBy,Status,
                            CreatedOn, EnrollmentType, CardType, CardToken) values (@FirstName,@LastName,@BVN,@PhoneNumber,@EmailAddress,@PanicFinger,@CreatedBy,@Status,
@CreatedOn, @EnrollmentType, @CardType, @CardToken)";
                con.SetSQL(sql);
                con.AddParam("@FirstName", Customer.FirstName);
                con.AddParam("@LastName", Customer.LastName);
                con.AddParam("@BVN", Customer.BVN);
                con.AddParam("@PhoneNumber", Customer.PhoneNumber);
                con.AddParam("@EmailAddress", Customer.EmailAddress);
                con.AddParam("@PanicFinger", Customer.PanicFinger);
                con.AddParam("@CreatedBy", Customer.CreatedBy);
                con.AddParam("@MaxAmount", Customer.MaxAmount);
                con.AddParam("@Status", 1);
                con.AddParam("@CreatedOn", DateTime.Now);
                con.AddParam("@EnrollmentType", Customer.EnrollmentType);
                con.AddParam("@CardType", Customer.CardType);
                con.AddParam("@CardToken", Customer.CardToken);


                var resp = con.Insert();
                int r    = Convert.ToInt16(resp);
                if (r == 1)
                {
                    List <CustomerCreation> lt = new List <CustomerCreation>();
                    lt.Add(Customer);
                    return(Tuple.Create(true, lt));
                }
                else
                {
                    List <CustomerCreation> lt = new List <CustomerCreation>();
                    return(Tuple.Create(false, lt));
                }
            }
            catch (Exception ex)
            {
                new ErrorLog("Customer creation error:" + ex.ToString());
                List <CustomerCreation> lt = new List <CustomerCreation>();
                return(Tuple.Create(false, lt));
            }
        }
        public void ValidUserNameTest()
        {
            // arrange
            CustomerCreation validation = new CustomerCreation();

            // act
            string usernameTest1 = "72838meah";
            string usernameTest2 = "pie";
            string usernameTest3 = "pie@2019withme";

            // assert
            Assert.True(validation.IsValidUserName(usernameTest1));
            Assert.True(validation.IsValidUserName(usernameTest2));
            Assert.False(validation.IsValidUserName(usernameTest3));
        }
        public void ValidNameTest()
        {
            // arrange
            CustomerCreation validation = new CustomerCreation();

            // act
            string nameTest1 = "Mike";
            string nameTest2 = "4after";
            string nameTest3 = "after@dark";

            // assert
            Assert.True(validation.IsValidName(nameTest1));
            Assert.False(validation.IsValidName(nameTest2));
            Assert.False(validation.IsValidName(nameTest3));
        }
        /// <summary>
        /// input/output for the process of looking up customers by name with all
        /// the validation taking place along the way and finally displaying
        /// the customers meeting the search parameters.
        /// </summary>
        public void CustomerSearch()
        {
            CustomerCreation validation = new CustomerCreation();

            Console.WriteLine("Please enter a customer's partial or full first name.");
            string firstName = Console.ReadLine();

            if (firstName == "cancel")
            {
                return;
            }

            // check if valid first name
            while (firstName != "" && !validation.IsValidName(firstName))
            {
                Console.WriteLine("Invalid first name, please enter another or an empty string.");
                firstName = Console.ReadLine();
                if (firstName == "cancel")
                {
                    return;
                }
            }

            Console.WriteLine("Please enter a customer's partial or full last name.");
            string lastName = Console.ReadLine();

            if (lastName == "cancel")
            {
                return;
            }

            // check if valid last name
            while (lastName != "" && !validation.IsValidName(lastName))
            {
                Console.WriteLine("Invalid last name, please enter another or an empty string.");
                lastName = Console.ReadLine();
                if (lastName == "cancel")
                {
                    return;
                }
            }

            CustomerQueries search            = new CustomerQueries();
            var             searchedCustomers = search.CustomerSearch(firstName, lastName);

            // check if any customers have this first/last name
            if (searchedCustomers.Count() == 0)
            {
                Console.WriteLine("There are no Customers matching the search parameters");
            }
            else
            {
                // display list of customers fitting the first/last name
                Console.WriteLine($"ID\tFirst Name\tLast Name\tUsername");
                foreach (var c in searchedCustomers)
                {
                    Console.WriteLine($"{c.CustomerID}\t{c.FirstName}" +
                                      $"\t\t{c.LastName}\t\t{c.UserName}");
                }
                Console.Write("Search Complete! ");
            }
            Console.WriteLine("Press enter to return to the menu");
            Console.ReadLine();
        }
        /// <summary>
        /// input/output for the process of adding a new customer with all
        /// the validation taking place along the way and finally adding
        /// a new customer with the given information.
        /// </summary>
        public void AddNewCustomer()
        {
            // create new instance
            using (StoreApp_DbContext db = new StoreApp_DbContext())
            {
                CustomerCreation createCustomer = new CustomerCreation();
                Customer         newCustomer    = new Customer();

                Console.WriteLine("What's the first name of the Customer?");
                newCustomer.FirstName = Console.ReadLine();
                if (newCustomer.FirstName == "cancel")
                {
                    return;
                }

                while (!createCustomer.IsValidInputName(newCustomer.FirstName))
                {
                    Console.WriteLine("Invalid first name, please enter another .");
                    newCustomer.FirstName = Console.ReadLine();
                    if (newCustomer.FirstName == "cancel")
                    {
                        return;
                    }
                }

                Console.WriteLine("What's the last name of the customer?");
                newCustomer.LastName = Console.ReadLine();
                if (newCustomer.LastName == "cancel")
                {
                    return;
                }

                while (!createCustomer.IsValidInputName(newCustomer.LastName))
                {
                    Console.WriteLine("Invalid last name, please enter another");
                    newCustomer.LastName = Console.ReadLine();
                    if (newCustomer.LastName == "cancel")
                    {
                        return;
                    }
                }

                Console.WriteLine("What would you like the username for the customer to be?");
                newCustomer.UserName = Console.ReadLine();
                if (newCustomer.UserName == "cancel")
                {
                    return;
                }

                while (!createCustomer.IsValidUserName(newCustomer.UserName))
                {
                    Console.WriteLine("Invalid username, has to be 8 to 20 characters.");
                    newCustomer.UserName = Console.ReadLine();
                    if (newCustomer.UserName == "cancel")
                    {
                        return;
                    }
                }

                db.Add <Customer>(newCustomer);
                db.SaveChanges();

                Console.WriteLine("Customer successfully added! Hit enter to go back to menu.");
                Console.ReadLine();
            }
        }
        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" );
                }
            }
        }
Exemplo n.º 10
0
        protected void btnValidateOtp_Click(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                string bvn = cardBVN.Text;
                string otp = txtOtp.Text;
                //mock otp validation
                try
                {
                    if (true)
                    {
                        //capture finger print
                        var bvnDetails = (BvnSearchResp)Session["BvnSearchResp"];
                        //Commented for reader

                        /*var resp = client.CreateSession(new AuthRequestInfo());
                         * if (resp.ResponseCode == BFSClientReturnErrorCode.SUCCESS)
                         * {
                         *  Session["sessionKey"] = resp.SessionKey;
                         * }*/
                        //create the user in the DB
                        CustomerRepository customer = new CustomerRepository();
                        //var Duplicated = customer.ValidateDuplicateEnrollment(bvn);
                        bool Duplicated = false;
                        if (Duplicated)
                        {
                            //bounce user
                            Alertdiv.InnerText = " Duplicate Records For " + bvnDetails.FirstName + " " + bvnDetails.LastName + " Unable to register";
                            Alertdiv.Visible   = true;
                            return;
                        }
                        else
                        {
                            // string sessionID = Session["sessionKey"].ToString();
                            //if (Register.ResponseCode == BFSClientReturnErrorCode.SUCCESS)
                            Start();
                            if (true)
                            {
                                //save user
                                CustomerCreation createcustomer = new CustomerCreation
                                {
                                    BVN            = cardBVN.Text,
                                    CardToken      = Guid.NewGuid().ToString(),
                                    CardType       = "2",
                                    CreatedBy      = "Daze",
                                    EmailAddress   = bvnDetails.Email,
                                    Status         = 1,
                                    CreatedOn      = DateTime.Now,
                                    EnrollmentType = "2",
                                    FirstName      = bvnDetails.FirstName,
                                    LastName       = bvnDetails.LastName,
                                    MaxAmount      = Convert.ToDecimal(ConfigurationManager.AppSettings["MaxAmount"].ToString()),
                                    PanicFinger    = "not set",
                                    PhoneNumber    = bvnDetails.PhoneNumber1
                                };

                                var CreationResponse = customer.CreateCustomer(createcustomer);

                                if (CreationResponse.Item1)
                                {
                                    //created the user, rerturn success response
                                    //var Register = client.RegisterPerson(sessionID, bvn);

                                    // client.EndSession(sessionID);
                                    Thread.Sleep(2000);
                                    Alertdiv.InnerText = bvnDetails.FirstName + " " + bvnDetails.LastName + " Was created succesfully on Touch 'N' Go Platform successfully";
                                    Alertdiv.Visible   = true;
                                    // return;
                                }
                                else
                                {
                                    //failed creation
                                    //client.EndSession(sessionID);
                                    Alertdiv.InnerText = "Failed Creation For " + bvnDetails.FirstName + " " + bvnDetails.LastName;
                                    Alertdiv.Visible   = true;
                                    return;
                                }
                            }
                            else
                            {
                                // client.EndSession(sessionID);
                                Alertdiv.InnerText = "Could Not Capture thumbprint for: " + bvnDetails.FirstName + " " + bvnDetails.LastName + " Reason:";
                                Alertdiv.Visible   = true;
                                return;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Alertdiv.Visible   = true;
                    Alertdiv.InnerText = "An error Occured Failed Creation For";
                    return;

                    //throw;
                }
            }
        }