Esempio n. 1
0
        public async Task <ActionResult <ReturnCheckout> > AddBasket(BasketDTO basket)
        {
            //Check product exists
            var p = await _productRepo.GetProductById(basket.ProductId);

            if (p == null)
            {
                return(NotFound(new ErrorRes(404, "Product doesn't exist")));
            }
            //Find the User
            var user = await _userManager.FindByEmailFromClaimsPrinciple(HttpContext.User);

            if (user == null)
            {
                return(Unauthorized(new ErrorRes(401)));
            }
            //Check if user has the product or not
            var item = await _basketRepo.GetProductFromBasket(basket.ProductId, user.Id);

            if (item == null)
            {
                _basketGenericRepo.Add(new BasketItem {
                    Product  = p,
                    Quantity = basket.Quantity,
                    User     = user,
                });
            }
            //Update the basket item if exists
            else
            {
                item.Quantity = basket.Quantity;
                _basketGenericRepo.Update(item);
            }
            if (await _basketGenericRepo.SaveAll())
            {
                return(await GetBaskets());
            }
            return(BadRequest(new ErrorRes(400)));
        }
Esempio n. 2
0
        public async Task <ActionResult <Order> > CreateOrder()
        {
            var user = await _userManager.FindByEmailFromClaimsPrinciple(HttpContext.User);

            if (user == null)
            {
                return(Unauthorized(new ErrorRes(401)));
            }
            // get basket from the repo
            var basket = await _basketRepo.GetCarts(user.Id);

            var total = _basketRepo.GetTotal(basket);

            if (user.address == null)
            {
                return(Unauthorized(new ErrorRes(400, "You must fill your address to create an order")));
            }
            // create order items
            var items = new List <OrderItem>();

            foreach (var item in basket)
            {
                var orderItem = new OrderItem(item.Id, item.Product.Name, item.Product.PictureUrl, item.Product.Price, item.Quantity);
                items.Add(orderItem);
            }

            // create order
            var order = new Order(items, user.Email, user.address, total);

            //Add Order
            _orderGenericsRepo.Add(order);
            // save to db
            if (await _orderGenericsRepo.SaveAll())
            {
                return(Ok(_mapper.Map <Order, OrderReturnDTO>(order)));
            }
            return(BadRequest(new ErrorRes(400, "Problem creating order")));
        }