示例#1
0
        public void Handle(CustomerGetDetailsCommand command)
        {
            InfoAccumulator info = new InfoAccumulator();

            int customerId;

            try {
                customerId = CustomerIdEncryptor.DecryptCustomerId(command.CustomerId, command.CommandOriginator);
            } catch (Exception ex) {
                Log.Error(ex.Message);
                info.AddError("Invalid customer id.");
                SendReply(info, command);
                return;
            }

            Customer customer = CustomerQueries.GetCustomerById(customerId);
            IEnumerable <CustomerAddress> addresses = CustomerQueries.GetCustomerAddresses(customerId);
            IEnumerable <CustomerPhone>   phones    = CustomerQueries.GetCustomerPhones(customerId);
            var requesetedLoan = LoanQueries.GetCustomerRequestedLoan(customerId);

            SendReply(info, command, resp => {
                resp.PersonalDetails           = GetPersonalDetails(customer);
                resp.ContactDetails            = GetContactDetails(phones, customer);
                resp.CurrentLivingAddress      = GetCurrentLivingAddress(addresses, customer);
                resp.PreviousLivingAddress     = GetPreviousLivingAddress(addresses, customer);
                resp.AdditionalOwnedProperties = GetAdditionalOwnedProperties(addresses, customer)
                                                 .ToArray();
                resp.RequestedAmount = (decimal)requesetedLoan.Map(o => o.Amount.HasValue ? o.Amount.Value : 0);
            });
        }
示例#2
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity <Customer>().ToTable("Customers");
            modelBuilder.Entity <Employee>().ToTable("Employees");
            modelBuilder.Entity <Product>().ToTable("Products");
            modelBuilder.Entity <Order>().ToTable("Orders");
            modelBuilder.Entity <OrderDetail>().ToTable("Order Details");

            modelBuilder.Entity <CustomerOrderHistory>().HasKey(coh => coh.ProductName);
            modelBuilder.Entity <MostExpensiveProduct>().HasKey(mep => mep.TenMostExpensiveProducts);

            modelBuilder.Entity <CustomerQuery>().HasNoKey().ToQuery(
                () => CustomerQueries.FromSqlInterpolated(
                    $"SELECT [c].[CustomerID] + {_empty} as [CustomerID], [c].[Address], [c].[City], [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone], [c].[PostalCode], [c].[Region] FROM [Customers] AS [c]"
                    ));

            modelBuilder
            .Entity <OrderQuery>()
            .HasNoKey()
            .ToQuery(
                () => Orders
                .FromSqlRaw(@"select * from ""Orders""")
                .Select(
                    o => new OrderQuery {
                CustomerID = o.CustomerID
            }));

            modelBuilder.Entity <ProductView>().HasNoKey().ToView("Alphabetical list of products");
        }
示例#3
0
 public Customer GetByUserId(int id)
 {
     return(_context.Customers
            .Include(c => c.AddressList)
            .Include(c => c.CreditCardList)
            .FirstOrDefault(CustomerQueries.GetByUserId(id)));
 }
