Exemple #1
0
        public static float GetQtyOnHandByID(Session session, int?itemID, int locationID, string lot = null, int?LPNNumber = null)
        {
            if (itemID.HasValue == false)
            {
                return(0);
            }

            if (!(LPNNumber == null))
            {
                return(GetQtyOnHandByIDAndLot(session, itemID, locationID, lot, LPNNumber));
            }

            //If locationID.HasValue = False Then
            //    locationID = UsersBLL.GetUsersLocalLocation(My.Settings.UserName).Oid
            //End If

            try
            {
                if (locationID == 0)
                {
                    return(Convert.ToSingle(session.Evaluate <LocationInventory>(new AggregateOperand("", LocationInventory.Fields.QuantityOnHand.PropertyName, Aggregate.Sum), new BinaryOperator(LocationInventory.Fields.LocationInventoryItem.ItemID, itemID.Value, BinaryOperatorType.Equal))));
                }
                else
                {
                    LocationInventory quantity = session.FindObject <LocationInventory>(new GroupOperator(new BinaryOperator(LocationInventory.Fields.LocationInventoryItem.ItemID, itemID.Value, BinaryOperatorType.Equal) & new BinaryOperator(LocationInventory.Fields.Location.Oid.PropertyName, locationID, BinaryOperatorType.Equal)));
                    //Dim item As Items = Session.DefaultSession.GetObjectByKey(Of Items)(itemID, True)
                    //Return item.s ngQuantityOnHand
                    return(quantity.QuantityOnHand);
                }
            }
            catch (Exception ex)
            {
                return(0);
            }
        }
        public async Task <IActionResult> Edit(int id, [Bind("LocationId,LocationName,Dough,Pepperoni,Sausage,Bacon,Mushrooms,Olives,Anchovies,Salami,Chicken,Onions,Peppers")] LocationInventory locationInventory)
        {
            if (id != locationInventory.LocationId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(locationInventory);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!LocationInventoryExists(locationInventory.LocationId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(locationInventory));
        }
Exemple #3
0
        public async Task <IActionResult> AddCartItem(int?quantity, string productName, string locationName)
        {
            // Get the user who's azdding the item to the cart
            var           userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            VendorAppUser user   = await userManager.GetUserAsync(User);

            LocationInventory targetLocationInventory = await cartRepo.GetLocationInventoryByProductAndLocationName(locationName, productName);

            // Redirect user back to product page if any of the paramerters aren't valid
            if (quantity == null || productName == null || locationName == null || targetLocationInventory == null)
            {
                TempData["ErrorMessage"] = "Please enter valid input";
                return(Redirect(Request.Headers["Referer"]));
            }

            if (quantity > targetLocationInventory.Quanitity || quantity <= 0)
            {
                TempData["ErrorMessage"] = "Please enter a valid quantity";
                return(Redirect(Request.Headers["Referer"]));
            }

            // Add item to cart
            await cartRepo.AddItemToCart(userId, productName, locationName, quantity ?? -1);

            // Document changes
            TempData["FlashMessage"] = "Added to cart";
            cartLogger.LogInformation($"{productName} was added to {user.UserName}'s cart");

            // Take client back to list of products

            return(RedirectToAction("Index", "Product"));
        }
        // TODO: add docs
        public async Task <CartItem> RemoveItemFromCart(int cartId)
        {
            // Find the cart item with it's cart and the cart's user
            CartItem cartItemToRemove = await context.CartItems
                                        .Include(cI => cI.Cart)
                                        .ThenInclude(c => c.User)
                                        .FirstOrDefaultAsync(cI => cI.ID == cartId);

            // Retreive location to restock it's inventory upon deletion
            LocationInventory locationInventoryToRestock =
                await context.LocationInventoryRecords
                .FirstOrDefaultAsync(lIR =>
                                     lIR.Product.Name == cartItemToRemove.ProductName &&
                                     lIR.Location.Name == cartItemToRemove.LocationName);

            // Restock the inventory and update user's number of cart items
            locationInventoryToRestock.Quanitity += cartItemToRemove.AmountPurchased;
            cartItemToRemove.Cart.User.NumCartItems--;

            // Remove cart item
            context.CartItems.Remove(cartItemToRemove);

            // Save changes
            await context.SaveChangesAsync();

            return(cartItemToRemove);
        }
        // Now we can

        // TODO: Add/Update

        // TODO: Restock Inventory

        // TODO: Remove inventory
        /// <summary>
        /// Updates the locations inventory to decrease the quantity of a specified product
        /// </summary>
        /// <param name="amountToRemove">The amount to remove from the inventory</param>
        /// <param name="locationName">Name of the location</param>
        /// <param name="productName">Name of the product</param>
        /// <returns>The updated location inventory with it's know quantity</returns>
        public async Task <LocationInventory> RemoveInventory(int amountToRemove, string locationName, string productName)
        {
            LocationInventory locationInventoryToUpdate =
                await context.LocationInventoryRecords
                .FirstOrDefaultAsync(pI => pI.Product.Name == productName && pI.Location.Name == locationName);

            // Check if recor exists
            if (locationInventoryToUpdate == null)
            {
                return(null);
            }

            // check if location has the amount before we remove
            // TODO: throw an exception instead
            if (locationInventoryToUpdate.Quanitity - amountToRemove < 0)
            {
                return(null);
            }

            // update DB
            locationInventoryToUpdate.Quanitity -= amountToRemove;
            await context.SaveChangesAsync();

            return(locationInventoryToUpdate);
        }
        // TODO: add docs
        public async Task <LocationInventory> AddLocationInventory(LocationInventory locationInventory)
        {
            context.LocationInventoryRecords.Add(locationInventory);
            await context.SaveChangesAsync();

            return(locationInventory);
        }
        public List <LocationInventoryViewModel> AddToCart(List <LocationInventoryViewModel> livmList, LocationInventoryViewModel livm, CustomUser user)
        {
            var           iloc = livm.Location.LocationId;
            var           uloc = user.DefaultStore;
            CartInventory cInv = _repo.cartInventories.FirstOrDefault(x => x.CartId == user.CartId && x.ProductId == livm.ProductId);

            if (cInv == null)
            {
                cInv = new CartInventory
                {
                    CartId    = user.CartId,
                    ProductId = livm.ProductId
                };
                _repo.cartInventories.Add(cInv);
            }
            LocationInventory lInv = _repo.locationInventories.FirstOrDefault(z => z.LocationId == livm.Location.LocationId && z.ProductId == livm.ProductId);

            if (cInv != null && lInv.Quantity >= livm.purchaseQuantity)
            {
                cInv.CartQuantity    += livm.purchaseQuantity;
                lInv.Quantity        -= livm.purchaseQuantity;
                livm.Quantity        -= livm.purchaseQuantity;
                livm.purchaseQuantity = 0;
                _repo.CommitSave();
            }
            var l = livmList.FirstOrDefault(x => x.ProductId == livm.ProductId);

            l = livm;
            return(livmList);
        }
Exemple #8
0
        public static void UpdateStock(Session session, int ItemID, int LocationID, float Quantity, string lot = "", int?LPNNumber = null, DateTime?ExpirationDate = null, bool newInventory = true)
        {
            if (newInventory)
            {
                LocationInventory inventory = session.FindObject <LocationInventory>(new BinaryOperator(LocationInventory.Fields.LocationInventoryItem.ItemID.PropertyName, ItemID, BinaryOperatorType.Equal) & new BinaryOperator(LocationInventory.Fields.Location.Oid.PropertyName, LocationID, BinaryOperatorType.Equal));

                if (inventory == null)
                {
                    inventory = new LocationInventory(session);
                    inventory.LocationInventoryItem = session.GetObjectByKey <Items>(ItemID);
                    inventory.Location       = session.GetObjectByKey <Locations>(LocationID);
                    inventory.QuantityOnHand = Quantity;
                }
                else
                {
                    inventory.QuantityOnHand += Quantity;
                }

                inventory.Save();
            }


            if (((lot == null) || string.IsNullOrEmpty(lot)) && ((LPNNumber == null) || LPNNumber == 0))
            {
                return;
            }

            LocationInventoryByLot inventoryByLot = session.FindObject <LocationInventoryByLot>(new BinaryOperator(LocationInventoryByLot.Fields.LocationInventoryItem.ItemID.PropertyName, ItemID, BinaryOperatorType.Equal) & new BinaryOperator(LocationInventoryByLot.Fields.Location.Oid.PropertyName, LocationID, BinaryOperatorType.Equal) & new BinaryOperator(LocationInventoryByLot.Fields.LocationInventoryLot, lot, BinaryOperatorType.Equal) & new BinaryOperator(LocationInventoryByLot.Fields.LPNNumber, (LPNNumber ?? 0), BinaryOperatorType.Equal));

            if (inventoryByLot == null)
            {
                if (Quantity >= 0)
                {
                    inventoryByLot = new LocationInventoryByLot(session);
                    inventoryByLot.LocationInventoryItem = session.GetObjectByKey <Items>(ItemID);
                    inventoryByLot.Location             = session.GetObjectByKey <Locations>(LocationID);
                    inventoryByLot.LocationInventoryLot = lot;
                    inventoryByLot.LPNNumber            = LPNNumber;
                    inventoryByLot.QuantityOnHand       = Quantity;
                    if (ExpirationDate != null)
                    {
                        inventoryByLot.ExpirationDate = ExpirationDate;
                    }
                }
                else
                {
                    return;
                }
            }
            else
            {
                inventoryByLot.QuantityOnHand += Quantity;
            }

            inventoryByLot.Save();
        }
        public async Task <IActionResult> Create([Bind("LocationId,LocationName,Dough,Pepperoni,Sausage,Bacon,Mushrooms,Olives,Anchovies,Salami,Chicken,Onions,Peppers")] LocationInventory locationInventory)
        {
            if (ModelState.IsValid)
            {
                _context.Add(locationInventory);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(locationInventory));
        }
Exemple #10
0
        public IActionResult LocationInventory(int id)
        {
            var inventory    = Repo.GetInventoryByLocationID(id);
            var items        = Repo.GetAllItem();
            var locInventory = new LocationInventory
            {
                InventoryList = (List <Inventory>)inventory,
                ItemInventory = (List <Item>)items
            };

            return(View(locInventory));
        }
        /// <summary>
        ///  Adds an item to a user's cart.  Creates a cart record if one hasn't been added for the
        /// user. Returns null if the item was not sucessfully added to the cart.
        /// </summary>
        /// <param name="userId">Id of the user of the cart</param>
        /// <param name="productName">Name of the product being added</param>
        /// <param name="quantity">The amount of the product being added</param>
        /// <returns></returns>
        public async Task <Cart> AddItemToCart(string userId, string productName, string locationName, int quantity)
        {
            // Get instance of user from id
            EFCoreUserRepository userRepo = new EFCoreUserRepository(context);
            VendorAppUser        user     = await userRepo.Get(userId);

            Cart userCart;

            // If user doesn't exist stop process and return null
            if (user == null)
            {
                return(null);
            }

            // Check if user already has cart for us to use
            // If user has no cart, create one for them
            userCart = await FindCartByUserId(userId);

            if (userCart == null)
            {
                // userCart = new Cart
                // {
                //   User = user
                // };
                user.Cart = new Cart();
            }

            // add item to cart
            CartItem newItem = new CartItem
            {
                Cart            = user.Cart,
                ProductName     = productName,
                LocationName    = locationName,
                AmountPurchased = quantity
            };

            context.CartItems.Add(newItem);

            // Update the location inventory and the amount of cart items a user has
            LocationInventory updateLocatInventory =
                await new EFCoreLocationRepository(context)
                .RemoveInventory(newItem.AmountPurchased, newItem.LocationName, newItem.ProductName);

            // TODO: Update location inventory without using repo
            user.NumCartItems++;

            // save changes
            context.SaveChanges();


            return(userCart);
        }
        public LocationInventoryViewModel CreateLocationInventoryViewModel(LocationInventory locationInventory, Location location, Product product)
        {
            LocationInventoryViewModel livm = new LocationInventoryViewModel()
            {
                Location    = location,
                ProductId   = product.ProductId,
                Description = product.Description,
                Price       = product.Price,
                Quantity    = locationInventory.Quantity,
            };

            return(livm);
        }
        private (Customer, Location, Product, LocationInventory) SimplePopulate(StoreContext db)
        {
            var customer  = new Customer(Guid.NewGuid().ToString());
            var location  = new Location(Guid.NewGuid().ToString());
            var product   = new Product(Guid.NewGuid().ToString(), 1.0);
            var inventory = new LocationInventory(product, location, 10);

            db.Add(customer);
            db.Add(location);
            db.Add(product);
            db.Add(inventory);

            return(customer, location, product, inventory);
        }
        public async void ItShouldFindTheInventoryByLocationAndProductname()
        {
            //Given
            EFCoreLocationRepository locationRepo = new EFCoreLocationRepository(ctx);

            //When
            await locationRepo.AddLocationInventory(mockLocationInventory);

            //Then
            LocationInventory actualLocationInventory =
                await locationRepo.GetLocationInventoryByProductAndLocationName(mockLocation.Name, mockProduct.Name);

            Assert.Equal(1, actualLocationInventory.Quanitity);
        }
        public async void ItShouldRemoveLocationInventoryRecord()
        {
            //Given
            EFCoreLocationRepository locationRepo = new EFCoreLocationRepository(ctx);

            //When
            LocationInventory tempLocationInventory = await locationRepo.AddLocationInventory(mockLocationInventory);

            await locationRepo.RemoveLocationInventoryRecord(tempLocationInventory.ID);

            //Then

            Assert.Empty(await locationRepo.GetAllLocationInventoryRecords());
        }
        public async void ItShouldRestockInventory()
        {
            //Given
            EFCoreLocationRepository locationRepo = new EFCoreLocationRepository(ctx);
            //When
            await locationRepo.AddLocationInventory(mockLocationInventory);

            await locationRepo.RemoveInventory(-1, mockLocation.Name, mockProduct.Name);

            //Then
            LocationInventory actualLocationInventory =
                await locationRepo.GetLocationInventoryByProductAndLocationName(mockLocation.Name, mockProduct.Name);

            Assert.Equal(2, actualLocationInventory.Quanitity);
        }
        public static void InventoryRecall()
        {
            string path = Path.Combine(Environment.CurrentDirectory, "locationInventory.xml");
            Task <IEnumerable <SerializeInventory> > deserializeFile = Serializer.DeserializeInventoryFromFile(path);
            IEnumerable <SerializeInventory>         inventory       = new List <SerializeInventory>();

            try
            {
                inventory = deserializeFile.Result;
            }
            catch (AggregateException)
            {
                Console.WriteLine("Location Inventory File was not found.");
            }
            LocationInventory.AddRange(inventory);
        }
        public async Task <LocationInventory> RemoveLocationInventoryRecord(int id)
        {
            LocationInventory locationInventory = await context.LocationInventoryRecords.FindAsync(id);

            if (locationInventory == null)
            {
                // TODO: Log that no Entity was found to delete here or in Repo
                return(locationInventory);
            }

            context.LocationInventoryRecords.Remove(locationInventory);

            await context.SaveChangesAsync();

            return(locationInventory);
        }
Exemple #19
0
        private static void DeleteInventoryConsumption(Inventory productionRecord, Session inventorySession)
        {
            BomConsumption    consumption     = null;
            LocationInventory inventoryOnHand = null;

            using (XPCollection <BomConsumption> consumptions = productionRecord.InventoryConsumption)
            {
                for (int i = consumptions.Count - 1; i >= 0; i--)
                {
                    consumption     = consumptions[i];
                    inventoryOnHand = inventorySession.FindObject <LocationInventory>(new BinaryOperator(LocationInventory.Fields.LocationInventoryItem.ItemID.PropertyName, consumption.RawMatID.ItemID, BinaryOperatorType.Equal) & new BinaryOperator(LocationInventory.Fields.Location.Oid, UsersBLL.GetUsersLocalLocation(inventorySession, Properties.Settings.Default.UserName).Oid, BinaryOperatorType.Equal));
                    inventoryOnHand.QuantityOnHand += (float)(consumption.QuantityUsed + consumption.ScrapFactorUsed);
                    inventoryOnHand.Save();
                    consumption.Delete();
                }
            }
        }
        public LogicTest()
        {
            var opts = new DbContextOptionsBuilder <P1ProtoDBContext>()
                       .UseSqlite("Filename=Test.db")
                       .Options;

            mockUser = new VendorAppUser
            {
                UserName = "******"
            };

            mockLocation = new Location
            {
                Name = "location"
            };

            mockProduct = new Product
            {
                Name     = "product",
                Catagory = "catagory",
                FAClass  = "icon"
            };

            mockLocationInventory = new LocationInventory
            {
                Product   = mockProduct,
                Location  = mockLocation,
                Quanitity = 1
            };

            mockOrder = new Order();

            mockOrderItem = new OrderItem
            {
                ProductName     = "product",
                LocationName    = "location",
                AmountPurchased = 1
            };

            ctx = new P1ProtoDBContext(opts);

            Seed();
        }
        //
        // Update Methods
        //

        /// <summary>
        /// Update the amount of some product that a particular location has in stock
        /// </summary>
        /// <param name="location">Business-Model location object</param>
        /// <param name="product">Business-Model product object</param>
        /// <param name="qty">integer number of items to add</param>
        public void UpdateLocationStock(Library.Models.Location location, Library.Models.Product product)
        {
            LocationInventory dbLocationInventory;

            try {
                dbLocationInventory       = _dbContext.LocationInventories.First(x => x.LocationId == location.Id && x.ProductId == product.Id);
                dbLocationInventory.Stock = location.Stock[product];
            } catch (InvalidOperationException) {
                var dbLocation = _dbContext.Locations.First(l => l.Id == location.Id);
                var dbProduct  = _dbContext.Products.First(p => p.Id == product.Id);
                dbLocationInventory = new LocationInventory()
                {
                    Location = dbLocation,
                    Product  = dbProduct,
                    Stock    = location.Stock[product],
                    Price    = location.Prices[product]
                };
                _dbContext.LocationInventories.Add(dbLocationInventory);
            }
        }
        //
        // Update Methods
        //

        /// <summary>
        /// Update the amount of some product that a particular location has in stock
        /// </summary>
        /// <param name="location">Business-Model location object</param>
        /// <param name="product">Business-Model product object</param>
        /// <param name="qty">integer number of items to add</param>
        public void UpdateLocationStock(Library.Models.Location location)
        {
            if (location is null)
            {
                throw new ArgumentNullException(nameof(location));
            }
            foreach (var product in location.Stock)
            {
                int productId = product.Key;
                LocationInventory dbLocationInventory;
                try {
                    dbLocationInventory       = _dbContext.LocationInventories.First(x => x.LocationId == location.Id && x.ProductId == productId);
                    dbLocationInventory.Stock = location.Stock[productId];
                } catch (InvalidOperationException) {
                    var dbLocation = _dbContext.Locations.FirstOrDefault(l => l.Id == location.Id);

                    if (dbLocation is null)
                    {
                        throw new InvalidOperationException("Tried to update stock of a nonexistent location.");
                    }

                    var dbProduct = _dbContext.Products.FirstOrDefault(p => p.Id == productId);

                    if (dbProduct is null)
                    {
                        throw new InvalidOperationException("Tried to update stock of a nonexistent product.");
                    }

                    dbLocationInventory = new LocationInventory()
                    {
                        Location = dbLocation,
                        Product  = dbProduct,
                        Stock    = location.Stock[productId],
                        Price    = location.Prices[productId]
                    };
                    _dbContext.LocationInventories.Add(dbLocationInventory);
                }
            }
        }
Exemple #23
0
        public DiscordEmbed GetLocationEmbed(
            List <string> foundHiddenLocations = null,
            string entranceId = null,
            int exploreCount  = -1)
        {
            var builder = new DiscordEmbedBuilder()
                          .WithTitle(DisplayName);

            var desc = new System.Text.StringBuilder(Description);

            // Hostility Colors
            switch (SafetyRating.ToLower())
            {
            case "sanctuary": builder.WithColor(DiscordColor.Gold); break;

            case "friendly": builder.WithColor(DiscordColor.SpringGreen); break;

            case "neutral": builder.WithColor(DiscordColor.CornflowerBlue); break;

            case "caution": builder.WithColor(DiscordColor.Orange); break;

            case "dangerous": builder.WithColor(DiscordColor.IndianRed); break;

            case "hostile": builder.WithColor(DiscordColor.Red); break;

            default: builder.WithColor(DiscordColor.White); break;
            }

            // Buildings
            if (Buildings?.Count > 0)
            {
                builder.AddField("Buildings", string.Join(", ", Buildings.Select(b => b.Name)));
            }

            // Exits
            var exits = new List <string>();

            if (LocationConnections.Keys.Count > 0)
            {
                // Always show all exits for the starting location
                if (exploreCount >= ExploresNeeded || Id == Realm.GetSetting <string>("startinglocation"))
                {
                    exits.AddRange(LocationConnections.Keys);
                }
                else
                {
                    exits.Add(LocationConnections.FirstOrDefault(l => l.Value.Equals(entranceId, System.StringComparison.OrdinalIgnoreCase)).Key);
                }
            }

            // Include hidden exits (if found)
            if (HiddenLocationConnections.Keys.Count > 0 && foundHiddenLocations != null)
            {
                var toInclude = HiddenLocationConnections
                                .Where(l => foundHiddenLocations.Contains(l.Value))
                                .Select(l => l.Key);
                exits.AddRange(toInclude);
            }

            builder.AddField("Exits", string.Join(", ", exits));

            // Location Inventory
            if (LocationInventory?.Count > 0)
            {
                var items = LocationInventory.Select(inv => $"{inv.DisplayName} (x{inv.Amount})");
                builder.AddField("Items", string.Join(", ", items));
            }

            builder.WithDescription(desc.ToString());

            return(builder.Build());
        }
        public void PlacesOrderWithMultipleLineItems()
        {
            var options = TestUtil.GetMemDbOptions("PlacesOrderWithMultipleLineItems");

            Guid product1Id, product2Id;
            Guid customerId;
            Guid orderId;

            using (var db = new StoreContext(options))
            {
                var customer = new Customer(Guid.NewGuid().ToString());
                var location = new Location(Guid.NewGuid().ToString());
                db.Add(customer);
                db.Add(location);
                customerId = customer.CustomerId;

                var product1   = new Product(Guid.NewGuid().ToString(), 1.0);
                var inventory1 = new LocationInventory(product1, location, 10);
                db.Add(product1);
                db.Add(inventory1);
                product1Id = product1.ProductId;

                var product2   = new Product(Guid.NewGuid().ToString(), 1.0);
                var inventory2 = new LocationInventory(product2, location, 20);
                db.Add(product2);
                db.Add(inventory2);
                product2Id = product2.ProductId;

                var order = new Order(customer, location);
                orderId = order.OrderId;
                var orderLine1 = new OrderLineItem(order, product1);
                orderLine1.Quantity = 5;
                var orderLine2 = new OrderLineItem(order, product2);
                orderLine2.Quantity = 7;
                order.OrderLineItems.Add(orderLine1);
                order.OrderLineItems.Add(orderLine2);

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

            using (var db = new StoreContext(options))
            {
                var customer = (from c in db.Customers where c.CustomerId == customerId select c).First();

                var order =
                    (from o in db.Orders
                     where o.Customer.CustomerId == customer.CustomerId
                     select o).First();

                Assert.Equal(2, order.OrderLineItems.Count());
            }

            Assert.Equal(PlaceOrderResult.Ok, options.PlaceOrder(orderId, StoreDbUtil.Config.MAX_ORDER_QUANTITY));

            using (var db = new StoreContext(options))
            {
                var invProduct1 =
                    (from i in db.LocationInventories where i.Product.ProductId == product1Id select i).First();
                Assert.Equal(5, invProduct1.Quantity);

                var invProduct2 =
                    (from i in db.LocationInventories where i.Product.ProductId == product2Id select i).First();
                Assert.Equal(13, invProduct2.Quantity);
            }
        }
        public void RejectsOrderWhenNotEnoughInventory()
        {
            var options = TestUtil.GetMemDbOptions("RejectsOrderWhenNotEnoughInventory");

            String product1Name, product2Name;
            Guid   customerId;
            Guid   orderId;

            using (var db = new StoreContext(options))
            {
                var(customer, location, product1, inventory) = SimplePopulate(db);
                customerId = customer.CustomerId;
                var product2 = new Product(Guid.NewGuid().ToString(), 2.0);
                db.Add(product2);
                var inventory2 = new LocationInventory(product2, location, 20);
                db.Add(inventory2);

                product1Name = product1.Name;
                product2Name = product2.Name;

                var order = new Order(customer, location);
                orderId = order.OrderId;

                var orderLine1 = new OrderLineItem(order, product1);
                orderLine1.Quantity = 9;
                order.OrderLineItems.Add(orderLine1);

                var orderLine2 = new OrderLineItem(order, product2);
                orderLine2.Quantity = 10;
                order.OrderLineItems.Add(orderLine2);

                var orderLine3 = new OrderLineItem(order, product2);
                orderLine3.Quantity = 11;
                order.OrderLineItems.Add(orderLine3);

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

            using (var db = new StoreContext(options))
            {
                var customer = (from c in db.Customers where c.CustomerId == customerId select c).First();

                var order = (from o in db.Orders
                             where o.Customer.CustomerId == customer.CustomerId
                             select o).First();

                Assert.Equal(customer.CustomerId, order.Customer.CustomerId);
            }

            Assert.Equal(PlaceOrderResult.OutOfStock, options.PlaceOrder(orderId, StoreDbUtil.Config.MAX_ORDER_QUANTITY));

            using (var db = new StoreContext(options))
            {
                var inventoryP1 = (from i in db.LocationInventories where i.Product.Name == product1Name select i).First();
                Assert.Equal(10, inventoryP1.Quantity);

                var inventoryP2 = (from i in db.LocationInventories where i.Product.Name == product2Name select i).First();
                Assert.Equal(20, inventoryP2.Quantity);
            }
        }
        static void Main(string[] args)
        {
            using (StoreApplicationContext dbContext = CreateDbContext())
                using (IStoreRepository storeRepository = new StoreRepository(dbContext))
                {
                    while (true)
                    {
                        try
                        {
                            _logger.Info($"Saving");
                            storeRepository.Save();
                        }
                        catch (DbUpdateException ex)
                        {
                            _logger.Error($"Failed to Save");
                            Console.WriteLine(ex.Message);
                        }

                        Console.WriteLine();
                        Console.WriteLine("1:\tDisplay All Names");
                        Console.WriteLine("2:\tSearch By Last Name");
                        Console.WriteLine("3:\tDisplay Order History of each location");
                        Console.WriteLine("4:\tQuit");
                        Console.WriteLine();

                        int                              input = IntValidation(1, 4);
                        string                           input2;
                        var                              count = 0;
                        Customer                         customer;
                        Product                          ProductValue;
                        var                              products  = storeRepository.DisplayProducts();
                        var                              products2 = products.ToList();
                        List <OrderDetails>              orderDetails;
                        IEnumerable <Order>              OrderValue;
                        IEnumerable <Customer>           AllNames;
                        IEnumerable <Inventories>        LocationInventory;
                        IEnumerable <ProductCat>         prodCategories;
                        IEnumerable <Product>            getRecoProduct;
                        IEnumerable <ComponentInventory> componentInventories;
                        List <Product>                   Cart;
                        List <Product>                   ComponentCart;
                        decimal                          Total = 0;
                        int                              tempOrderId;
                        Dictionary <string, int>         HashProducts;
                        HashSet <Product>                HashLoop;
                        int                              inventoryId;
                        switch (input)
                        {
                        case 1:
                            AllNames = storeRepository.GetNames();
                            Console.WriteLine();
                            count = 0;
                            _logger.Info($"Choosing Customer to Order for");
                            foreach (var x in AllNames)
                            {
                                Console.WriteLine($"\t{count}: {x.GetFullName()}");
                                count++;
                            }

                            if (count == 0)
                            {
                                Console.WriteLine("There are 0 Customers");
                                break;
                            }
                            var AllNamesList = AllNames.ToList();

                            Console.WriteLine($"Choose Customer to interact with or Press {AllNames.Count()} to go back");

                            input = IntValidation(0, AllNames.Count());
                            if (input != AllNames.Count())
                            {
                                customer   = AllNames.ElementAt(input);
                                OrderValue = storeRepository.GetOrders(customer);

                                _logger.Info($"Displaying orders for {customer.FName} {customer.LName} {customer.CustomerId}");
                                List <OrderDetails> temp2 = new List <OrderDetails>();
                                while (true)
                                {
                                    Console.WriteLine();
                                    Console.WriteLine("Do you want to view and sort Customer Order History?");
                                    Console.WriteLine("1:\tYes");
                                    Console.WriteLine("2:\tNo");
                                    Console.WriteLine();
                                    input = IntValidation(1, 2);
                                    if (input == 2)
                                    {
                                        break;
                                    }

                                    Console.WriteLine();
                                    Console.WriteLine("What do you want to sort by?");
                                    Console.WriteLine("1:\tEarliest");
                                    Console.WriteLine("2:\tLatest");
                                    Console.WriteLine("3:\tCheapest");
                                    Console.WriteLine("4:\tExpensive");
                                    Console.WriteLine();
                                    input = IntValidation(1, 4);
                                    List <Order> orderList = OrderValue.ToList();
                                    if (input == 1)
                                    {
                                        orderList = Order.SortList(orderList, Sort.Early);
                                    }
                                    else if (input == 2)
                                    {
                                        orderList = Order.SortList(orderList, Sort.Late);
                                    }
                                    else if (input == 3)
                                    {
                                        orderList = Order.SortList(orderList, Sort.Cheap);
                                    }
                                    else if (input == 4)
                                    {
                                        orderList = Order.SortList(orderList, Sort.Expensive);
                                    }
                                    count = 0;
                                    foreach (var x in orderList)
                                    {
                                        Console.WriteLine();
                                        Console.WriteLine($"Order {count}:\tTime:{x.TimeStamp}  \nStore: {x.Location.Name}\tCost: ${x.TotalAmount}");
                                        orderDetails = storeRepository.GetOrderDetails(x).ToList();
                                        temp2.AddRange(orderDetails);
                                        var y = orderDetails;
                                        foreach (var z in y)
                                        {
                                            var i = Order.GetProductName(products.ToList(), z.ProductId);
                                            Console.WriteLine($"\t{i}\tAmount:{z.Quantity} ");
                                        }
                                        count++;
                                    }
                                }
                                Cart = new List <Product>();

                                LocationInventory = storeRepository.GetInventories(customer);
                                List <Inventories> LocationInventoryList = LocationInventory.ToList();
                                Total = 0;
                                while (true)
                                {
                                    count    = 4;
                                    products = storeRepository.DisplayProducts();
                                    Console.WriteLine();
                                    foreach (var x in products)
                                    {
                                        if (count % 3 == 0)
                                        {
                                            Console.WriteLine($"\t{count - 4}: {x.ProductCost}  {x.ProductName}\t\t ");
                                        }
                                        else
                                        {
                                            Console.Write($"\t{count - 4}: {x.ProductCost}  {x.ProductName}\t\t ");
                                        }
                                        count++;
                                    }
                                    _logger.Info($"Get Recommended Items");
                                    Product product = new Product();

                                    List <Product> tempP     = new List <Product>();
                                    List <Order>   orderList = OrderValue.ToList();
                                    foreach (var x in orderList)
                                    {
                                        var y = storeRepository.GetOrderDetails(x).ToList();
                                        foreach (var z in y)
                                        {
                                            foreach (var t in products)
                                            {
                                                if (t.ProductId == z.ProductId)
                                                {
                                                    tempP.Add(t);
                                                }
                                            }
                                        }
                                        count++;
                                    }

                                    Console.WriteLine();
                                    Console.WriteLine();
                                    Console.WriteLine("Recommended Items:\n");
                                    var getStuff = dbContext.Products.Where(x => x.ProductCategoryId == tempP[tempP.Count - 1].CategoryId).ToList();
                                    count = 0;
                                    foreach (var x in getStuff)
                                    {
                                        if (count > 2)
                                        {
                                            break;
                                        }
                                        Console.Write($"   {x.ProductName}");
                                        count++;
                                    }

                                    Console.WriteLine();
                                    Console.WriteLine();
                                    Console.WriteLine();
                                    Console.WriteLine($"Add Product to cart or Enter {products.Count()} to purchase it\n");
                                    Console.WriteLine($"Purchasing from Default Location: {customer.DefaultLocation.Name}");
                                    Console.WriteLine($"There are {Cart.Count} Items in cart for a total of ${Total}");
                                    input = IntValidation(0, products.Count());
                                    _logger.Info($"Choose item to add to cart");
                                    if (input != products.Count())
                                    {
                                        ProductValue = products.ElementAt(input);
                                        _logger.Info($"Item chosen = {ProductValue.ProductName}");
                                        if (ProductValue.HasComponents)
                                        {
                                            componentInventories = storeRepository.GetComponents(ProductValue);
                                            ComponentCart        = new List <Product>();
                                            foreach (var x in componentInventories)
                                            {
                                                foreach (var y in products2)
                                                {
                                                    if (x.ComponentProductId == y.ProductId)
                                                    {
                                                        ComponentCart.Add(y);
                                                    }
                                                }
                                            }
                                            List <Inventories> tempInv = new List <Inventories>();
                                            tempInv.AddRange(LocationInventoryList);
                                            Decimal        tempTotal = Total;
                                            List <Product> tempCart  = new List <Product>();
                                            tempCart.AddRange(Cart);

                                            foreach (var x in ComponentCart)
                                            {
                                                if (Order.CheckCart(x, LocationInventoryList))
                                                {
                                                    Console.WriteLine($"\t{x.ProductName} has been added to cart");
                                                    Total += x.ProductCost;
                                                    Cart.Add(x);
                                                }
                                                else
                                                {
                                                    LocationInventoryList.Clear();
                                                    LocationInventoryList.AddRange(tempInv);
                                                    Cart.Clear();
                                                    Cart.AddRange(tempCart);
                                                    Total = tempTotal;

                                                    Console.WriteLine();
                                                    Console.WriteLine("Inventory is out");

                                                    break;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (Order.CheckCart(ProductValue, LocationInventoryList))
                                            {
                                                Console.WriteLine($"\t{ProductValue.ProductName} has been added to cart");
                                                Total += ProductValue.ProductCost;
                                                Cart.Add(ProductValue);
                                            }
                                            else
                                            {
                                                Console.WriteLine();
                                                Console.WriteLine("Inventory is out");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (Cart.Count == 0)
                                        {
                                            Console.WriteLine();
                                            Console.WriteLine("The cart is empty, so nothing was purchased!");
                                            Console.WriteLine();
                                            break;
                                        }
                                        else
                                        {
                                            //SA.Orders(ConsumerId,StoreId,TotalAmount)
                                            Order newOrder = new Order
                                            {
                                                CustomerId  = customer.CustomerId,
                                                StoreId     = customer.DefaultLocation.LocationId,
                                                TotalAmount = Total,
                                                Location    = customer.DefaultLocation,
                                                Customer    = customer,
                                                TimeStamp   = DateTime.Now,
                                            };
                                            storeRepository.AddOrder(newOrder, customer.DefaultLocation, customer);
                                            try
                                            {
                                                _logger.Info($"Saving");
                                                storeRepository.Save();
                                            }
                                            catch (DbUpdateException ex)
                                            {
                                                _logger.Error($"Failed to Save");
                                                Console.WriteLine(ex.Message);
                                            }
                                            Thread.Sleep(50);
                                            tempOrderId  = dbContext.Orders.OrderByDescending(y => y.OrderId).Select(a => a.OrderId).FirstOrDefault();
                                            HashProducts = new Dictionary <string, int>();
                                            HashLoop     = new HashSet <Product>();
                                            foreach (var x in Cart)
                                            {
                                                if (HashProducts.ContainsKey(x.ProductName))
                                                {
                                                    HashProducts[x.ProductName] += 1;
                                                }
                                                else
                                                {
                                                    HashProducts.Add(x.ProductName, 1);
                                                }
                                                HashLoop.Add(x);
                                            }
                                            count = 0;
                                            foreach (var x in HashLoop)
                                            {
                                                count++;
                                                Console.WriteLine(count);
                                                OrderDetails newOrderDetails = new OrderDetails
                                                {
                                                    OrderId   = tempOrderId,
                                                    ProductId = x.ProductId,
                                                    Quantity  = HashProducts[x.ProductName],
                                                };

                                                storeRepository.AddOrderDetails(newOrderDetails, newOrder, x);
                                                try
                                                {
                                                    _logger.Info($"Saving");
                                                    storeRepository.Save();
                                                }
                                                catch (DbUpdateException ex)
                                                {
                                                    _logger.Error($"Failed to Save");
                                                    Console.WriteLine(ex.Message);
                                                }
                                                inventoryId = dbContext.Inventory.Where(y => y.ProductId == x.ProductId && y.StoreId == customer.DefaultLocation.LocationId).Select(a => a.InventoryId).First();
                                                Thread.Sleep(50);
                                                Inventories inventories = new Inventories
                                                {
                                                    Quantity    = Order.getInventory(LocationInventoryList, x.ProductId),
                                                    StoreId     = customer.DefaultLocation.LocationId,
                                                    ProductId   = x.ProductId,
                                                    InventoryId = inventoryId,
                                                };
                                                storeRepository.UpdateInventory(inventories);
                                                try
                                                {
                                                    _logger.Info($"Saving");
                                                    storeRepository.Save();
                                                }
                                                catch (DbUpdateException ex)
                                                {
                                                    _logger.Error($"Failed to Save");
                                                    Console.WriteLine(ex.Message);
                                                }
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                            break;

                        case 2:
                            _logger.Info($"Search for name name");
                            do
                            {
                                Console.WriteLine("Please enter Full/Parital Last Name to search by");
                                input2 = Console.ReadLine();
                                if (input2.Length < 200 && input2.Length > 0)
                                {
                                    break;
                                }
                                else
                                {
                                    Console.WriteLine("Please enter word with 1 - 199 characters, ");
                                }
                            } while (true);

                            AllNames = storeRepository.GetNames(input2);
                            Console.WriteLine();
                            count = 0;

                            foreach (var x in AllNames)
                            {
                                Console.WriteLine($"\t{count}: {x.GetFullName()}");
                                count++;
                            }
                            if (count == 0)
                            {
                                Console.WriteLine("Your search had 0 results");
                            }
                            break;

                        case 3:
                            _logger.Info($"Display All orders by each location");
                            var n = storeRepository.GetOrders().ToList();
                            var p = n.OrderByDescending(k => k.Location.LocationId);


                            foreach (var a in p)
                            {
                                var    b    = dbContext.Consumer.ToList();
                                var    z    = dbContext.Store.ToList();
                                string name = "John Albert";
                                foreach (var m in z)
                                {
                                    if (m.Consumer.Where(c => c.ConsumerId == a.CustomerId).Select(x => x.ConsumerId).FirstOrDefault() == a.CustomerId)
                                    {
                                        name = m.Consumer.Where(c => c.ConsumerId == a.CustomerId).Select(x => x.Fname).FirstOrDefault() + " " + m.Consumer.Where(c => c.ConsumerId == a.CustomerId).Select(x => x.Lname).FirstOrDefault();
                                    }
                                }
                                Console.WriteLine($"{ a.Location.Name}");
                                Console.WriteLine($"\t{name}\t{a.TimeStamp}\t{a.TotalAmount}");
                                Console.WriteLine();
                            }
                            break;

                        case 4:
                            _logger.Info($"Exiting Application");
                            return;
                        }
                    }
                }
        }