Example #1
0
        public Result <Maybe <PizzaDto> > Update(int id, PizzaDto pizza)
        {
            try
            {
                var pizzaDb = _context.Pizzas.SingleOrDefault(p => p.Id == id);
                if (pizzaDb == null)
                {
                    return(Result.Success(_mapper.Map <Maybe <PizzaDto> >(null)));
                }

                pizzaDb.Name  = pizza.Name;
                pizzaDb.Price = pizza.Price;

                _context.SaveChanges();

                return(Result.Success(_mapper.Map <Maybe <PizzaDto> >(pizzaDb)));
            }
            catch (SqlException ex)
            {
                return(Result.Failure <Maybe <PizzaDto> >(ex.Message));
            }
            catch (DbUpdateException ex)
            {
                return(Result.Failure <Maybe <PizzaDto> >(ex.Message));
            }
        }
        public long CreateSavedPizza(long userId, PizzaDto pizzaDto)
        {
            return(UseDb(uow =>
            {
                var ingredientItems = pizzaDto.Ingredients.Select(x => new IngredientItem
                {
                    IngredientId = x.Id,
                    Quantity = x.Quantity
                }).ToList();

                foreach (var item in ingredientItems)
                {
                    uow.IngredientItems.Create(item);
                }

                uow.Save();

                var entity = new SavedPizza
                {
                    FixPizzaId = pizzaDto.BasePizzaId,
                    UserId = userId,
                    Name = pizzaDto.Name,
                    IngredientItems = ingredientItems,
                };

                uow.SavedPizzas.Create(entity);

                uow.Save();

                return entity.Id;
            }));
        }
        public PizzaDto RemoveToppingFromPizza(int pizza_id, int ingredient_id)
        {
            Ingredient test_ingredient = _dbQueries.GetIngredientById(ingredient_id);

            _dbQueries.DeleteToppingFromPizza(pizza_id, ingredient_id);
            PizzaDto return_pizza = GetOnePizza(pizza_id);

            return(return_pizza);
        }
Example #4
0
        public IHttpActionResult Update(int id, [FromBody] PizzaDto pizza)
        {
            var result = _pizzaService.Update(id, pizza);

            if (result.IsFailure)
            {
                return(StatusCode(HttpStatusCode.InternalServerError));
            }

            return(result.Value.HasNoValue ? (IHttpActionResult)NotFound() : Ok(result.Value.Value));
        }
Example #5
0
        public IHttpActionResult Add([FromBody, CustomizeValidator(RuleSet = "PreValidator")] PizzaDto pizza)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = _pizzaService.Add(pizza);

            return(result.IsSuccess ?
                   Created($"api/pizzas/{result.Value.Id}", result.Value) :
                   (IHttpActionResult)BadRequest(result.Error));
        }
Example #6
0
        //public PizzaDto GetPizza(Guid? id, string userFk)
        //{

        //    using (var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
        //    {
        //        PizzaDto pizza = db.Users.FirstOrDefault(x => x.Id == userFk)
        //                    .Pizzas.ToList().Where(x => x.PizzaId == id).Select(p => p.toPizzaDto()).FirstOrDefault();
        //        if(pizza == null)
        //        {
        //            pizza = GetPizzasFromUsersWithRole(UserRoles.Owner).Where(x => x.PizzaId == id).FirstOrDefault();
        //        }
        //        if (pizza != null)
        //        {
        //            return pizza;
        //        }
        //        else
        //        {
        //            throw new Exception();
        //        }
        //    }
        //}

        public PizzaDto GetPizza(Guid?id)
        {
            PizzaDto pizza = db.Pizzas.Find(id).toPizzaDto();

            if (pizza != null)
            {
                return(pizza);
            }
            else
            {
                throw new Exception();
            }
        }
