示例#1
0
        /// <summary>
        /// Displays detailed information about an order.
        /// </summary>
        /// <param name="db">Store context.</param>
        /// <param name="order">Order to get information from.</param>
        /// <param name="amountCharged">Amount charged for the order.</param>
        public void DisplayDetail(StoreContext db, Order order, double?amountCharged)
        {
            var titleString = $"\nOrder placed on {order.TimeSubmitted} at {order.Location.Name} store.";

            Console.WriteLine(titleString);
            Console.Write(new string('=', titleString.Length));
            Console.Write("\n");

            var displayAlignment    = "{0,-7}{1,-9}{2,-40}";
            var itemNameDividerSize = order.OrderLineItems.Max(li => li.Product.Name.Length);

            Console.Write(displayAlignment, "Qty", "Charged", "Item");
            Console.Write("\n");
            Console.Write(displayAlignment, "---", "-------", new string('-', itemNameDividerSize));
            Console.Write("\n");

            foreach (var li in order.OrderLineItems)
            {
                Console.WriteLine(displayAlignment,
                                  li.Quantity, "$" + li.AmountCharged, li.Product.Name);
            }
            Console.Write(displayAlignment, "---", "-------", new string('-', itemNameDividerSize));
            Console.Write("\n");
            Console.WriteLine(displayAlignment, order.OrderLineItems.Sum(li => li.Quantity), "$" + amountCharged, "Total");
            CliInput.PressAnyKey();
        }
        /// <summary>
        /// Handles user input.
        /// </summary>
        public void InputLoop()
        {
            do
            {
                Console.Write("Location name: ");
                var name = Console.ReadLine();
                if (name.Trim() == "")
                {
                    this.AbortThenExit("No name provided.");
                    return;
                }

                var location = new StoreDb.Location(name);

                var added = this.ApplicationState.DbOptions.AddLocation(location);
                if (!added)
                {
                    CliPrinter.Error("A location with that name already exists.");
                    continue;
                }

                this.MenuExit();
                CliInput.PressAnyKey("Location added.");
                break;
            } while (true);
        }
        /// <summary>
        /// Handle menu input.
        /// </summary>
        public void InputLoop()
        {
            Console.WriteLine("Select store for orders:");

            var numLocations = 0;
            IEnumerable <Guid> locationIds = null;

            using (var db = new StoreContext(this.ApplicationState.DbOptions))
            {
                var locations     = db.GetLocations();
                var locationsIter = Enumerable.Range(1, locations.Count()).Zip(locations);
                foreach (var location in locationsIter)
                {
                    Console.WriteLine($"  {location.First}. {location.Second.Name}");
                }
                numLocations = locationsIter.Count();
                locationIds  = locationsIter.Select(i => i.Second.LocationId).ToList();
            }

            bool validator(int num)
            {
                if (num > 0 && num <= numLocations)
                {
                    return(true);
                }
                else
                {
                    CliPrinter.Error($"Please enter a store number between 1 and {numLocations}");
                    return(false);
                }
            }

            var locationSelected = CliInput.GetInt(0, validator, "Enter store number:");

            var customerId = this.ApplicationState.UserData.CustomerId;
            var locationId = locationIds.ElementAt(locationSelected - 1 ?? 0);

            if (this.ApplicationState.DbOptions.SetDefaultLocation(customerId, locationId))
            {
                CliInput.PressAnyKey("Store set.");
                this.ApplicationState.UserData.OperatingLocationId = locationId;
                this.ApplicationState.UserData.RefreshDefaultLocation();
                this.MenuExit();
                return;
            }
            else
            {
                CliInput.PressAnyKey("An error occurred while setting the store. Please try again.");
            }
        }