示例#4
0
 public Customer GetByEmailOrCPF(string email, string cpf)
 {
     return(_context.Customers
            .Include(c => c.AddressList)
            .Include(c => c.CreditCardList)
            .FirstOrDefault(CustomerQueries.GetByEmailOrCPF(email, cpf)));
 }
        public void lookUpCustomer()
        {
            CustomerQueries search = new CustomerQueries();

            Console.WriteLine("Please enter First and Last Name with space seperating them.");
            string input = Console.ReadLine();

            string[] name = input.Split(' ');
            while (name.Count() < 2)
            {
                Console.WriteLine("Invalid input, please try again");
                input = Console.ReadLine();
                name  = input.Split(' ');
            }
            var results = search.findCustomer(name[0], name[1]);

            if (results.Count() == 0)
            {
                Console.WriteLine("There are no customers found under that name");
            }
            else
            {
                Console.WriteLine($"ID\tFirst Name\tLast Name\tPhoneNumber");
                foreach (var c in results)
                {
                    Console.WriteLine($"{c.CustomerID}\t{c.FirstName}" +
                                      $"\t\t{c.LastName}\t\t{c.PhoneNumber}");
                }
            }
            Console.WriteLine("Press enter to return to the menu");
            Console.ReadLine();
        }
        public void showOrderHistory()
        {
            Console.Clear();
            showCustomerList();
            CustomerQueries customerQuery = new CustomerQueries();

            Console.WriteLine("Please Enter the ID of the Customer you would like to view History of");
            string input = Console.ReadLine();

            int.TryParse(input, out int result);

            if (customerQuery.existsCustomer(result))
            {
                var orders   = customerQuery.getHistory(result);
                var customer = customerQuery.getCustomer(result);
                if (orders.Count() == 0)
                {
                    Console.WriteLine($"No history Found for {customer.FirstName} {customer.LastName}");
                }
                else
                {
                    Console.WriteLine($"{customer.FirstName} {customer.LastName}");
                    Console.WriteLine("StoreID\tOrder ID\tProduct\t\tQuantity\tTotal\t\tTime");
                    foreach (var o in orders)
                    {
                        double total = o.Product.Price * o.Count;
                        Console.WriteLine($"{o.Product.Store.StoreID}\t{o.OrderID}\t\t" +
                                          $"{o.Product.Name}\t{o.Count}\t\t{total}\t\t{o.Time}");
                    }
                }
                Console.WriteLine("Press enter to return to the menu");
                Console.ReadLine();
            }
        }
        public void GetCustomerListTypedListTest()
        {
            var actual = CustomerQueries.GetCustomerListTypedList(MaxNumberOfItemsToReturn);

            Assert.AreEqual(MaxNumberOfItemsToReturn, actual.ToList().Count());
            Assert.AreEqual(MaxNumberOfItemsToReturn, actual.Count());
        }
        public void ValidCustomerIDQueryTest()
        {
            //Arrange
            var options = new DbContextOptionsBuilder <StoreApp_DbContext>()
                          .UseInMemoryDatabase(databaseName: "CustomerQueriesTests")
                          .Options;

            //Act
            using (var db = new StoreApp_DbContext(options))
            {
                Customer customer = new Customer
                {
                    FirstName = "Michael",
                    LastName  = "Hall",
                    UserName  = "******"
                };

                db.Add(customer);
                db.SaveChanges();
            }

            //Assert
            using (var context = new StoreApp_DbContext(options))
            {
                Assert.Equal(1, context.Customers.Count());
                CustomerQueries check = new CustomerQueries();

                Assert.False(check.IsValidCustomerID(1));
                Assert.False(check.IsValidCustomerID(2));
                Assert.False(check.IsValidCustomerID(-5));
            }
        }
 public IEnumerable <Customer> GetAll(string search)
 {
     return(_context.Customers
            .AsNoTracking()
            .Where(CustomerQueries.GetAll(search))
            .ToList());
 }
示例#10
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity <Customer>().ToTable("Customers");
            modelBuilder.Entity <Employee>().ToTable("Employees");
            modelBuilder.Entity <Product>().ToTable("Products");
            modelBuilder.Entity <Order>().ToTable("Orders");
            modelBuilder.Entity <OrderDetail>().ToTable("Order Details");

            modelBuilder.Entity <CustomerOrderHistory>().HasKey(coh => coh.ProductName);
            modelBuilder.Entity <MostExpensiveProduct>().HasKey(mep => mep.TenMostExpensiveProducts);

#pragma warning disable CS0618 // Type or member is obsolete
            modelBuilder.Query <CustomerView>().HasNoKey().ToQuery(
                () => CustomerQueries.FromSqlRaw("SELECT * FROM Customers"));

            modelBuilder
            .Query <OrderQuery>()
            .ToQuery(
                () => Orders
                .FromSqlRaw(@"select * from ""Orders""")
                .Select(
                    o => new OrderQuery
            {
                CustomerID = o.CustomerID
            }));

            modelBuilder.Query <ProductQuery>().ToView("Alphabetical list of products");
