public async Task Edit_WithQuantityNull_ShouldDeleteTheIngredientFromRecipe()
        {
            var dbContext = WantoeatDbContextInMemoryFactory.InitializeContext();

            await SeedData(dbContext);

            var recipe = dbContext.Recipes.First();

            var viewModel = new RecipeEditInputModel
            {
                Id              = recipe.Id,
                Name            = recipe.Name,
                CookingTimeName = recipe.CookingTime.Name,
                CategoryName    = recipe.Category.Name,
                IngredientNames = new List <string> {
                    "Eggs", "Mayo", "Avocado"
                },
                Quantity = new List <string> {
                    "3 pcs.", null, "3 pcs."
                },
            };

            var recipeIngredient = recipe.RecipeIngredient.Where(x => x.Ingredient.Name == "Mayo").First();

            var service = new RecipeService(dbContext);
            var actual  = await service.EditAsync(viewModel);

            Assert.DoesNotContain(recipeIngredient, actual.RecipeIngredient);
        }
Beispiel #2
0
        public async Task <IActionResult> Edit(RecipeEditInputModel model)
        {
            if (!ModelState.IsValid)
            {
                var unusedIngredients = await this.ingredientService.GetAllUnused(model.Id).ToListAsync();

                this.ViewData["ingredients"] = unusedIngredients.Select(ingredient => new RecipeCreateIngredientViewModel
                {
                    Name = ingredient.Name
                }).OrderBy(x => x.Name)
                                               .ToList();

                var allCookingTimes = await this.cookingTimeService.GetAll().ToListAsync();

                this.ViewData["cookingTimes"] = allCookingTimes.Select(item => item.Name).ToList();

                var allCategories = await this.categoryService.GetAll().ToListAsync();

                this.ViewData["categories"] = allCategories.Select(item => item.Name).ToList();

                return(this.View(model));
            }

            if (model.NewImageFile != null && model.NewImageFile.Length != 0)
            {
                if (model.ImagePath != null)
                {
                    model.ImagePath = this.imageService.ReplaceImage(model.NewImageFile, model.ImagePath, model.Name);
                }
                else
                {
                    model.ImagePath = this.imageService.UploadImage(model.NewImageFile, model.Name);
                }
            }

            var recipe = await this.recipeService.EditAsync(model);

            if (recipe == null)
            {
                throw new NullReferenceException();
            }

            return(this.RedirectToAction("Details", new { id = recipe.Id }));
        }
Beispiel #3
0
        public IActionResult Edit(RecipeEditInputModel model)
        {
            if (!this.recipes.Exist(model.Id))
            {
                return(this.NotFound());
            }

            if (!this.ModelState.IsValid)
            {
                return(this.View());
            }

            var recipeEditServiceModel = this.mapper.Map <RecipeEditServiceModel>(model);

            this.recipes.Edit(recipeEditServiceModel);

            //TODO: Images
            return(this.RedirectToAction("Details", "Recipes", new { Id = model.Id }));
        }
