/// <summary>
        /// Gets the user entry for the name and the list of categories, then adds the dish to the meal, and saves it to file.
        /// It is called by the code behind in DishEditPage View.
        /// </summary>
        private void SaveButtonExecute()
        {
            // build the dish category list
            InputDishCategories = new List <string>();
            if (DishCategoryCheckBox1)
            {
                InputDishCategories.Add(DishCategories["1"]);
            }
            if (DishCategoryCheckBox2)
            {
                InputDishCategories.Add(DishCategories["2"]);
            }
            if (DishCategoryCheckBox3)
            {
                InputDishCategories.Add(DishCategories["3"]);
            }
            if (DishCategoryCheckBox4)
            {
                InputDishCategories.Add(DishCategories["4"]);
            }
            if (DishCategoryCheckBox5)
            {
                InputDishCategories.Add(DishCategories["5"]);
            }

            // if the page is opened to create a new dish, add the dish to the database
            if (SelectedDish == null)
            {
                DishDB.Add(new Dish(EntryName, InputDishCategories, UserData));
                DishDBIO.WriteDishesToJSON(DishDB);
                MessagingCenter.Send(this, "DB updated");                       // refresh the search result
            }
            // otherwise edit the dish
            else
            {
                NameBeforeEdit = string.Copy(SelectedDish.Name);                        // save the dish name before change

                // if editing from the DishDB, find the dish in DishDB and update it
                if (IsFromDB)
                {
                    foreach (Dish dish in DishDB)
                    {
                        if (dish.Name == SelectedDish.Name)
                        {
                            dish.Name = EntryName;
                            dish.ThisDishCategories = InputDishCategories;
                            DishDBIO.WriteDishesToJSON(DishDB);
                            MessagingCenter.Send(this, "DB updated");                                   // refresh the search result
                            break;
                        }
                    }
                }
                // if editing from the meal, update the dish in the meal
                else
                {
                    SelectedMeal.EditDish(SelectedDish, EntryName, InputDishCategories);
                    UserDaysIO.WriteUserDaysToJSON(UserDays);
                }
            }
        }
        /// <summary>
        /// Updates tags and dish-tag links
        /// </summary>
        /// <param name="dishTagNames">List of tag names for dish</param>
        /// <param name="dish">Dish</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task UpdateTagLinks(HashSet <TagToAdd> dishTagNames, DishDB dish, CancellationToken cancellationToken = default)
        {
            foreach (var item in dishTagNames)
            {
                TagDB tag = await _context.Tags.IgnoreQueryFilters().Where(_ => _.TagName == item.TagName).Select(_ => _).FirstOrDefaultAsync(cancellationToken);

                if (tag is null)
                {
                    var tagAfter = await _tagService.AddTagDBAsync(item);

                    dish.DishTags.Add(new DishTagDB {
                        TagId = tagAfter.Data.Id, DishId = dish.Id
                    });
                }
                else if (_context.Entry(tag).Property <bool>("IsDeleted").CurrentValue)
                {
                    _context.Entry(tag).Property <bool>("IsDeleted").CurrentValue = false;
                    dish.DishTags.Add(new DishTagDB {
                        TagId = tag.Id, DishId = dish.Id
                    });
                }
                else
                {
                    dish.DishTags.Add(new DishTagDB {
                        TagId = tag.Id, DishId = dish.Id
                    });
                }
            }
        }
        public async Task <Result <DishView> > AddAsync(DishToAdd dish, CancellationToken cancellationToken = default)
        {
            DishDB dishToAdd = _mapper.Map <DishDB>(dish);

            dishToAdd.Added = DateTime.UtcNow;
            _context.Dishes.Add(dishToAdd);
            try
            {
                await UpdateTagLinks(dish.TagNames, dishToAdd);

                await _context.SaveChangesAsync(cancellationToken);

                DishDB dishAfterAdding = await _context.Dishes.Where(_ => _.Id == dishToAdd.Id).Include(c => c.DishTags).ThenInclude(sc => sc.Tag).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                DishView view = _mapper.Map <DishView>(dishAfterAdding);
                view.TagList = CollectTagList(dishAfterAdding.DishTags, cancellationToken).Result;
                return(Result <DishView> .Ok(view));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Result <DishView> .Fail <DishView>(ExceptionConstants.CANNOT_SAVE_MODEL + ex.Message));
            }
            catch (DbUpdateException ex)
            {
                return(Result <DishView> .Fail <DishView>(ExceptionConstants.CANNOT_SAVE_MODEL + ex.Message));
            }
            catch (ArgumentNullException ex)
            {
                return(Result <DishView> .Fail <DishView>(ExceptionConstants.SOURCE_IS_NULL + ex.Message));
            }
        }
        public async Task <Result <IEnumerable <DishView> > > GetByTagIndexAsync(string tagName, CancellationToken cancellationToken = default)
        {
            TagDB tag = await _context.Tags.Where(_ => _.TagName == tagName).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

            if (tag is null)
            {
                return(Result <IEnumerable <DishView> > .Fail <IEnumerable <DishView> >(ExceptionConstants.TAG_WAS_NOT_FOUND));
            }
            var dishTags = await _context.DishTags.Where(_ => _.TagId == tag.Id).AsNoTracking().ToListAsync(cancellationToken);

            if (!dishTags.Any())
            {
                return(Result <IEnumerable <DishView> > .Fail <IEnumerable <DishView> >(ExceptionConstants.DISHES_WERE_NOT_FOUND));
            }

            List <DishView> views = new List <DishView>();

            foreach (var dishTag in dishTags)
            {
                DishDB dish = await _context.Dishes.Where(_ => _.Id == dishTag.DishId).Include(c => c.DishTags).ThenInclude(sc => sc.Tag).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                DishView viewItem = _mapper.Map <DishView>(dish);
                viewItem.TotalCost = Math.Round(viewItem.Price * (1 - viewItem.Sale / 100), 2);
                viewItem.TagList   = new HashSet <TagToAdd>();
                foreach (var item in dish.DishTags)
                {
                    var tagItem = await _context.Tags.Where(_ => _.Id == item.TagId).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                    viewItem.TagList.Add(_mapper.Map <TagToAdd>(tagItem));
                }
                views.Add(viewItem);
            }

            return(Result <IEnumerable <DishView> > .Ok(_mapper.Map <IEnumerable <DishView> >(views)));
        }
        public ActionResult Details(int id)
        {
            //creation of multiple variables to check conditions and for the display
            IOrderDB               order             = new OrderDB(Configuration);
            IOrderManager          om                = new OrderManager(order);
            ICustomerDB            customer          = new CustomerDB(Configuration);
            ICustomerManager       cm                = new CustomerManager(customer);
            ICityDB                citydb            = new CityDB(Configuration);
            ICityManager           cityman           = new CityManager(citydb);
            IDelivery_staffDB      dsDB              = new Delivery_staffDB(Configuration);
            IDelivery_staffManager dsM               = new Delivery_staffManager(dsDB);
            IDishDB                dish              = new DishDB(Configuration);
            IDishManager           dishManager       = new DishManager(dish);
            IOrder_dishesDB        order_Dishes      = new Order_dishesDB(Configuration);
            IOrder_dishesManager   odm               = new Order_dishesManager(order_Dishes);
            IRestaurantDB          restaurant        = new RestaurantDB(Configuration);
            IRestaurantManager     restaurantManager = new RestaurantManager(restaurant);

            //Creations of multiple ViewData for the display
            var customerlist = cm.GetCustomers();

            ViewData["Customers"] = customerlist;
            var citylist = cityman.GetCities();

            ViewData["City"] = citylist;
            var allOrders = om.GetOrders();

            ViewData["AllOrders"] = allOrders;
            var allStaff = dsM.GetDelivery_staffs();

            ViewData["AllStaffs"] = allStaff;
            var allDishes = dishManager.GetAllDishes();

            ViewData["AllDishes"] = allDishes;
            var allOrderDishes = odm.GetAllOrders_dishes();

            ViewData["AllOrderDishes"] = allOrderDishes;
            var allRestaurants = restaurantManager.GetRestaurants();

            ViewData["AllRestaurants"] = allRestaurants;

            ViewBag.nameDL = HttpContext.Session.GetString("nameDL");
            var od = om.GetOrders_ds(id); //Get all orders according to the deliverer's id

            List <Order> odtrie = new List <Order>();

            //Creation of a list which will only contain the non delivery order(s)
            foreach (Order o in od)
            {
                if (o.status.Equals("non delivery"))
                {
                    odtrie.Add(o);
                }
            }

            return(View(odtrie)); //Display the non delivery order(s)
        }