Example #7
0
        public async Task <Result <PizzaDto> > GetPizzaAsync(Guid pizzaUid)
        {
            PizzaDto pizzaDto = await(from dbPizza in AllNoTrackedOf <Pizza>()
                                      where dbPizza.Uid == pizzaUid
                                      select dbPizza.ToPizzaDto())
                                .SingleOrDefaultAsync();

            if (pizzaDto == null)
            {
                return(Result.NotFound <PizzaDto>(ResultErrorCodes.PIZZA_NOT_FOUND));
            }

            return(Result.Ok(pizzaDto));
        }
Example #8
0
        public PizzaDto SavePizza([FromBody] PizzaDto pizza)
        {
            PizzaDto oldPizza = _pizzaService.GetPizza(pizza.Id);

            if (oldPizza != null)
            {
                if (oldPizza.ImgPath != null && oldPizza.ImgPath != "" && oldPizza.ImgPath != pizza.ImgPath)
                {
                    string fullPath = _config["Image:Path"] + oldPizza.ImgPath;
                    System.IO.File.Delete(fullPath);
                }
            }
            return(_pizzaService.SavePizza(pizza));
        }
Example #9
0
        public PizzaDto GetPizza(int id)
        {
            if (id == 0)
            {
                PizzaDto newPizza = new PizzaDto();
                newPizza.Prices      = new List <PriceDto>();
                newPizza.Ingredients = new List <IngredientDto>();
                newPizza.ImgPath     = "";
                return(newPizza);
            }
            Pizza pizza = _pizzaRepository.GetPizza(id);

            return(ConvertPizza(pizza));
        }
Example #10
0
        public Result <PizzaDto> Add(PizzaDto pizza)
        {
            try
            {
                var pizzaDb = _mapper.Map <PizzaDb>(pizza);

                _context.Pizzas.Add(pizzaDb);
                _context.SaveChanges();

                return(Result.Success(_mapper.Map <PizzaDto>(pizzaDb)));
            }
            catch (DbUpdateException ex)
            {
                return(Result.Failure <PizzaDto>(ex.Message));
            }
        }
Example #11
0
        public IHttpActionResult Add([CustomizeValidator(RuleSet = "PreValidation")] PizzaDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var result = _pizzaService.Add(model);
            var url    = Url.Link("GetPizzaById", new { id = result.Value.Id });

            var ctx = GlobalHost.ConnectionManager.GetHubContext <PizzaShop.Web.Hubs.PizzaHub>();

            ctx.Clients.All.PizzaAdded(model);

            return(result.IsSuccess ? Created(url, result.Value) : (IHttpActionResult)BadRequest(result.Error));
        }
Example #12
0
        public void Update(PizzaDto model)
        {
            //var dbModel = _context.Pizzas.Find(model.Id); //SELECT
            //dbModel.Name = model.Name;
            //dbModel.Price = model.Price;
            var dbModel = _mapper.Map <PizzaDb>(model);

            _context.Pizzas.Attach(dbModel);
            var entry = _context.Entry(dbModel);

            // global state
            //entry.State = System.Data.Entity.EntityState.Modified;
            entry.Property(x => x.Name).IsModified  = true;
            entry.Property(x => x.Price).IsModified = true;

            _context.SaveChanges(); //UPDATE
        }
Example #13
0
        public Result <PizzaDto> Add(PizzaDto model)
        {
            try
            {
                var dbModel = _mapper.Map <PizzaDb>(model);

                _context.Pizzas.Add(dbModel);
                _context.SaveChanges();

                model.Id = dbModel.Id;
                return(Result.Success(model));
            }
            catch (DbUpdateException ex)
            {
                return(Result.Failure <PizzaDto>(ex.Message));
            }
        }
        // PUT /api/pizza/5
        public string Put(int id, PizzaDto pizzaDto)
        {
            // pesquisa a pizza no banco de dados
            // limpa seus filhos
            // e salva...
            var pizzaAlterar = _pizzaServico.GetById(id);

            pizzaAlterar.Name = pizzaDto.Name;

            var ingredientesJaExistiam = pizzaAlterar.Ingredients;
            var ingredienteChegando    = pizzaDto.Ingredients;

            AlterarListaManyToMany(ingredienteChegando, ingredientesJaExistiam);

            _pizzaServico.Save(pizzaAlterar);

            return("Pizza [" + pizzaAlterar.Id + "] salva com sucesso!");
        }