Beispiel #4
0
        public async Task <Recipe> EditAsync(RecipeEditInputModel model)
        {
            var recipeFromDb = GetById(model.Id);

            recipeFromDb.Name        = model.Name;
            recipeFromDb.Description = model.Description;
            recipeFromDb.Category    = this.dbContext.Categories.Where(x => x.Name == model.CategoryName).FirstOrDefault();
            recipeFromDb.CookingTime = this.dbContext.CookingTimes.Where(x => x.Name == model.CookingTimeName).FirstOrDefault();
            recipeFromDb.ImagePath   = model.ImagePath;
            recipeFromDb.ModifiedOn  = DateTime.UtcNow;

            int counter = 0;

            foreach (var currentIngredient in recipeFromDb.RecipeIngredient)
            {
                if (model.Quantity[counter] == null)
                {
                    this.dbContext.RecipeIngredient.Remove(currentIngredient);
                }
                else
                {
                    currentIngredient.Quantity = model.Quantity[counter];
                }

                counter++;
            }

            if (model.IngredientQuantities != null)
            {
                if (model.IngredientQuantities.IngredientNames.Count() != model.IngredientQuantities.RecipeIngredientQuantity.Count())
                {
                    throw new ArgumentNullException();
                }

                for (int i = 0; i < model.IngredientQuantities.IngredientNames.Count(); i++)
                {
                    var ingredient = this.dbContext.Ingredients.FirstOrDefault(x => x.Name == model.IngredientQuantities.IngredientNames[i]);

                    if (ingredient == null)
                    {
                        return(null);
                    }

                    RecipeIngredient recipeIngredient = new RecipeIngredient
                    {
                        Recipe     = recipeFromDb,
                        Ingredient = ingredient,
                        Quantity   = model.IngredientQuantities.RecipeIngredientQuantity[i],
                    };

                    if (this.dbContext.IngredientAllergen.Any(x => x.Ingredient.Name == ingredient.Name &&
                                                              !recipeFromDb.RecipeAllergens.Any(y => y.AllergenId == x.AllergenId)))
                    {
                        RecipeAllergen recipeAllergen = new RecipeAllergen
                        {
                            Recipe   = recipeFromDb,
                            Allergen = this.dbContext.IngredientAllergen.Where(x => x.Ingredient.Name == model.IngredientQuantities.IngredientNames[i]).Select(x => x.Allergen).FirstOrDefault()
                        };

                        recipeAllergen = this.dbContext.RecipeAllergen.Add(recipeAllergen).Entity;
                        recipeFromDb.RecipeAllergens.Add(recipeAllergen);
                    }

                    recipeIngredient = this.dbContext.RecipeIngredient.Add(recipeIngredient).Entity;
                    recipeFromDb.RecipeIngredient.Add(recipeIngredient);
                }
            }

            await this.dbContext.SaveChangesAsync();

            return(recipeFromDb);
        }