示例#4
0
        /// <summary>
        /// Handle input.
        /// </summary>
        public void InputLoop()
        {
            do
            {
                PrintMenu();
                using (var db = new StoreContext(this.ApplicationState.DbOptions))
                {
                    var location = db.GetLocationById(this.ApplicationState.UserData.OperatingLocationId);
                    var order    = db.FindCurrentOrder(location, this.ApplicationState.UserData.CustomerId);
                    if (order == null)
                    {
                        CliPrinter.Error("There was an error retrieving your order. Please try again.");
                        break;
                    }

                    bool itemNumberValidator(int num)
                    {
                        if (num > 0 && num <= this.InventoryIds.Count)
                        {
                            return(true);
                        }
                        else
                        {
                            CliPrinter.Error($"Please enter an inventory number between 1 and {this.InventoryIds.Count}");
                            return(false);
                        }
                    }

                    var itemIndex = CliInput.GetInt(CliInput.GetIntOptions.AllowEmpty, itemNumberValidator, "Inventory number: ") ?? 0;
                    if (itemIndex == 0)
                    {
                        break;
                    }

                    var inventoryId = this.InventoryIds[itemIndex - 1];
                    var product     = db.GetProductFromInventoryId(inventoryId);

                    var projectedQuantity = db.ProjectStockBasedOnOrder(order, product);

                    if (projectedQuantity <= 0)
                    {
                        CliInput.PressAnyKey("That item is out of stock");
                        continue;
                    }

                    var orderQuantity = CliInput.GetInt(CliInput.GetIntOptions.AllowEmpty,
                                                        v => v > 0 && v <= projectedQuantity,
                                                        $"Quantity [1..{projectedQuantity}]: ") ?? 0;
                    if (orderQuantity == 0)
                    {
                        continue;
                    }

                    db.AddLineItem(order, product, orderQuantity);
                    db.SaveChanges();

                    CliInput.PressAnyKey("\nAdded to order.");
                }
            } while (true);
            this.MenuExit();
        }
        /// <summary>
        /// Handle menu input.
        /// </summary>
        public void InputLoop()
        {
            if (this.ApplicationState.UserData.CurrentOrderId == null)
            {
                this.AbortThenExit("No current order on file.");
                return;
            }

            var orderTotalCost = 0.0;

            using (var db = new StoreContext(this.ApplicationState.DbOptions))
            {
                var order = db.GetOrderById(this.ApplicationState.UserData.CurrentOrderId);
                if (order.OrderLineItems.Count == 0)
                {
                    CliInput.PressAnyKey("There are no items in your order.");
                    this.MenuExit();
                    return;
                }
                Console.WriteLine("Qty\tEach\tTotal\tName");
                Console.WriteLine("===\t=====\t=====\t====");


                var totalItems = 0;
                foreach (var o in order.OrderLineItems)
                {
                    var lineItemTotalCost = o.Product.Price * o.Quantity;
                    orderTotalCost += lineItemTotalCost;
                    totalItems     += o.Quantity;
                    Console.WriteLine($"{o.Quantity}\t${o.Product.Price}\t${lineItemTotalCost}\t{o.Product.Name}");
                }
                Console.Write("---\t-----\t-----\t--------------------------\n");
                Console.Write($"{totalItems}\t\t${orderTotalCost}\n\n");
            }
            Console.WriteLine("1.  Place Order");
            Console.WriteLine("2.  Exit");

            ConsoleKeyInfo cki;

            do
            {
                cki = Console.ReadKey(true);
                if (cki.Key == ConsoleKey.D1)
                {
                    Console.WriteLine("Placing order...");

                    var orderId = this.ApplicationState.UserData.CurrentOrderId;
                    try
                    {
                        var orderResult = this.ApplicationState.DbOptions.PlaceOrder(orderId, StoreDbUtil.Config.MAX_ORDER_QUANTITY);
                        switch (orderResult)
                        {
                        case PlaceOrderResult.Ok:
                            this.AbortThenExit("Order placed successfully.");
                            return;

                        case PlaceOrderResult.OutOfStock:
                            this.AbortThenExit("Unable to place order: Some items are out of stock.");
                            return;

                        case PlaceOrderResult.NoLineItems:
                            this.AbortThenExit("Unable to place order: There are no items in the order.");
                            return;

                        case PlaceOrderResult.OrderNotFound:
                            this.AbortThenExit("Unable to place order: Unable to locate the order.");
                            return;

                        case PlaceOrderResult.HighQuantityRejection:
                            this.AbortThenExit($"Unable to place order: Item quantities too high ({StoreDbUtil.Config.MAX_ORDER_QUANTITY} max)");
                            return;
                        }
                    } catch (NullReferenceException) {
                        this.AbortThenExit("Unable to place order: Order id is missing (this is a bug).");
                        return;
                    }
                }
                else if (cki.Key == ConsoleKey.D2 || cki.Key == ConsoleKey.Enter)
                {
                    this.MenuExit();
                    return;
                }
            } while (true);
        }
        /// <summary>
        /// Handle input.
        /// </summary>
        public void InputLoop()
        {
            do
            {
                this.PrintMenu();
                if (this.ApplicationState.UserData.CurrentOrderId == null)
                {
                    CliInput.PressAnyKey("There is currently no open order.");
                    break;
                }
                using (var db = new StoreContext(this.ApplicationState.DbOptions))
                {
                    var order = db.GetOrderById(this.ApplicationState.UserData.CurrentOrderId);
                    if (order == null)
                    {
                        break;
                    }
                    if (order.OrderLineItems.Count() == 0)
                    {
                        CliInput.PressAnyKey("There are no items in your order.");
                        break;
                    }
                }

                var getLineOptions = CliInput.GetLineOptions.AcceptEmpty | CliInput.GetLineOptions.TrimSpaces;
                var option         = CliInput.GetLine(getLineOptions, v => true, "[D]elete / Change [Q]uantity: ");
                switch (option)
                {
                case null:
                case "":
                    this.MenuExit();
                    return;

                case "D":
                case "d":
                {
                    var itemNumber = CliInput.GetInt(CliInput.GetIntOptions.AllowEmpty, n => n > 0 && n <= this.LineItemIds.Count, "Select item number:");
                    if (itemNumber == null)
                    {
                        continue;
                    }

                    using (var db = new StoreContext(this.ApplicationState.DbOptions))
                    {
                        var deleted = db.DeleteLineItem(this.LineItemIds[(int)itemNumber - 1]);
                        if (!deleted)
                        {
                            CliInput.PressAnyKey("There was a problem deleting that line item. Please try again.");
                        }
                    }
                    break;
                }

                case "Q":
                case "q":
                {
                    var itemNumber = CliInput.GetInt(CliInput.GetIntOptions.AllowEmpty, n => n > 0 && n <= this.LineItemIds.Count, "Select item number:");
                    if (itemNumber == null)
                    {
                        continue;
                    }

                    using (var db = new StoreContext(this.ApplicationState.DbOptions))
                    {
                        var order = db.GetOrderById(this.ApplicationState.UserData.CurrentOrderId);

                        var lineItemId = this.LineItemIds[(int)itemNumber - 1];
                        var lineItem   = order.OrderLineItems.Where(li => li.OrderLineItemId == lineItemId);

                        var product = lineItem.First().Product;


                        var maxOrder = db.LocationInventories
                                       .Where(i => i.Location.LocationId == order.Location.LocationId)
                                       .Where(i => i.Product.ProductId == product.ProductId)
                                       .Select(i => i.Quantity).FirstOrDefault();

                        var newQuantity = CliInput.GetInt(CliInput.GetIntOptions.AllowEmpty,
                                                          q => q >= 0 && q <= maxOrder,
                                                          $"New quantity [{maxOrder} max]:");

                        if (newQuantity == null)
                        {
                            continue;
                        }

                        var adjusted = db.SetLineItemQuantity(this.LineItemIds[(int)itemNumber - 1], (int)newQuantity);
                        if (!adjusted)
                        {
                            CliInput.PressAnyKey("There was a problem adjusting the quantity for that line item. Please try again.");
                        }
                    }
                    break;
                }
                }
            } while (true);
            this.MenuExit();
        }
        /// <summary>
        /// Handle user input.
        /// </summary>
        public void InputLoop()
        {
            string EmailLoop(DbContextOptions <StoreContext> dbOptions)
            {
                var    cliOptions = CliInput.GetLineOptions.TrimSpaces | CliInput.GetLineOptions.AcceptEmpty;
                string login      = "";

                do
                {
                    login = CliInput.GetLine(cliOptions, CliInput.EmailValidator, "Email Address:");

                    if (login == "" || login == null)
                    {
                        return(null);
                    }

                    if (dbOptions.LoginExists(login))
                    {
                        CliPrinter.Error("That email address is already in use.");
                    }
                    else
                    {
                        break;
                    }
                } while (true);
                return(login);
            }

            do
            {
                var cliOptions = CliInput.GetLineOptions.TrimSpaces | CliInput.GetLineOptions.AcceptEmpty;

                var firstName = CliInput.GetLine(cliOptions, Customer.ValidateName, "First Name:");

                if (firstName == "" || firstName == null)
                {
                    this.AbortThenExit("Empty entry - exiting.");
                    return;
                }

                var lastName = CliInput.GetLine(cliOptions, Customer.ValidateName, "Last Name:");
                if (lastName == "" || lastName == null)
                {
                    this.AbortThenExit("Empty entry - exiting.");
                    return;
                }
                var login = EmailLoop(this.ApplicationState.DbOptions);
                if (login == "" || login == null)
                {
                    this.AbortThenExit("Empty entry - exiting.");
                    return;
                }

                var password = CliInput.GetPassword("Password:"******"")
                {
                    this.AbortThenExit("Empty entry - exiting.");
                    return;
                }
                var customer = new Customer();
                // Data pre-validated above.
                customer.FirstName = firstName;
                customer.LastName  = lastName;
                customer.Login     = login;
                customer.Password  = password;

                var createResult = this.ApplicationState.DbOptions.CreateUserAccount(customer);

                if (createResult == CreateUserAccountResult.Ok)
                {
                    this.ApplicationState.UserData.CustomerId = customer.CustomerId;
                    this.MenuExit();
                    this.MenuAdd(new StoreCliMenuUser.Main(this.ApplicationState));
                    CliInput.PressAnyKey("\nAccount created.");
                    break;
                }
                else
                {
                    CliPrinter.Error("An error occurred while creating your account. Please try again.");
                }
            } while (true);
        }