Example #15
0
        private PizzaDto ConvertPizza(Pizza pizza)
        {
            PizzaDto convertedPizza = new PizzaDto
            {
                Id          = pizza.Id,
                Name        = pizza.Name,
                Description = pizza.Description,
                ImgPath     = pizza.ImgPath,
                Prices      = pizza.Prices.ToList().ConvertAll(ConverPrice)
            };

            convertedPizza.Ingredients = new List <PizzaIngredientDto>();
            foreach (PizzaIngredient pizzaIngredient in pizza.PizzaIngredients)
            {
                convertedPizza.Ingredients.Add(ConvertIngredient(pizzaIngredient.Ingredient));
            }
            return(convertedPizza);
        }
        public PizzaDto GetOnePizza(int pizza_id)
        {
            //get pizza
            Pizza found_pizza = _dbQueries.GetPizzaById(pizza_id);

            //format pizza dto
            PizzaDto          found_pizza_dto = _mapper.Map <PizzaDto>(found_pizza);
            List <Ingredient> ingredients     = _dbQueries.GetIngredientForPizza(pizza_id);

            //convert each ingredient to ingredient dto
            List <IngredientDto> ingredient_dtos = new List <IngredientDto>();

            foreach (Ingredient ingredient in ingredients)
            {
                ingredient_dtos.Add(_mapper.Map <IngredientDto>(ingredient));
            }

            found_pizza_dto.ingredients = ingredient_dtos;
            return(found_pizza_dto);
        }
        // POST /api/pizza
        public string Post(PizzaDto pizzaDto)
        {
            var pizzaIncluir = new Pizza();

            pizzaIncluir.Name        = pizzaDto.Name;
            pizzaIncluir.Ingredients = new List <Ingredient>();
            _pizzaServico.Save(pizzaIncluir);

            if (pizzaDto.Ingredients != null)
            {
                foreach (var ingredienteDto in pizzaDto.Ingredients)
                {
                    var ingrediente = _ingredienteServico.GetById(ingredienteDto.Id);
                    pizzaIncluir.AddIngredient(ingrediente);
                }
            }

            _pizzaServico.Save(pizzaIncluir);
            return("Pizza [" + pizzaIncluir.Id + "] incluída com sucesso!");
        }
Example #18
0
        public IList <PizzaDto> ListarPizzas()
        {
            var listaPizzas = db.PIZZAS.Include(a => a.SABORES)
                              .Include(b => b.TAMANHOS)
                              .Include(c => c.PIZZA_ADICIONAIS);

            var listaPizzasDto = new List <PizzaDto>();

            foreach (var item in listaPizzas)
            {
                var pizzaDto = new PizzaDto()
                {
                    Identificador = item.ID,
                    Sabor         = item.SABORES.DESCRICAO,
                    Tamanho       = item.TAMANHOS.DESCRICAO,
                    Adicionais    = item.PIZZA_ADICIONAIS.Select(r => r.ADICIONAIS.DESCRICAO).ToList()
                };
                listaPizzasDto.Add(pizzaDto);
            }
            return(listaPizzasDto);
        }