#pragma warning restore CS0618 // Type or member is obsolete
        }
        public void ReturnNullWhenDocumentNotExists()
        {
            var expression = CustomerQueries.GetByDocument("12345678956");
            var customs    = _customers.AsQueryable().Where(expression).FirstOrDefault();

            Assert.AreEqual(null, customs);
        }
示例#12
0
 public Customer GetByEmail(string email)
 {
     return(_context.Customers
            .AsNoTracking()
            .Include(c => c.AddressList)
            .Include(c => c.CreditCardList)
            .FirstOrDefault(CustomerQueries.GetByEmail(email)));
 }
示例#13
0
        /// <summary>
        /// Handles a message.
        /// </summary>
        /// <param name="command">The command to handle.</param>
        /// <remarks>
        /// This method will be called when a message arrives on the bus and should contain
        ///             the custom logic to execute when the command is received.
        /// </remarks>
        public void Handle(CustomerUpdateCommand command)
        {
            InfoAccumulator info = new InfoAccumulator();

            if (!ValidateCommand(command, info))
            {
                SendReply(info, command, response => response.CustomerId = command.CustomerId);
                return;
            }

            int customerId;

            try {
                customerId = CustomerIdEncryptor.DecryptCustomerId(command.CustomerId, command.CommandOriginator);
            } catch (Exception ex) {
                Log.Error(ex.Message);
                info.AddError("Invalid customer id.");
                SendReply(info, command, resp => resp.CustomerId = command.CustomerId);
                return;
            }

            //requests only PropertyStatusId from DB
            Customer customer = CustomerQueries.GetCustomerPartiallyById(customerId, o => o.PropertyStatusId);

            FillCustomerProperties(customer, command, info);
            if (info.HasErrors)
            {
                SendReply(info, command, resp => resp.CustomerId = command.CustomerId);
                return;
            }

            IEnumerable <CustomerAddress> addresses = FillCustomerPropertyStatusAndTimeAtAddressAndGetAddresses(command, customer, customerId);
            IEnumerable <CustomerPhone>   phones    = ExtractPhoneNumbers(command, customerId);

            string referenceSource = null;
            string visitTimes      = null;

            if (command.Cookies != null)
            {
                referenceSource = command.Cookies.ReferenceSource;
                visitTimes      = command.Cookies.VisitTimes;
            }

            var errors = CustomerProcessor.UpdateCustomer(customer, command.RequestedAmount, referenceSource, visitTimes, command.CampaignSourceRef, addresses, phones);

            if (errors.HasErrors)
            {
                if (errors.IsRetry)
                {
                    RegisterError(info, command);
                }

                return;
            }

            SendReply(errors, command, response => response.CustomerId = command.CustomerId);
        }
示例#14
0
        /// <summary>
        /// Gets the user identifier by email address.
        /// </summary>
        /// <param name="emailAddress">The email address.</param>
        /// <returns></returns>
        public Optional <int> GetUserIdByUserName(string emailAddress)
        {
            if (emailAddress.IsEmpty())
            {
                throw new ArgumentException("Got empty email address");
            }

            return(CustomerQueries.GetUserIdByUserName(emailAddress));
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            ModelHelpers.SetStringLengths(modelBuilder);

            modelBuilder.Entity <CustomerView>().HasNoKey().ToQuery(
                () => CustomerQueries.FromSqlInterpolated($@"SELECT ""c"".""CustomerID"" || {_empty} as ""CustomerID"", ""c"".""Address"", ""c"".""City"", ""c"".""CompanyName"", ""c"".""ContactName"", ""c"".""ContactTitle"", ""c"".""Country"", ""c"".""Fax"", ""c"".""Phone"", ""c"".""PostalCode"", ""c"".""Region"" FROM ""Customers"" AS ""c"""
                                                          ));
        }
