Ejemplo n.º 1
0
        public IGraph GetNode(Guid id, string foodUriPrefix)
        {
            var food = Get(id);

            if (Notificator.HasErrors())
            {
                return(null);
            }

            var nutrients = UnitOfWork.Repository <Nutrient>().GetAll();

            var fat = nutrients
                      .FirstOrDefault(n => n.Name == "Total Fat");
            var carbohydrate = nutrients
                               .FirstOrDefault(n => n.Name == "Carbohydrate");
            var protein = nutrients
                          .FirstOrDefault(n => n.Name == "Protein");

            var g = new Graph();

            g.NamespaceMap.AddNamespace("dbp", new Uri("https://dbpedia.org/property/"));
            g.NamespaceMap.AddNamespace("dbo", new Uri("https://dbpedia.org/ontology/"));

            var t = MapFoodEntityToNode(g, food, fat, carbohydrate, protein, foodUriPrefix);

            g.Assert(t);

            return(g);
        }
Ejemplo n.º 2
0
        public override User Update(User user, params string[] ruleSets)
        {
            var validator = new InlineValidator <User>();

            validator.RuleFor(u => u.Username)
            .Must(usn => !UnitOfWork.Users.Search(u => u.Username == usn && u.Id != user.Id).Any())
            .WithMessage("Already exists an user with this username.");

            validator.RuleFor(u => u.Email)
            .Must(usn => !UnitOfWork.Users.Search(u => u.Email == usn && u.Id != user.Id).Any())
            .WithMessage("Already exists an user with this email.");

            if (!IsValid(validator, user))
            {
                return(null);
            }

            var persisted = Get(user.Id);

            if (Notificator.HasErrors())
            {
                return(null);
            }

            persisted.Email     = user.Email;
            persisted.FirstName = user.FirstName;
            persisted.LastName  = user.LastName;
            persisted.Username  = user.Username;
            persisted.Roles     = user.Roles
                                  .Where(r => r.Id != Guid.Empty)
                                  .Select(r => UnitOfWork.Roles.Get(r.Id))
                                  .ToList();

            return(base.Update(persisted, ruleSets));
        }
Ejemplo n.º 3
0
        public override void Remove(Guid id)
        {
            if (UnitOfWork.Recipes.Search(r => r.UserId == id).Any())
            {
                Notify(NotificationType.ERROR, string.Empty, $"It's not possible to remove a {nameof(User)} with recipes");
                return;
            }

            var user = Get(id);

            if (Notificator.HasErrors())
            {
                return;
            }

            using var transaction = UnitOfWork.BeginTransaction();

            try
            {
                user.Roles.Clear();
                UnitOfWork.SaveChanges();

                UnitOfWork.Users.Remove(user);
                UnitOfWork.SaveChanges();

                transaction.Commit();
            }
            catch (Exception e)
            {
                transaction.Rollback();
                Logger.LogError(e.Message);
                Notify(NotificationType.ERROR, string.Empty, $"There was an error removing {nameof(User)}.");
            }
        }
Ejemplo n.º 4
0
        public override Food Update(Food entity, params string[] ruleSets)
        {
            if (UnitOfWork.Foods.Search(f => f.Name == entity.Name && f.Id != entity.Id).Any())
            {
                Notify(NotificationType.ERROR, "Name", "Already exists a food with this name.");
                return(null);
            }

            var food = UnitOfWork.Foods.Get(entity.Id);

            if (food == null)
            {
                Notify(NotificationType.ERROR, string.Empty, $"{nameof(Food)} not found.");
                return(null);
            }

            using var transaction = UnitOfWork.BeginTransaction();

            try
            {
                if (food.NutritionFacts != null)
                {
                    UnitOfWork.NutritionFactsNutrients.Remove(food.NutritionFacts.NutritionFactsNutrients);
                    UnitOfWork.NutritionFacts.Remove(food.NutritionFacts);
                }

                UnitOfWork.SaveChanges();

                if (entity.NutritionFacts != null)
                {
                    food.NutritionFacts = UnitOfWork.NutritionFacts.Add(entity.NutritionFacts);
                }

                food.Name = entity.Name;

                food = base.Update(food, ruleSets);

                if (Notificator.HasErrors())
                {
                    transaction.Rollback();
                    return(null);
                }

                UnitOfWork.SaveChanges();
                transaction.Commit();
            }
            catch (Exception e)
            {
                transaction.Rollback();
                Logger.LogError(e.Message);
                Notify(NotificationType.ERROR, string.Empty, $"There was an error updating {nameof(Food)}.");

                return(null);
            }

            return(Get(food.Id));
        }