Example #19
0
        public IHttpActionResult SelecionarPizza(int id)
        {
            if (!db.PIZZAS.Any(r => r.ID == id))
            {
                return(BadRequest("Pizza informada inválida."));
            }

            var pizza = db.PIZZAS.Include(a => a.SABORES)
                        .Include(b => b.TAMANHOS)
                        .Include(c => c.PIZZA_ADICIONAIS)
                        .First(r => r.ID == id);

            var pizzaDto = new PizzaDto()
            {
                Identificador = pizza.ID,
                Sabor         = pizza.SABORES.DESCRICAO,
                Tamanho       = pizza.TAMANHOS.DESCRICAO,
                Adicionais    = pizza.PIZZA_ADICIONAIS.Select(r => r.ADICIONAIS.DESCRICAO).ToList()
            };

            return(Ok(pizzaDto));
        }
        public List <PizzaDto> GetAllPizzas()
        {
            //get pizzas
            List <Pizza> all_pizzas = _dbQueries.GetAllPizzas();

            //format dto
            List <PizzaDto> all_pizza_dtos = new List <PizzaDto>();

            foreach (Pizza pizza in all_pizzas)
            {
                PizzaDto             pizza_dto       = _mapper.Map <PizzaDto>(pizza);
                List <Ingredient>    ingredients     = _dbQueries.GetIngredientForPizza(pizza.pizza_id);
                List <IngredientDto> ingredient_dtos = new List <IngredientDto>();
                foreach (Ingredient ingredient in ingredients)
                {
                    ingredient_dtos.Add(_mapper.Map <IngredientDto>(ingredient));
                }
                pizza_dto.ingredients = ingredient_dtos;
                all_pizza_dtos.Add(pizza_dto);
            }
            return(all_pizza_dtos);
        }
Example #21
0
        public async Task <ActionResult <PizzaDto> > Post(PizzaDto pizzaDto)
        {
            var pizza = new Pizza()
            {
                Id            = pizzaDto.Id,
                Size          = pizzaDto.Size,
                Crust         = pizzaDto.Crust,
                Cheese        = pizzaDto.Cheese,
                Sauce         = pizzaDto.Sauce,
                PizzaToppings = pizzaDto.Toppings.Select(t => new PizzaTopping()
                {
                    PizzaId   = pizzaDto.Id,
                    ToppingId = t.Id
                }).ToList()
            };

            await context.AddAsync(pizza);

            await context.SaveChangesAsync();

            return(Ok());
        }
        public void AddToCart(Guid id, string size)
        {
            CartOrderDto cart;
            object       sessionCart = Session["cart"];

            PizzaDto pizzaToAdd = repository.GetPizza(id);

            pizzaToAdd.Size = size;

            if (sessionCart != null)
            {
                cart = (CartOrderDto)sessionCart;
                if (cart.Items.Any(item => item.Pizza.PizzaId == id && item.Pizza.Size == size))
                {
                    cart.Items.Find(x => x.Pizza.PizzaId == id && x.Pizza.Size == size).Quantity++;
                }
                else
                {
                    cart.Items.Add(new CartItemDto
                    {
                        Pizza    = pizzaToAdd,
                        Quantity = 1
                    });
                }
                Session["cart"] = cart;
            }
            else
            {
                cart = new CartOrderDto();
                cart.Items.Add(new CartItemDto
                {
                    Pizza    = pizzaToAdd,
                    Quantity = 1
                });
                Session["cart"] = cart;
            }
        }