示例#16
0
    public IQueryable <TEntity> Set <TEntity>()
        where TEntity : class
    {
        if (typeof(TEntity) == typeof(Customer))
        {
            return((IQueryable <TEntity>)Customers.AsQueryable());
        }

        if (typeof(TEntity) == typeof(Employee))
        {
            return((IQueryable <TEntity>)Employees.AsQueryable());
        }

        if (typeof(TEntity) == typeof(Order))
        {
            return((IQueryable <TEntity>)Orders.AsQueryable());
        }

        if (typeof(TEntity) == typeof(OrderDetail))
        {
            return((IQueryable <TEntity>)OrderDetails.AsQueryable());
        }

        if (typeof(TEntity) == typeof(Product))
        {
            return((IQueryable <TEntity>)Products.AsQueryable());
        }

        if (typeof(TEntity) == typeof(CustomerQuery))
        {
            return((IQueryable <TEntity>)CustomerQueries.AsQueryable());
        }

        if (typeof(TEntity) == typeof(OrderQuery))
        {
            return((IQueryable <TEntity>)OrderQueries.AsQueryable());
        }

        if (typeof(TEntity) == typeof(ProductQuery))
        {
            return((IQueryable <TEntity>)ProductQueries.AsQueryable());
        }

        if (typeof(TEntity) == typeof(ProductView))
        {
            return((IQueryable <TEntity>)ProductViews.AsQueryable());
        }

        if (typeof(TEntity) == typeof(CustomerQueryWithQueryFilter))
        {
            return((IQueryable <TEntity>)CustomerQueriesWithQueryFilter.AsQueryable());
        }

        throw new InvalidOperationException("Invalid entity type: " + typeof(TEntity));
    }
示例#17
0
        public void GetCostumersAsync_Test()
        {
            Mock <IOptions <DatabaseConfig> > optionsMock = new Mock <IOptions <DatabaseConfig> >();

            optionsMock.SetupGet(o => o.Value).Returns(new DatabaseConfig()
            {
                ConnectionString = "conString"
            });
            ICustomerQueries queries   = new CustomerQueries(optionsMock.Object);
            Task             queryTask = Task.Run(() => queries.GetCostumersAsync(0, 10));
        }
        public void CustomerQueryExceptionTest()
        {
            // arrange
            var options = new DbContextOptionsBuilder <StoreApp_DbContext>()
                          .UseInMemoryDatabase(databaseName: "CustomerQueryExceptionTest")
                          .Options;
            CustomerQueries check = new CustomerQueries();

            // assert
            check.CustomerSearch("yes", "no");
        }
        public void showCustomerList()
        {
            Console.Clear();
            CustomerQueries customerQuery = new CustomerQueries();
            var             customerList  = customerQuery.getCustomersAll();

            Console.WriteLine("ID\tFirst Name\tLast Name\tPhonenumber");
            foreach (var c in customerList)
            {
                Console.WriteLine($"{c.CustomerID}\t{c.FirstName}\t{c.LastName}\t{c.PhoneNumber}");
            }
            Console.WriteLine("Press enter to return to the menu");
            Console.ReadLine();
        }
示例#20
0
        static void Main(string[] args)
        {
            Database.SetInitializer(new SalesDbInitializer());

            var context         = new SalesContext();
            var customerQueries = new CustomerQueries(context);

            var demo = new Demo(customerQueries);

            var customers = demo.Run().Result;

            foreach (var cust in customers)
            {
                System.Console.WriteLine(cust.Name);
            }
        }