Beispiel #6
0
        // GET: Customer/Details/5
        public ActionResult Details()
        {
            if ((string)HttpContext.Session.GetString("login") != "Aucun customer n'est log" && (string)HttpContext.Session.GetString("login") != null) // A customer is logged ?
            {
                //Get the login of the current customer
                ViewBag.login = HttpContext.Session.GetString("login");

                //creation of multiple variables to check conditions and for the display
                IOrderDB               order           = new OrderDB(Configuration);
                IOrderManager          om              = new OrderManager(order);
                IDelivery_staffDB      dsDB            = new Delivery_staffDB(Configuration);
                IDelivery_staffManager dsM             = new Delivery_staffManager(dsDB);
                IDishDB              dish              = new DishDB(Configuration);
                IDishManager         dishManager       = new DishManager(dish);
                IOrder_dishesDB      order_Dishes      = new Order_dishesDB(Configuration);
                IOrder_dishesManager odm               = new Order_dishesManager(order_Dishes);
                IRestaurantDB        restaurant        = new RestaurantDB(Configuration);
                IRestaurantManager   restaurantManager = new RestaurantManager(restaurant);

                //Get the id of the current customer
                var id = (int)HttpContext.Session.GetInt32("id");

                //Get an orderlist according to the customer id
                var ordersList = om.GetOrders(id);

                //Creations of multiple ViewData for the display
                var allOrders = om.GetOrders();
                ViewData["AllOrders"] = allOrders;
                var allStaff = dsM.GetDelivery_staffs();
                ViewData["AllStaffs"] = allStaff;
                var allDishes = dishManager.GetAllDishes();
                ViewData["AllDishes"] = allDishes;
                var allOrderDishes = odm.GetAllOrders_dishes();
                ViewData["AllOrderDishes"] = allOrderDishes;
                var allRestaurants = restaurantManager.GetRestaurants();
                ViewData["AllRestaurants"] = allRestaurants;

                //Check if the customer has not order
                if (ordersList == null)
                {
                    return(RedirectToAction("DetailsNoOrder", "Customer", new { user = id.ToString() }));
                }
                else
                {
                    return(View(ordersList)); // Return the Details view
                }
            }
            else
            {
                return(RedirectToAction("Index", "Customer")); // return to the login page
            }
        }
        /// <summary>
        /// Input validation whether to proceed with saving the dish
        /// </summary>
        /// <returns></returns>
        private bool SaveButtonCanExecute()
        {
            // if the entered name already exists, return false
            if (DishDB.Select(dish => dish.Name).Contains(EntryName))
            {
                if (SelectedDish == null || SelectedDish.Name != EntryName)
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #8
0
        public async void Menu_GetByTagIndexAsync_PositiveAndNegative_Test()
        {
            var options = new DbContextOptionsBuilder <DreamFoodDeliveryContext>()
                          .UseInMemoryDatabase(databaseName: "Menu_GetByTagIndexAsync_PositiveAndNegative_Test")
                          .Options;
            string tagTestName       = "new";
            string tagTestSecondName = "old";

            using (var context = new DreamFoodDeliveryContext(options))
            {
                TagDB[] tags = new TagDB[]
                {
                    new TagDB
                    {
                        TagName = tagTestName
                    },
                    new TagDB
                    {
                        TagName = tagTestSecondName
                    },
                };
                DishDB dish = new DishDB
                {
                    Name = "dish"
                };

                context.AddRange(tags);
                context.Add(dish);
                DishTagDB dishTag = new DishTagDB
                {
                    TagId  = tags.FirstOrDefault(x => x.TagName == tagTestName).Id,
                    DishId = dish.Id
                };
                context.Add(dishTag);

                await context.SaveChangesAsync();
            }

            using (var context = new DreamFoodDeliveryContext(options))
            {
                var service = new MenuService(_mapper, context);

                var resultPositive = await service.GetByTagIndexAsync(tagTestName);

                var resultNegative = await service.GetByTagIndexAsync(tagTestSecondName);

                resultPositive.IsSuccess.Should().BeTrue();
                resultNegative.IsSuccess.Should().BeFalse();
            }
        }
        //Display the list of dishes of a restaurant
        public ActionResult Plat(int id)
        {
            IDishDB      dish        = new DishDB(Configuration);
            IDishManager dishManager = new DishManager(dish);



            var dishes = dishManager.GetDishes(id);

            HttpContext.Session.SetInt32("idResto", id); //setting a session for the command action

            ViewBag.id = id;

            return(View(dishes));
        }
 /// <summary>
 /// Whether AdditionalEditDish command can execute;
 /// </summary>
 /// <returns></returns>
 private bool AdditionalEditDishCanExecute()
 {
     // if the DIsh in the DishDB was edited, always allow additional update to the meals
     if (IsFromDB)
     {
         return(true);
     }
     // if the Dish in the Meal was edited, only update if the DishDB still contains that Dish.
     else
     {
         if (DishDB.Select(dish => dish.Name).Contains(NameBeforeEdit))
         {
             return(true);
         }
         return(false);
     }
 }
        public async Task <Result <DishView> > UpdateAsync(DishToUpdate dish, CancellationToken cancellationToken = default)
        {
            DishDB dishToUpdate = await _context.Dishes.IgnoreQueryFilters().Include(c => c.DishTags).ThenInclude(sc => sc.Tag).AsNoTracking().FirstOrDefaultAsync(_ => _.Id == dish.Id);

            if (dishToUpdate is null)
            {
                return(Result <DishView> .Quite <DishView>(ExceptionConstants.DISH_WAS_NOT_FOUND));
            }
            var dishTagList = await _context.DishTags.Where(_ => _.DishId == dish.Id).AsNoTracking().ToListAsync(cancellationToken);

            _context.DishTags.RemoveRange(dishTagList);
            dishToUpdate.DishTags.Clear();
            await _context.SaveChangesAsync(cancellationToken);

            try
            {
                dishToUpdate          = _mapper.Map <DishDB>(dish);
                dishToUpdate.Modified = DateTime.Now;

                _context.Entry(dishToUpdate).Property(c => c.Name).IsModified        = true;
                _context.Entry(dishToUpdate).Property(c => c.Composition).IsModified = true;
                _context.Entry(dishToUpdate).Property(c => c.Description).IsModified = true;
                _context.Entry(dishToUpdate).Property(c => c.Price).IsModified       = true;
                _context.Entry(dishToUpdate).Property(c => c.Weight).IsModified      = true;
                _context.Entry(dishToUpdate).Property(c => c.Sale).IsModified        = true;
                _context.Entry(dishToUpdate).Property(c => c.Modified).IsModified    = true;

                await UpdateTagLinks(dish.TagNames, dishToUpdate);

                await _context.SaveChangesAsync(cancellationToken);

                DishDB dishAfterAdding = await _context.Dishes.Where(_ => _.Id == dishToUpdate.Id).Include(c => c.DishTags).ThenInclude(sc => sc.Tag).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                DishView view = _mapper.Map <DishView>(dishAfterAdding);
                view.TagList = CollectTagList(dishAfterAdding.DishTags, cancellationToken).Result;
                return(Result <DishView> .Ok(_mapper.Map <DishView>(view)));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Result <DishView> .Fail <DishView>(ExceptionConstants.CANNOT_UPDATE_MODEL + ex.Message));
            }
            catch (DbUpdateException ex)
            {
                return(Result <DishView> .Fail <DishView>(ExceptionConstants.CANNOT_UPDATE_MODEL + ex.Message));
            }
        }
Beispiel #12
0
        //Display the dish(es) in a specific order
        public ActionResult DishesInOrder(int id)
        {
            IDishDB      dish        = new DishDB(Configuration);
            IDishManager dishManager = new DishManager(dish);

            IOrder_dishesDB      order_Dishes = new Order_dishesDB(Configuration);
            IOrder_dishesManager odm          = new Order_dishesManager(order_Dishes);

            //Creation of a ViewData for the display
            var allDishes = dishManager.GetAllDishes();

            ViewData["AllDishes"] = allDishes;


            var orderDishes = odm.GetOrders_dishes(id);

            return(View(orderDishes)); //Display the list of dish(es)
        }
Beispiel #13
0
        public int InsertUpdateDish(DishData dish)
        {
            SqlConnection  SqlConn = null;
            SqlTransaction SqlTran = null;

            try
            {
                SqlConn = new SqlConnection(SystemConfigurations.EateryConnectionString);
                SqlConn.Open();
                SqlTran = SqlConn.BeginTransaction();
                int rowsAffected = new DishDB().InsertUpdateDish(dish, SqlTran);
                SqlTran.Commit();
                SqlConn.Close();
                return(rowsAffected);
            }
            catch (Exception ex)
            {
                SqlTran.Rollback();
                SqlConn.Close();
                throw ex;
            }
        }
Beispiel #14
0
        public int DeleteDishes(IEnumerable <int> dishIDs)
        {
            SqlConnection  SqlConn = null;
            SqlTransaction SqlTran = null;

            try
            {
                SqlConn = new SqlConnection(SystemConfigurations.EateryConnectionString);
                SqlConn.Open();
                SqlTran = SqlConn.BeginTransaction();
                int rowsAffected = new DishDB().DeleteDishes(String.Join(",", dishIDs), SqlTran);
                SqlTran.Commit();
                SqlConn.Close();
                return(rowsAffected);
            }
            catch (Exception ex)
            {
                SqlTran.Rollback();
                SqlConn.Close();
                throw ex;
            }
        }
        public async Task <Result <DishView> > GetByIdAsync(string dishId, CancellationToken cancellationToken = default)
        {
            Guid id = Guid.Parse(dishId);

            try
            {
                DishDB dish = await _context.Dishes.IgnoreQueryFilters().Where(_ => _.Id == id).Include(c => c.DishTags).ThenInclude(sc => sc.Tag).FirstOrDefaultAsync(cancellationToken);

                if (dish is null)
                {
                    return(Result <DishView> .Fail <DishView>(ExceptionConstants.DISH_WAS_NOT_FOUND));
                }
                DishView view = _mapper.Map <DishView>(dish);
                view.TotalCost = Math.Round(view.Price * (1 - view.Sale / 100), 2);
                view.TagList   = CollectTagList(dish.DishTags, cancellationToken).Result;
                return(Result <DishView> .Ok(view));
            }
            catch (ArgumentNullException ex)
            {
                return(Result <DishView> .Fail <DishView>(ExceptionConstants.SOURCE_IS_NULL + ex.Message));
            }
        }
        public async Task <Result <BasketView> > AddUpdateDishAsync(string dishId, string userIdFromIdentity, int quantity, CancellationToken cancellationToken = default)
        {
            DishDB dishToAdd = await _context.Dishes.Where(_ => _.Id == Guid.Parse(dishId)).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

            if (dishToAdd is null)
            {
                return(Result <BasketView> .Fail <BasketView>(ExceptionConstants.DISH_WAS_NOT_FOUND));
            }
            UserDB user = await _context.Users.Where(_ => _.IdFromIdentity == userIdFromIdentity).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

            AppUser userIdentity = await _userManager.FindByIdAsync(userIdFromIdentity);

            if (user is null || userIdentity is null)
            {
                return(Result <BasketView> .Fail <BasketView>(ExceptionConstants.USER_WAS_NOT_FOUND));
            }
            BasketDB basket = await _context.Baskets.Where(_ => _.UserId == user.Id).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

            if (basket is null)
            {
                return(Result <BasketView> .Fail <BasketView>(ExceptionConstants.BASKET_WAS_NOT_FOUND));
            }

            var connection = await _context.BasketDishes.Where(_ => _.BasketId == basket.Id && _.DishId == Guid.Parse(dishId)).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

            if (connection is null)
            {
                BasketDishDB basketDish = new BasketDishDB()
                {
                    BasketId = basket.Id, DishId = dishToAdd.Id, Quantity = quantity, DishPrice = dishToAdd.Price, Sale = dishToAdd.Sale
                };
                _context.BasketDishes.Add(basketDish);
            }
            else
            {
                if (quantity > 0)
                {
                    connection.Quantity = quantity;
                    _context.Entry(connection).Property(c => c.Quantity).IsModified = true;
                }
                else // quantity == 0
                {
                    _context.BasketDishes.Remove(connection);
                }
            }

            basket.ModificationTime = DateTime.Now;
            _context.Entry(basket).Property(c => c.ModificationTime).IsModified = true;

            try
            {
                await _context.SaveChangesAsync(cancellationToken);

                var dishList = await _context.BasketDishes.Where(_ => _.BasketId == basket.Id).AsNoTracking().ToListAsync(cancellationToken);

                //BasketView view = CollectBasket(basket, dishList, userIdentity).Result.Data;
                //return Result<BasketView>.Ok(view);
                return(CollectBasket(basket, dishList, userIdentity).Result);
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return(Result <BasketView> .Fail <BasketView>(ExceptionConstants.CANNOT_SAVE_MODEL + ex.Message));
            }
            catch (DbUpdateException ex)
            {
                return(Result <BasketView> .Fail <BasketView>(ExceptionConstants.CANNOT_SAVE_MODEL + ex.Message));
            }
            catch (ArgumentNullException ex)
            {
                return(Result <BasketView> .Fail <BasketView>(ExceptionConstants.SOURCE_IS_NULL + ex.Message));
            }
        }
 public bool DeleteDishByID(int dishID)
 {
     DishDB dishDB = new DishDB();
     Dish dish = dishDB.GetById(dishID);
     Response<Dish> response = dish.Delete();
     return response.Success;
 }
        public bool UpdateDish(int dishID, string dishName, decimal dishPrice, int dishNumber, int dishRestaurantMenuID)
        {
            DishDB dishDB = new DishDB();
            Dish dish = dishDB.GetById(dishID);
            dish.Name = dishName;
            dish.Price = dishPrice;
            dish.Number = dishNumber;
            dish.RestaurantMenuID = dishRestaurantMenuID;
            Response<Dish> response = dish.Update();
            foreach (string r in response.Messages)
            {
                Console.WriteLine(r);
            }

            return response.Success;
        }
 public List<Dish> GetDishesByRestaurantMenuId(int restaurantMenuID)
 {
     DishDB dishDB = new DishDB();
     return dishDB.GetByRestaurantMenuId(restaurantMenuID);
 }
 public List<Dish> GetDishesByRestaurantID(int restaurantID)
 {
     DishDB dishDB = new DishDB();
     List<Dish> dishes = dishDB.GetDishesByRestaurantID(restaurantID);
     return dishes;
 }
        public Dish GetDishById(int dishID)
        {
            DishDB dishDB = new DishDB();

            return dishDB.GetById(dishID);
        }
        public async Task <Result <IEnumerable <DishView> > > GetAllDishesByRequestAsync(RequestParameters request, CancellationToken cancellationToken = default)
        {
            try
            {
                List <DishDB> dishesList = new List <DishDB>();
                if (request.TagsNames.Any())
                {
                    HashSet <DishTagDB> dishTagsList = new HashSet <DishTagDB>();
                    foreach (var tagName in request.TagsNames)
                    {
                        TagDB tag = await _context.Tags.Where(_ => _.TagName == tagName).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                        if (!(tag is null))
                        {
                            var dishTags = await _context.DishTags.Where(_ => _.TagId == tag.Id).AsNoTracking().ToListAsync(cancellationToken);

                            if (dishTags.Any())
                            {
                                foreach (var dishTag in dishTags)
                                {
                                    if (dishTagsList.Count is 0)
                                    {
                                        dishTagsList.Add(dishTag);
                                    }
                                    var dishTagToCompare = dishTagsList.Where(_ => _.DishId == dishTag.DishId).FirstOrDefault();
                                    if (!dishTagsList.Where(_ => _.DishId == dishTag.DishId).Any())
                                    {
                                        dishTagsList.Add(dishTag);
                                    }
                                }
                            }
                        }
                    }
                    if (!dishTagsList.Any())
                    {
                        return(Result <IEnumerable <DishView> > .Fail <IEnumerable <DishView> >(ExceptionConstants.DISHES_WERE_NOT_FOUND));
                    }
                    foreach (DishTagDB dishTag in dishTagsList)
                    {
                        DishDB dish = await _context.Dishes.Where(_ => _.Id == dishTag.DishId).Include(c => c.DishTags).ThenInclude(sc => sc.Tag).Select(_ => _).AsNoTracking().FirstOrDefaultAsync(cancellationToken);

                        dishesList.Add(dish);
                    }
                }
                else
                {
                    dishesList = await _context.Dishes.Include(c => c.DishTags).ThenInclude(sc => sc.Tag).AsNoTracking().ToListAsync(cancellationToken);
                }

                if (!dishesList.Any())
                {
                    return(Result <IEnumerable <DishView> > .Fail <IEnumerable <DishView> >(ExceptionConstants.DISHES_WERE_NOT_FOUND));
                }
                if (!string.IsNullOrEmpty(request.Request) && dishesList.Any())
                {
                    dishesList = dishesList.Where(_ => _.Name.Contains(request.Request) || _.Composition.Contains(request.Request) || _.Description.Contains(request.Request)).ToList();
                }
                if (request.OnSale && dishesList.Any())
                {
                    dishesList = dishesList.Where(_ => _.Sale > 0).ToList();
                }
                if (request.LowerPrice > 0 && dishesList.Any())
                {
                    dishesList = dishesList.Where(_ => _.Price >= request.LowerPrice).ToList();
                }
                if (request.UpperPrice > 0 && request.UpperPrice >= request.LowerPrice && dishesList.Any())
                {
                    dishesList = dishesList.Where(_ => _.Price <= request.UpperPrice).ToList();
                }

                List <DishView> views = await CollectViews(dishesList);

                return(Result <IEnumerable <DishView> > .Ok(_mapper.Map <IEnumerable <DishView> >(views)));
            }
            catch (ArgumentNullException ex)
            {
                return(Result <IEnumerable <DishView> > .Fail <IEnumerable <DishView> >(ExceptionConstants.SOURCE_IS_NULL + ex.Message));
            }
        }
        //POST : Restaurtant/command
        public ActionResult Command()
        {
            //take back the Form
            string platun       = Request.Form["platun"];
            string platunun     = Request.Form["platunun"];
            string platununun   = Request.Form["platununun"];
            string platunununun = Request.Form["platunununun"];
            string deliveryTime = Request.Form["deliveryTime"];

            IDishDB                dish                = new DishDB(Configuration);
            IOrderDB               orderdb             = new OrderDB(Configuration);
            IOrder_dishesDB        orderddb            = new Order_dishesDB(Configuration);
            IDelivery_staffDB      dldb                = new Delivery_staffDB(Configuration);
            IRestaurantDB          restodb             = new RestaurantDB(Configuration);
            IDishManager           dishManager         = new DishManager(dish);
            IOrderManager          orderManager        = new OrderManager(orderdb);
            IOrder_dishesManager   order_DishesManager = new Order_dishesManager(orderddb);
            IDelivery_staffManager dlmanager           = new Delivery_staffManager(dldb);
            IRestaurantManager     restoManager        = new RestaurantManager(restodb);

            //creation of lists for create the orders and the order_dishes
            List <Dish_Order> dishlist = new List <Dish_Order>();
            //List of dish
            List <Dish> plat = dishManager.GetDishes((int)HttpContext.Session.GetInt32("idResto"));
            //List of quantity
            List <string> s = new List <string>();

            s.Add(platun);
            s.Add(platunun);
            if (platununun != null)
            {
                s.Add(platununun);
            }
            if (platunununun != null)
            {
                s.Add(platunununun);
            }

            int   x = 0;
            int   quantitytemp;
            float pricetemp;
            float priceGeneral = 0;

            //Creation of my ViewModel Dish_Order
            foreach (Dish d in plat)
            {
                Dish_Order order = new Dish_Order();
                order.Dish_Id    = d.dish_Id;
                order.Name       = d.name;
                order.Price      = d.price;
                pricetemp        = d.price;
                order.Quantity   = Int32.Parse(s.ElementAt(x));
                quantitytemp     = Int32.Parse(s.ElementAt(x));
                order.totalPrice = quantitytemp * pricetemp;
                priceGeneral    += quantitytemp * pricetemp;
                dishlist.Add(order);
                x++;
            }

            //Set the Final price for the view
            ViewBag.prix = priceGeneral;

            //if the customer has select at least 1 dish
            if (priceGeneral != 0)
            {
                //Create a new Order
                Order ikse = new Order();
                ikse.delivery_time = deliveryTime;
                ikse.totalPrice    = priceGeneral;
                ikse.customer_Id   = (int)HttpContext.Session.GetInt32("id");

                //select whitch delivery staff is available
                var dslist       = dlmanager.GetDelivery_staffs();
                int idDs         = -1;
                var listeresto   = restoManager.GetRestaurants();
                int cityCodeTemp = 0;

                //Select the list of delivery staff
                foreach (Delivery_staff ds in dslist)
                {
                    //find the city of the restaurant
                    foreach (Dish d in plat)
                    {
                        if (d.dish_Id == dishlist[0].Dish_Id)
                        {
                            foreach (Restaurant r in listeresto)
                            {
                                if (d.restaurant_Id == r.restaurant_Id)
                                {
                                    cityCodeTemp = r.cityCode;
                                }
                            }
                        }
                    }

                    //if the delivery staff is at the good city
                    if (ds.cityCode == cityCodeTemp)
                    {
                        var isbusy    = false;
                        var oListByDl = orderManager.GetOrders_ds(ds.delivery_staff_Id);
                        int cptOrder  = 0;
                        foreach (Order o in oListByDl)
                        {
                            //select the orders non delivery
                            if (o.status == "non delivery")
                            {
                                //change the 11:00 in 1100, change the minutes from base 60 to base 100 for calculation
                                string deliveryTimePourInt = o.delivery_time.Remove(2, 1);
                                string deliveryTimePartOne = deliveryTimePourInt.Substring(0, 2);
                                string deliveryTimePartTwo = deliveryTimePourInt.Substring(2);
                                int    test = Int32.Parse(deliveryTimePartTwo);
                                switch (test)
                                {
                                case 0:
                                    break;

                                case 15:
                                    test = 25;
                                    break;

                                case 30:
                                    test = 50;
                                    break;

                                case 45:
                                    test = 75;
                                    break;
                                }
                                deliveryTimePartTwo = test.ToString();

                                int deliveryTimeInt = Int32.Parse(deliveryTimePartOne + deliveryTimePartTwo);
                                //correct the houres
                                if (deliveryTimeInt % 10 == 0)
                                {
                                    deliveryTimeInt *= 10;
                                    if (deliveryTimeInt / 10000 != 0)
                                    {
                                        deliveryTimeInt /= 10;
                                    }
                                }
                                //same think for the delivery time of the order
                                string deliveryTimeForCompare = deliveryTime.Remove(2, 1);

                                string dtPartOne = deliveryTimeForCompare.Substring(0, 2);
                                string dtPartTwo = deliveryTimeForCompare.Substring(2);
                                int    essai     = Int32.Parse(dtPartTwo);
                                switch (essai)
                                {
                                case 0:
                                    break;

                                case 15:
                                    essai = 25;
                                    break;

                                case 30:
                                    essai = 50;
                                    break;

                                case 45:
                                    essai = 75;
                                    break;
                                }
                                dtPartTwo = essai.ToString();
                                int dTForCompare = Int32.Parse(dtPartOne + dtPartTwo);
                                if (dTForCompare % 10 == 0)
                                {
                                    dTForCompare *= 10;
                                    if (dTForCompare / 10000 != 0)
                                    {
                                        dTForCompare /= 10;
                                    }
                                }
                                int compare = (deliveryTimeInt - dTForCompare);

                                //if the order is within 15 minutes before or after the delivery staff's order
                                if (compare <= 25 && compare >= -25)
                                {
                                    cptOrder++;
                                }
                            }
                        }
                        //if the staff is busy
                        if (cptOrder >= 5)
                        {
                            isbusy = true;
                        }
                        //if the staff is free
                        if (isbusy == false)
                        {
                            //assign the staff to the order
                            idDs = ds.delivery_staff_Id;
                        }
                    }
                }
                //if a staff is free
                if (idDs != -1)
                {
                    //assign the staff
                    ikse.delivery_staff_Id = idDs;

                    //create the order in the database
                    var orderaiedi = orderManager.AddOrder(ikse);

                    //create the order dishes and add to the database
                    foreach (Dish_Order disho in dishlist)
                    {
                        Order_dishes order_dishes_ = new Order_dishes();
                        order_dishes_.order_Id = orderaiedi;
                        order_dishes_.dish_Id  = disho.Dish_Id;
                        order_dishes_.quantity = disho.Quantity;
                        order_dishes_.price    = disho.totalPrice;
                        if (order_dishes_.quantity != 0)
                        {
                            order_DishesManager.AddOrder_dishes(order_dishes_);
                        }
                    }
                    //return the normal view
                    return(View());
                }
                //if no staff is free
                else
                {
                    //return the error view
                    return(RedirectToAction("ErrorNoDs", "Restaurant"));
                }
            }
            //if the customer didn't select any dish, return the error view
            return(RedirectToAction("ErrorNoQuantity", "Restaurant"));
        }