Example #23
0
        public List <PizzaDto> GetPizzaAtPriceOrderIds(int[] ids)
        {
            List <PizzaDto> pizzas = new List <PizzaDto>();

            ids.ToList().ForEach(id => {
                OrderPrice orderPrice = _orderPriceRepository.GetItem(id);
                Price price           = _priceRepository.GetItem(orderPrice.PriceId);
                Pizza pizza           = _pizzaRepository.GetItem(price.PizzaId);
                PizzaDto foundPizza   = pizzas.Find(value => value.Id == pizza.Id);
                if (foundPizza != null)
                {
                    PriceDto priceDto = ConverPrice(price);
                    priceDto.Count    = orderPrice.Count;
                    foundPizza.Prices.Add(priceDto);
                }
                else
                {
                    PizzaDto pizzaDto             = ConvertPizza(pizza);
                    pizzaDto.Prices.First().Count = orderPrice.Count;
                    pizzas.Add(pizzaDto);
                }
            });
            return(pizzas);
        }
        public long CreateFixPizza(PizzaDto pizzaDto)
        {
            return(UseDb(uow =>
            {
                var entity = new FixPizza
                {
                    Name = pizzaDto.Name,
                    Price = pizzaDto.Price,
                    IngredientItems = pizzaDto.Ingredients
                                      .Select(x => new IngredientItem
                    {
                        IngredientId = x.Id,
                        Quantity = x.Quantity
                    })
                                      .ToList()
                };

                uow.FixPizzas.Create(entity);

                uow.Save();

                return entity.Id;
            }));
        }
        public PizzaDto GetPizzaById(PizzaType pizzaType, long pizzaId)
        {
            return(UseDb(uow =>
            {
                if (pizzaType == PizzaType.Fix)
                {
                    var entity = uow.FixPizzas.GetById(pizzaId);

                    var dto = new PizzaDto
                    {
                        Id = entity.Id,
                        Name = entity.Name,
                        Price = entity.Price,
                        PizzaType = PizzaType.Fix,
                        Ingredients = entity.IngredientItems.Select(i => new IngredientDto
                        {
                            Id = i.Ingredient.Id,
                            Name = i.Ingredient.Name,
                            Price = i.Ingredient.Price,
                            Weight = i.Ingredient.Weight,
                            Quantity = i.Quantity
                        }).ToList()
                    };

                    return dto;
                }
                else if (pizzaType == PizzaType.Saved)
                {
                    var entity = uow.SavedPizzas.GetById(pizzaId);

                    var dto = new PizzaDto
                    {
                        Id = entity.Id,
                        Name = entity.Name,
                        Price = entity.BasePizza.Price > entity.IngredientItems.Sum(i => i.Quantity * i.Ingredient.Price)
                                ? entity.BasePizza.Price
                                : entity.IngredientItems.Sum(i => i.Quantity * i.Ingredient.Price),
                        PizzaType = PizzaType.Saved,
                        Ingredients = entity.IngredientItems.Select(i => new IngredientDto
                        {
                            Id = i.Ingredient.Id,
                            Name = i.Ingredient.Name,
                            Price = i.Ingredient.Price,
                            Weight = i.Ingredient.Weight,
                            Quantity = i.Quantity
                        }).ToList()
                    };

                    return dto;
                }
                else if (pizzaType == PizzaType.Modified)
                {
                    var entity = uow.ModifiedPizzas.GetById(pizzaId);

                    decimal price = entity.BasePizza.Price;
                    // add price for each extra ingredient
                    var basePizzaIngredients = entity.BasePizza.IngredientItems.ToList();
                    foreach (var thisIngr in entity.IngredientItems)
                    {
                        var baseIngr = basePizzaIngredients.FirstOrDefault(x => x.IngredientId == thisIngr.IngredientId);
                        int thisCount = thisIngr.Quantity;
                        int baseCount = baseIngr?.Quantity ?? 0;
                        int extraIngredientsCount = thisCount > baseCount
                            ? thisCount - baseCount
                            : 0;

                        price += thisIngr.Ingredient.Price * extraIngredientsCount;
                    }

                    var dto = new PizzaDto
                    {
                        Id = entity.Id,
                        BasePizzaId = entity.FixPizzaId,
                        // Here should be entity.UserId which is not in the database yet
                        // UserId =
                        Name = $"{entity.BasePizza} (змінена)",
                        Price = price,
                        PizzaType = PizzaType.Modified,
                        Ingredients = entity.IngredientItems.Select(i => new IngredientDto
                        {
                            Id = i.Ingredient.Id,
                            Name = i.Ingredient.Name,
                            Price = i.Ingredient.Price,
                            Weight = i.Ingredient.Weight,
                            Quantity = i.Quantity
                        }).ToList()
                    };

                    return dto;
                }

                return null;
            }));
        }