Ejemplo n.º 5
0
        public override Recipe Add(Recipe entity, params string[] ruleSets)
        {
            ruleSets.Append("MassVolumeConflict");
            ruleSets.Append("default");

            var add = base.Add(entity, ruleSets);

            if (Notificator.HasErrors())
            {
                return(null);
            }

            return(GetDetailed(add.Id));
        }
Ejemplo n.º 6
0
        public override Food Add(Food entity, params string[] ruleSets)
        {
            if (UnitOfWork.Foods.Search(f => f.Name == entity.Name).Any())
            {
                Notify(NotificationType.ERROR, "Name", "Already exists a food with this name.");
                return(null);
            }

            var food = base.Add(entity, ruleSets);

            if (Notificator.HasErrors())
            {
                return(null);
            }

            return(Get(food.Id));
        }
Ejemplo n.º 7
0
        public User UpdatePassword(Guid id, string oldPassword, string newPassword)
        {
            var user = UnitOfWork.Users.Get(id);

            if (Notificator.HasErrors())
            {
                return(null);
            }

            var hasher = new PasswordHasher <User>();
            var verify = hasher.VerifyHashedPassword(user, user.Password, oldPassword);

            if (PasswordVerificationResult.Failed == verify)
            {
                Notify(NotificationType.ERROR, string.Empty, "Old password is invalid.");
                return(null);
            }

            user.Password = hasher.HashPassword(user, newPassword);

            return(base.Update(user, "default"));
        }
Ejemplo n.º 8
0
        public override void Remove(Guid id)
        {
            var food = Get(id);

            if (Notificator.HasErrors())
            {
                return;
            }

            if (UnitOfWork.Ingredients.Search(i => i.FoodId == food.Id).Any())
            {
                Notify(NotificationType.ERROR, string.Empty, "It is not possible to delete foods that belong to recipes.");
                return;
            }

            using var transaction = UnitOfWork.BeginTransaction();

            try
            {
                if (food.NutritionFacts != null)
                {
                    UnitOfWork.NutritionFactsNutrients.Remove(food.NutritionFacts.NutritionFactsNutrients);
                    UnitOfWork.NutritionFacts.Remove(food.NutritionFacts);
                }

                UnitOfWork.Foods.Remove(food);

                UnitOfWork.SaveChanges();
                transaction.Commit();
            }
            catch (Exception e)
            {
                transaction.Rollback();
                Logger.LogError(e.Message);
                Notify(NotificationType.ERROR, string.Empty, $"There was an error removing '{nameof(Food)}'.");
            }
        }
Ejemplo n.º 9
0
        public override Recipe Update(Recipe entity, params string[] ruleSets)
        {
            ruleSets.Append("MassVolumeConflict");
            ruleSets.Append("default");

            var recipe = GetDetailed(entity.Id);

            using var transaction = UnitOfWork.BeginTransaction();

            try
            {
                // Remove modo de preparo e ingredientes
                if (recipe.Preparation != null)
                {
                    UnitOfWork.PreparationSteps.Remove(recipe.Preparation.Steps);
                    UnitOfWork.Preparations.Remove(recipe.Preparation);
                }

                UnitOfWork.Ingredients.Remove(recipe.Ingredients);
                UnitOfWork.SaveChanges();

                // Cria novo modo de preparo e ingredientes
                if (entity.Preparation != null)
                {
                    recipe.Preparation = UnitOfWork.Preparations.Add(entity.Preparation);
                }

                if (entity.Ingredients != null)
                {
                    foreach (var ingredient in entity.Ingredients)
                    {
                        recipe.Ingredients.Add(UnitOfWork.Ingredients.Add(ingredient));
                    }
                }

                recipe.Name     = entity.Name;
                recipe.Servings = entity.Servings;

                // Valida e atualiza
                recipe = base.Update(recipe, ruleSets);

                if (Notificator.HasErrors())
                {
                    transaction.Rollback();
                    return(null);
                }

                UnitOfWork.SaveChanges();
                transaction.Commit();
            }
            catch (Exception e)
            {
                transaction.Rollback();
                Logger.LogError(e.Message);
                Notify(NotificationType.ERROR, string.Empty, $"There was an error removing {nameof(Recipe)}.");

                return(null);
            }

            return(recipe);
        }