示例#8
0
        /// <summary>
        /// Print this menu.
        /// </summary>
        public void PrintMenu()
        {
            Console.Clear();
            CliPrinter.Title("Order History");
            switch (this.CurrentOperatingMode)
            {
            case OperatingMode.SelectLocation:
                using (var db = new StoreContext(this.ApplicationState.DbOptions))
                {
                    var locations = db.GetLocations();
                    this.LocationIds.Clear();
                    var i = 1;
                    foreach (var location in locations)
                    {
                        this.LocationIds.Add(location.LocationId);
                        Console.WriteLine($"{i}.  {location.Name}");
                        i += 1;
                    }
                    Console.WriteLine("\n");
                }
                break;

            case OperatingMode.ViewOrders:
                using (var db = new StoreContext(this.ApplicationState.DbOptions))
                {
                    var location = db.GetLocationById(this.SelectedLocation);
                    if (location == null)
                    {
                        break;
                    }

                    var orders = db
                                 .GetOrderHistory(location)
                                 .Select(o => new {
                        OrderId       = o.OrderId,
                        Customer      = o.Customer,
                        Location      = o.Location,
                        TimeCreated   = o.TimeCreated,
                        TimeSubmitted = o.TimeSubmitted,
                        TimeFulfilled = o.TimeFulfilled,
                        AmountPaid    = o.AmountPaid,
                        OrderLineItem = o.OrderLineItems,
                        AmountCharged = db.GetAmountCharged(o),
                    }).ToList();

                    if (orders.Count() == 0)
                    {
                        CliPrinter.Error("There are no orders for this location.");
                        this.CurrentOperatingMode = OperatingMode.SelectLocation;
                        CliInput.PressAnyKey();
                        this.PrintMenu();
                        return;
                    }

                    var upArrow   = '↑';
                    var downArrow = '↓';

                    var priceSortSymbol = '-';
                    var dateSortSymbol  = '-';

                    switch (this.SortKey)
                    {
                    case OrderSortKey.DateDesc:
                        orders         = orders.OrderByDescending(o => o.TimeSubmitted).ToList();
                        dateSortSymbol = downArrow;
                        break;

                    case OrderSortKey.DateAsc:
                        orders         = orders.OrderBy(o => o.TimeSubmitted).ToList();
                        dateSortSymbol = upArrow;
                        break;

                    case OrderSortKey.PriceDesc:
                        orders          = orders.OrderByDescending(o => o.AmountCharged).ToList();
                        priceSortSymbol = downArrow;
                        break;

                    case OrderSortKey.PriceAsc:
                        orders          = orders.OrderBy(o => o.AmountCharged).ToList();
                        priceSortSymbol = upArrow;
                        break;
                    }
                    var historyDisplayAlignment = "{0,-6}{1,-9}{2,-25}";
                    var priceSortLine           = $"{priceSortSymbol}----";
                    var dateSortLine            = $"{dateSortSymbol}---";

                    Console.WriteLine(historyDisplayAlignment, "Num", "Price", "Date");
                    Console.WriteLine(historyDisplayAlignment, "---", priceSortLine, dateSortLine);
                    var i = 1;
                    this.OrderIds.Clear();
                    foreach (var order in orders)
                    {
                        this.OrderIds.Add(order.OrderId);
                        Console.WriteLine(historyDisplayAlignment,
                                          i + ".", "$" + order.AmountCharged, order.TimeSubmitted, order.Location.Name);
                        i += 1;
                    }
                }
                break;

            default:
                break;
            }
        }