示例#21
0
        /// <summary>
        /// Handles the CustomerSignupCommand.
        /// </summary>
        /// <param name="command">The command.</param>
        public void Handle(CustomerSignupCommand command)
        {
            InfoAccumulator info = ValidateSignupCommand(command);

            if (info.HasErrors)
            {
                SendReply(info, command);
                return;
            }

            //TODO: code below contains race condition. We should find a way to validate to do it properly

            if (!BrokerQueries.IsExistsBroker(command.EmailAddress))
            {
                Log.ErrorFormat("Attempt to sign in customer with email of broker: {0}", command.EmailAddress);
                info.AddError("Sign-up error");
                SendReply(info, command);
                return;
            }

            SecurityUser user;

            try {
                user = CustomerQueries.CreateSecurityUser(command.EmailAddress, command.Password, command.SequrityQuestionId ?? 0, command.SecurityQuestionAnswer, command.CommandOriginatorIP);
            } catch (SqlException ex) {
                Log.ErrorFormat("Attempt to sign in existing customer: {0}", command.EmailAddress);
                info.AddError("Sign-up error");
                SendReply(info, command);
                return;
            }



            Customer customer = ConvertToCustomer(command, user);
            int      id       = (int)CustomerQueries.UpsertCustomer(customer);

            if (id < 1)
            {
                Log.ErrorFormat("could not create customer of user: "******"could not create customer");
            }

            string encryptedCustomerId = CustomerIdEncryptor.EncryptCustomerId(customer.Id, command.CommandOriginator);

            SendReply(info, command, response => response.CustomerId = encryptedCustomerId);
        }