Ejemplo n.º 10
0
        public Recipe CalculateAnonymousRecipe(Recipe recipe)
        {
            var recipeNutritionFacts     = new NutritionFacts();
            var recipeNutritionFactsRows = new List <NutritionFactsNutrients>();

            foreach (var ingredient in recipe.Ingredients)
            {
                var food = _foodService.Get(ingredient.FoodId);

                if (Notificator.HasErrors())
                {
                    return(null);
                }

                if (food.NutritionFacts == null)
                {
                    continue;
                }

                ingredient.Food = food;

                if (!IsValid(new IngredientValidator(_localizer), ingredient, "MassVolumeConflict"))
                {
                    return(null);
                }

                var foodServingSize     = food.NutritionFacts.ServingSize;
                var foodServingSizeUnit = food.NutritionFacts.ServingSizeUnit;

                var quantity             = 0.0;
                var ingredientProportion = 0.0;

                switch (ingredient.QuantityUnit)
                {
                case Measures.g:
                case Measures.mg:
                case Measures.kg:
                    quantity             = UnitConverter.ConvertByAbbreviation(ingredient.Quantity, "Mass", Enum.GetName(typeof(Measures), ingredient.QuantityUnit), G);
                    foodServingSize      = UnitConverter.ConvertByAbbreviation(foodServingSize, "Mass", Enum.GetName(typeof(Measures), foodServingSizeUnit), G);
                    ingredientProportion = quantity / foodServingSize;
                    break;

                case Measures.L:
                case Measures.ml:
                    quantity             = UnitConverter.ConvertByAbbreviation(ingredient.Quantity, "Volume", Enum.GetName(typeof(Measures), ingredient.QuantityUnit), L);
                    foodServingSize      = UnitConverter.ConvertByAbbreviation(foodServingSize, "Volume", Enum.GetName(typeof(Measures), foodServingSizeUnit), L);
                    ingredientProportion = quantity / foodServingSize;
                    break;

                case Measures.un:
                    quantity             = ingredient.Quantity;
                    ingredientProportion = quantity;
                    break;

                default:
                    Notify(NotificationType.ERROR, string.Empty, "Invalid unit of measurement.");
                    return(null);
                }

                ingredientProportion /= recipe.Servings;

                recipeNutritionFacts.DailyValue    += food.NutritionFacts.DailyValue * ingredientProportion;
                recipeNutritionFacts.ServingEnergy += food.NutritionFacts.ServingEnergy * ingredientProportion;

                foreach (var nfn in food.NutritionFacts.NutritionFactsNutrients)
                {
                    var recipeNfn = recipeNutritionFactsRows.FirstOrDefault(x => x.Nutrient.Id == nfn.Nutrient.Id);

                    if (recipeNfn != null)
                    {
                        recipeNfn.AmountPerServing += nfn.AmountPerServing * ingredientProportion;
                        recipeNfn.DailyValue       += nfn.DailyValue * ingredientProportion;
                    }
                    else
                    {
                        recipeNutritionFactsRows.Add(new NutritionFactsNutrients
                        {
                            AmountPerServing     = nfn.AmountPerServing * ingredientProportion,
                            DailyValue           = nfn.DailyValue * ingredientProportion,
                            AmountPerServingUnit = nfn.AmountPerServingUnit,
                            Nutrient             = nfn.Nutrient,
                            NutrientId           = nfn.NutrientId
                        });
                    }
                }
            }

            recipe.NutritionFacts = recipeNutritionFacts;
            recipe.NutritionFacts.NutritionFactsNutrients = recipeNutritionFactsRows;

            return(recipe);
        }