Example #26
0
 public IHttpActionResult Update(int id, [FromBody] PizzaDto model)
 {
     _pizzaService.Update(model);
     return(StatusCode(HttpStatusCode.NoContent));
 }
Example #27
0
        public PizzaDto SavePizza(PizzaDto newPizza)
        {
            Pizza pizza = _pizzaRepository.GetPizza(newPizza.Id) ?? new Pizza {
            };

            pizza.Name        = newPizza.Name;
            pizza.Description = newPizza.Description;
            pizza.ImgPath     = newPizza.ImgPath;
            if (pizza.PizzaIngredients != null)
            {
                for (int i = 0; i < pizza.PizzaIngredients.Count; i++)
                {
                    IngredientDto ingredientData = newPizza.Ingredients.Find(value => value.Id == pizza.PizzaIngredients.ElementAt(i).Id);
                    if (ingredientData == null)
                    {
                        _pizzaIngredientRepository.Delete(pizza.PizzaIngredients.ElementAt(i).Id);
                    }
                    else
                    {
                        PizzaIngredient pizzaIngredient = _pizzaIngredientRepository.GetItem(pizza.PizzaIngredients.ElementAt(i).Id);
                        pizzaIngredient.IngredientId = ingredientData.Id;
                        pizzaIngredient.Ingredient   = null;
                        _pizzaIngredientRepository.Save(pizzaIngredient);
                    }
                }
            }
            if (pizza.Prices != null)
            {
                for (int i = 0; i < pizza.Prices.Count; i++)
                {
                    PriceDto priceData = newPizza.Prices.Find(value => value.Id == pizza.Prices.ElementAt(i).Id);
                    if (priceData == null)
                    {
                        _priceRepository.Delete(pizza.Prices.ElementAt(i).Id);
                    }
                    else
                    {
                        Price price = _priceRepository.GetItem(pizza.Prices.ElementAt(i).Id);
                        price.DoughThickness = priceData.DoughThickness;
                        price.Size           = priceData.Size;
                        price.Weight         = priceData.Weight;
                        price.Cost           = priceData.Cost;
                        _priceRepository.Save(price);
                    }
                }
            }
            pizza = _pizzaRepository.Save(pizza);
            foreach (IngredientDto ingredient in newPizza.Ingredients)
            {
                PizzaIngredient pizzaIngredient = null;
                if (pizza.PizzaIngredients != null)
                {
                    pizzaIngredient = pizza.PizzaIngredients.Where(value => value.IngredientId == ingredient.Id).FirstOrDefault();
                }
                if (pizzaIngredient == null)
                {
                    PizzaIngredient newPizzaIngredient = new PizzaIngredient
                    {
                        IngredientId = ingredient.Id,
                        PizzaId      = pizza.Id
                    };
                    _pizzaIngredientRepository.Save(newPizzaIngredient);
                }
            }
            foreach (PriceDto price in newPizza.Prices)
            {
                Price oldPrice = _priceRepository.GetItem(price.Id);
                if (oldPrice == null)
                {
                    Price newPrice = new Price
                    {
                        Id             = 0,
                        DoughThickness = price.DoughThickness,
                        Size           = price.Size,
                        Cost           = price.Cost,
                        Weight         = price.Weight,
                        PizzaId        = pizza.Id,
                    };
                    _priceRepository.Save(newPrice);
                }
            }
            pizza = _pizzaRepository.GetPizza(pizza.Id);
            return(ConvertPizza(pizza));
        }
        public PizzaDto UpdatePizza([FromBody] PizzaDto updated_pizza)
        {
            Pizza update_confirmation = _dbQueries.UpdatePizza(_mapper.Map <Pizza>(updated_pizza));

            return(_mapper.Map <PizzaDto>(GetOnePizza(update_confirmation.pizza_id)));
        }