示例#22
0
        /// <summary>
        /// Creates the customer.
        /// </summary>
        /// <param name="cmd">The command.</param>
        /// <returns></returns>
        private Customer ConvertToCustomer(CustomerSignupCommand cmd, SecurityUser user)
        {
            Customer customer = new Customer();

            customer.Name      = cmd.EmailAddress.ToLowerInvariant();
            customer.OriginID  = ConvertToOriginId(cmd.CommandOriginator);
            customer.Vip       = CustomerQueries.IsVip(cmd.EmailAddress.ToLowerInvariant()) ?? false; //TODO: look again in this flow, how we get vip
            customer.Id        = user.UserId;
            customer.RefNumber = RefNumGenerator.GenerateRefNumber();

            customer.Status               = CustomerStatus.Registered.ToString();
            customer.WizardStep           = (int)WizardStepType.SignUp;
            customer.CollectionStatus     = (int)CollectionStatusNames.Enabled;
            customer.TrustPilotStatusID   = (int)TrustPilotStauses.Neither;
            customer.GreetingMailSentDate = DateTime.UtcNow;
            customer.BrokerID             = null;
            return(customer);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.HasPostgresExtension("uuid-ossp");

            modelBuilder.Entity <Customer>()
            .Property(c => c.CustomerID)
            .HasColumnType("varchar(5)");

            modelBuilder.Entity <Employee>(
                b =>
            {
                b.Property(c => c.EmployeeID).HasColumnType("int4");
                b.Property(c => c.ReportsTo).HasColumnType("int4");
            });

            modelBuilder.Entity <Order>()
            .Property(o => o.EmployeeID)
            .HasColumnType("int4");
            modelBuilder.Entity <OrderDetail>()
            .Property(od => od.UnitPrice)
            .HasColumnType("money");

            modelBuilder.Entity <Product>(
                b =>
            {
                b.Property(p => p.UnitPrice).HasColumnType("money");
                b.Property(p => p.UnitsInStock).HasColumnType("int2");
            });

            modelBuilder.Entity <MostExpensiveProduct>()
            .Property(p => p.UnitPrice)
            .HasColumnType("money");

#pragma warning disable CS0618 // Type or member is obsolete
            modelBuilder.Query <CustomerView>().HasNoKey().ToQuery(
                () => CustomerQueries.FromSqlInterpolated($@"SELECT ""c"".""CustomerID"" || {_empty} as ""CustomerID"", ""c"".""Address"", ""c"".""City"", ""c"".""CompanyName"", ""c"".""ContactName"", ""c"".""ContactTitle"", ""c"".""Country"", ""c"".""Fax"", ""c"".""Phone"", ""c"".""PostalCode"", ""c"".""Region"" FROM ""Customers"" AS ""c"""
                                                          ));
#pragma warning restore CS0618 // Type or member is obsolete
        }
 public IEnumerable Query()
 {
     return(CustomerQueries.GetCustomerViewTypedView(5));
 }
        /// <summary>
        /// input/output for the process of displaying an customer's history with all
        /// the validation taking place along the way and finally displaying
        /// the history of the customer meeting the input parameters.
        /// </summary>
        public void DisplayCustomerHistory()
        {
            CustomerQueries checkCustomer = new CustomerQueries();
            OrderCreation   checkNum      = new OrderCreation();

            // get and display all the customer info to pick from
            var customers = checkCustomer.GetCustomers();

            Console.WriteLine("ID\tFirst Name\tLast Name\tUsername");
            foreach (var c in customers)
            {
                Console.WriteLine($"{c.CustomerID}\t{c.FirstName}" +
                                  $"\t\t{c.LastName}\t\t{c.UserName}");
            }

            Console.WriteLine("Please enter an ID from above for the customer you would like to see.");
            int customerID;

            do
            {
                string input = Console.ReadLine();
                if (input == "cancel")
                {
                    return;
                }

                // check if input is an int
                while (!checkNum.IsValidNum(input))
                {
                    Console.WriteLine("Invalid ID number, please enter another.");
                    input = Console.ReadLine();
                    if (input == "cancel")
                    {
                        return;
                    }
                }

                int id = checkNum.StringToInt(input);

                // check to see if there is a customer with the given ID
                if (checkCustomer.IsValidCustomerID(id))
                {
                    customerID = id;
                }
                else
                {
                    Console.WriteLine("There is no customer with this ID, please enter another.");
                    customerID = 0;
                }
            } while (customerID == 0); // repeat if no customer with that ID

            var customerHistory = checkCustomer.GetCustomerHistory(customerID);
            var customer        = checkCustomer.GetCustomer(customerID);

            // get and display the order history of that customer if they have one
            if (customerHistory.Count() == 0)
            {
                Console.WriteLine($"As of now, {customer.FirstName} {customer.LastName} has placed no orders.");
            }
            else
            {
                Console.WriteLine($"Order history for {customer.FirstName} {customer.LastName}");
                Console.WriteLine("Location\tOrder ID\tProduct\t\tQuantity\tTotal\t\tTimestamp");
                foreach (var o in customerHistory)
                {
                    double price = o.Product.Price * o.Quantity;
                    Console.WriteLine($"{o.Product.Store.Location}\t{o.OrderID}\t\t" +
                                      $"{o.Product.ProductName}\t" +
                                      $"{o.Quantity}\t\t${price}\t\t{o.Timestamp}");
                }
            }

            Console.WriteLine("Press enter to return to the menu");
            Console.ReadLine();
        }
        /// <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 order with all
        /// the validation taking place along the way and finally adding
        /// a new order with the given information.
        /// </summary>
        public void AddNewOrder()
        {
            // declare new instance(s)
            using (StoreApp_DbContext db = new StoreApp_DbContext())
            {
                OrderCreation   createOrder   = new OrderCreation();
                CustomerQueries checkCustomer = new CustomerQueries();
                Order           newOrder      = new Order();

                Console.WriteLine("Please enter the customerID of your Customer placing an order.");
                do
                {
                    string input = Console.ReadLine();
                    if (input == "cancel")
                    {
                        return;
                    }

                    // check if input is an int
                    while (!createOrder.IsValidNum(input))
                    {
                        Console.WriteLine("Invalid customerID number, please enter another.");
                        input = Console.ReadLine();
                        if (input == "cancel")
                        {
                            return;
                        }
                    }

                    // check if there is a customer with the inputted ID
                    int id = createOrder.StringToInt(input);
                    if (checkCustomer.IsValidCustomerID(id))
                    {
                        newOrder.CustomerID = id;
                    }
                    else
                    {
                        Console.WriteLine("There is no Customer with this ID, please enter another.");
                        newOrder.CustomerID = 0;
                    }
                } while (newOrder.CustomerID == 0); // repeat if there is no customer with the ID

                // display all the available products
                ProductQueries checkProducts = new ProductQueries();
                var            products      = checkProducts.GetProducts();
                Console.WriteLine("Here are all the available products:");
                Console.WriteLine("ID\tStore\t\tName\t\tInventory\tPrice");
                foreach (var p in products)
                {
                    Console.WriteLine($"{p.ProductID}\t{p.Store.Location}\t{p.ProductName}" +
                                      $"\t{p.Inventory}\t\t{p.Price}");
                }

                bool multipleProducts;
                int  productCount = 0;

                do
                {
                    Console.WriteLine("Please enter the ID of the product being ordered");

                    do
                    {
                        string input = Console.ReadLine();
                        if (input == "cancel")
                        {
                            return;
                        }

                        // check if input is an int
                        while (!createOrder.IsValidNum(input))
                        {
                            Console.WriteLine("Invalid product ID number, please enter another.");
                            input = Console.ReadLine();
                            if (input == "cancel")
                            {
                                return;
                            }
                        }

                        int id = createOrder.StringToInt(input);
                        // check if there is a product with the inputted ID
                        if (checkProducts.IsValidProductID(id))
                        {
                            newOrder.ProductID = id;
                        }
                        else
                        {
                            Console.WriteLine("There is no product with this ID or there is none left, please enter another.");
                            newOrder.ProductID = 0;
                        }
                    } while (newOrder.ProductID == 0); // repeat if no product with that ID

                    var product = checkProducts.GetProductName(newOrder.ProductID);
                    Console.WriteLine($"For buying, specify the number of {product.ProductName}");

                    do
                    {
                        string input = Console.ReadLine();
                        if (input == "cancel")
                        {
                            return;
                        }

                        // check if input is an int
                        while (!createOrder.IsValidNum(input))
                        {
                            Console.WriteLine("Invalid amount, please enter another.");
                            input = Console.ReadLine();
                            if (input == "cancel")
                            {
                                return;
                            }
                        }

                        int amount = createOrder.StringToInt(input);
                        // check if the inventory is high enough for given amount
                        if (amount == 0)
                        {
                            Console.WriteLine("Please specify an amount");
                        }
                        else if (createOrder.IsUnreasonableQuantity(amount))
                        {
                            // if the amount requested is unreasonable (>=10)
                            Console.WriteLine($"{amount} is an unreasonable amount of {product.ProductName}");
                            newOrder.Quantity = 0;
                        }
                        else if (checkProducts.IsValidProductQuantity(amount, newOrder.ProductID))
                        {
                            // if there is enough product and it is reasonable
                            newOrder.Quantity = amount;
                        }
                        else
                        {
                            Console.WriteLine($"There is not {amount} available at this store, please enter another amount.");
                            newOrder.Quantity = 0;
                        }
                    } while (newOrder.Quantity == 0); // repeat if not enough product or unreasonable

                    Console.WriteLine("Would you like to include another product in this order (yes or no)?");
                    string addProduct = Console.ReadLine();
                    if (addProduct == "cancel")
                    {
                        return;
                    }

                    // check if they are saying yes or no to extra product
                    while (addProduct != "yes" && addProduct != "no")
                    {
                        Console.WriteLine("Please pick put in one of the two");
                        addProduct = Console.ReadLine();
                        if (addProduct == "cancel")
                        {
                            return;
                        }
                    }

                    if (addProduct == "yes")
                    {
                        multipleProducts = true;
                    }
                    else
                    {
                        multipleProducts = false;
                    }

                    productCount++;

                    if (productCount == 1)
                    {
                        // keep same timestamp for multiple product order
                        newOrder.Timestamp = createOrder.GetTimeStamp();
                    }

                    db.Add <Order>(newOrder);
                    db.SaveChanges();

                    StoreQueries updateStore = new StoreQueries();
                    updateStore.UpdateInventory(newOrder);

                    newOrder.OrderID++;
                } while (multipleProducts); // go back if they wanted another product
                Console.WriteLine("Order successfully placed! Hit enter to go back to menu.");
                Console.ReadLine();
            }
        }
        public async Task <IActionResult> SyncCustomers()
        {
            var errorList        = new List <string>();
            var customersCreated = 0;
            var customersUpdated = 0;

            try
            {
                if (_db.Connection.State == System.Data.ConnectionState.Closed)
                {
                    await _db.Connection.OpenAsync();
                }

                var query     = new CustomerQueries(_db);
                var customers = await query.GetAllCustomers();

                foreach (var customer in customers)
                {
                    var limit = 0;
                    int.TryParse(customer._pos_customer_accountlimit, out limit);

                    var found = await _context.Customer.FindAsync(int.Parse(customer.id.ToString()));

                    if (found == null)
                    {
                        customersCreated++;
                        var newCustomer = new Customer
                        {
                            Address      = customer._pos_customer_address,
                            City         = customer._pos_customer_city,
                            CompanyName  = customer._pos_customer_company_name,
                            Country      = customer._pos_customer_country,
                            CreditLimit  = limit,
                            CustomerCode = customer.id.ToString(),
                            CustomerId   = int.Parse(customer.id.ToString()),
                            Email        = customer._pos_customer_email,
                            FirstName    = customer._pos_customer_first_name,
                            LastName     = customer._pos_customer_last_name,
                            Mobile       = customer._pos_customer_mobile,
                            PhoneNumber  = customer._pos_customer_phone,
                            PostalCode   = customer._pos_customer_postal_code,
                            Province     = customer._pos_customer_province,
                            PstNumber    = customer._pos_customer_pst_number,
                            Status       = "",
                            UserName     = customer._pos_customer_email,
                            Website      = customer._pos_customer_contractorlink
                        };
                        await _context.Customer.AddAsync(newCustomer);

                        await _context.SaveChangesAsync();
                    }
                    else
                    {
                        customersUpdated++;
                        found.Address      = customer._pos_customer_address;
                        found.City         = customer._pos_customer_city;
                        found.CompanyName  = customer._pos_customer_company_name;
                        found.Country      = customer._pos_customer_country;
                        found.CreditLimit  = limit;
                        found.CustomerCode = customer.id.ToString();
                        // found.CustomerId = int.Parse(customer.id.ToString());
                        found.Email       = customer._pos_customer_email;
                        found.FirstName   = customer._pos_customer_first_name;
                        found.LastName    = customer._pos_customer_last_name;
                        found.Mobile      = customer._pos_customer_mobile;
                        found.PhoneNumber = customer._pos_customer_phone;
                        found.PostalCode  = customer._pos_customer_postal_code;
                        found.Province    = customer._pos_customer_province;
                        found.PstNumber   = customer._pos_customer_pst_number;
                        found.Status      = "";
                        found.UserName    = customer._pos_customer_email;
                        found.Website     = customer._pos_customer_contractorlink;
                        await _context.SaveChangesAsync();
                    }
                }
                _db.Connection.Close();
            }
            catch (Exception ex)
            {
                errorList.Add("order taxes:" + ex.ToString());
            }

            await _emailSender.SendEmailAsync("*****@*****.**", "Sync Finished: Customers", $"Sync Finished: Customers.  \n Customers Created: {customersCreated}. \n Customers Updated: {customersUpdated}. \n Errors: {string.Join(",", errorList)}");

            return(Ok(errorList));
        }
示例#29
0
 private void toolStripButtonViewAsEntityLinq_Click(object sender, EventArgs e)
 {
     bindingSourceCustomerList.DataSource = CustomerQueries.GetCustomerViewRelatedLinq();
 }
示例#30
0
 /// <summary>
 /// Handles the Click event of the toolStripButtonLinqBarf control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 private void toolStripButtonLinqBarf_Click(object sender, EventArgs e)
 {
     bindingSourceCustomerList.DataSource = CustomerQueries.GetCustomerListAnonymousLinq(MaxNumberOfItemsToReturn);
 }