Beispiel #5
0
        public async Task <IActionResult> Edit(RecipeEditInputModel input)
        {
            var userId                = this.userManager.GetUserId(this.User);
            var isUserRecipeAuthor    = this.usersService.IsUserRecipeAuthor(userId, input.Id);
            var allowedMaxCountImages = int.Parse(this.TempData["MaxCountImages"].ToString());

            var isValidImages = true;

            if (input.Images != null)
            {
                isValidImages = input.NewImages?.Count <= allowedMaxCountImages;
                if (!isValidImages)
                {
                    this.ViewData["Errors"] += $"Можете да качите най-много {allowedMaxCountImages} снимки" + "\r\n";
                }
            }

            var isExist      = this.recipesService.IsExistRecipeTitle(input.Title);
            var title        = this.recipesService.GetRecipeTitle(input.Id);
            var isValidTitle = true;

            if (isExist && title.ToLower() != input.Title.ToLower())
            {
                isValidTitle             = false;
                this.ViewData["Errors"] += RecipeExistNameError + "\r\n";
            }

            var isAtLeastChecked = false;

            foreach (var cookingMethod in input.AllCookingMethods)
            {
                if (cookingMethod.Selected)
                {
                    isAtLeastChecked = true;
                    break;
                }
            }

            var isValidIngredients = true;

            foreach (var ingredientName in input.IngredientsNames.Split("\r\n", StringSplitOptions.RemoveEmptyEntries))
            {
                if (ingredientName.Length > AttributesConstraints.IngredientNameMaxLength ||
                    ingredientName.Length < AttributesConstraints.IngredientNameMinLength)
                {
                    isValidIngredients       = false;
                    this.ViewData["Errors"] += IngredientNameError + "\r\n";
                    break;
                }
            }

            if (!this.ModelState.IsValid ||
                !isAtLeastChecked ||
                !isValidTitle ||
                !isValidIngredients ||
                !isValidImages ||
                !isUserRecipeAuthor)
            {
                var categories     = this.categoriesService.GetAll <RecipeEditCategoryDropDownViewModel>();
                var cuisines       = this.cuisinesService.GetAll <RecipeEditCuisineDropDownViewModel>();
                var cookingMethods = this.cookingMethodsService.GetAll <RecipeEditCookingMethodsCheckboxViewModel>();

                input.Categories        = categories;
                input.Cuisines          = cuisines;
                input.AllCookingMethods = cookingMethods;

                var imagesCount = input.Images?.Count ?? 0;
                this.TempData["MaxCountImages"] = AttributesConstraints.RecipeImagesMaxCount - imagesCount;

                return(this.View(input));
            }

            var user = await this.userManager.GetUserAsync(this.User);

            var recipeDto = new RecipeEditDto
            {
                Id               = input.Id,
                Title            = input.Title,
                AuthorId         = user.Id,
                Description      = input.Description,
                Advices          = input.Advices,
                Servings         = input.Servings,
                PrepTime         = input.PrepTime,
                CookTime         = input.CookTime,
                SeasonalType     = input.SeasonalType,
                SkillLevel       = input.SkillLevel,
                CategoryId       = input.CategoryId,
                CuisineId        = input.CuisineId,
                NewImages        = input.NewImages,
                IngredientsNames = input.IngredientsNames,
                CookingMethods   = input.AllCookingMethods,
            };

            int recipeId = await this.recipesService.EditAsync(recipeDto);

            this.TempData["SuccessEditRecipe"] = SuccessEditRecipe;

            return(this.Redirect("/"));
        }
        public async Task <IActionResult> Edit(string id, RecipeEditInputModel recipeEditInputModel)
        {
            if (!this.ModelState.IsValid)
            {
                recipeEditInputModel.RecipeViewData = await this.recipeService.GetRecipeViewDataModelAsync();

                recipeEditInputModel.NeededTime = this.enumParseService
                                                  .GetEnumDescription(recipeEditInputModel.NeededTime, typeof(Period));

                return(this.View(recipeEditInputModel));
            }

            var recipeServiceModel = recipeEditInputModel.To <RecipeServiceModel>();

            var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

            recipeServiceModel.UserId = userId;

            var photoUrl = await this.cloudinaryService.UploadPhotoAsync(
                recipeEditInputModel.Photo,
                $"{userId}-{recipeEditInputModel.Title}",
                GlobalConstants.CloudFolderForRecipePhotos);

            recipeServiceModel.Photo = photoUrl;

            foreach (var allergenName in recipeEditInputModel.AllergenNames)
            {
                recipeServiceModel.Allergens.Add(new RecipeAllergenServiceModel
                {
                    Allergen = new AllergenServiceModel {
                        Name = allergenName
                    },
                });
            }

            foreach (var lifestyleType in recipeEditInputModel.LifestyleTypes)
            {
                recipeServiceModel.Lifestyles.Add(new RecipeLifestyleServiceModel
                {
                    Lifestyle = new LifestyleServiceModel {
                        Type = lifestyleType
                    },
                });
            }

            recipeServiceModel.NeededTime = this.enumParseService
                                            .Parse <Period>(recipeEditInputModel.NeededTime);

            if (!await this.recipeService.EditAsync(id, recipeServiceModel))
            {
                this.TempData["Error"] = EditErrorMessage;

                recipeEditInputModel.RecipeViewData = await this.recipeService.GetRecipeViewDataModelAsync();

                recipeEditInputModel.NeededTime = this.enumParseService
                                                  .GetEnumDescription(recipeEditInputModel.NeededTime, typeof(Period));

                return(this.View(recipeEditInputModel));
            }

            this.TempData["Success"] = EditSuccessMessage;

            return(this.Redirect($"/Recipes/Details/{id}"));
        }