Beispiel #1
0
        public async Task <Guid> AddCartItem(AddProductToCartDto item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }
            var product = await _context.Products.FirstOrDefaultAsync(c => c.Id == item.ProductId);

            if (product == null)
            {
                throw new EntityNotFoundException($"Product with id:{item.ProductId} doesn't exist");
            }

            var cart = await GetCartById(item.CartId);

            if (cart == null)
            {
                cart = await CreateNewCart(item);
            }
            else
            {
                await AddItemToExistingCart(item, cart);
            }

            await _context.SaveChangesAsync();

            return(cart.CartId);
        }
Beispiel #2
0
        public async Task <IActionResult> Add(AddProductToCartDto productCartDto)
        {
            try
            {
                var cartId = await _cartCrudService.AddCartItem(productCartDto);

                return(Ok(cartId));
            }
            catch (ArgumentNullException e)
            {
                return(BadRequest(e.Message));
            }
            catch (EntityNotFoundException e)
            {
                return(BadRequest(e.Message));
            }
        }
Beispiel #3
0
        private async Task AddItemToExistingCart(AddProductToCartDto item, DataAccess.Entities.Cart cart)
        {
            var cartItem = cart.CartItems.FirstOrDefault(c => c.ProductId == item.ProductId);

            if (cartItem != null)
            {
                cartItem.Quantity++;
                _context.CartItems.Update(cartItem);
            }
            else
            {
                cartItem = new CartItem()
                {
                    CartId         = cart.Id,
                    ProductId      = item.ProductId,
                    ForBonusPoints = item.ForBonusPoints,
                    Quantity       = 1
                };
                await _context.CartItems.AddAsync(cartItem);
            }
        }
Beispiel #4
0
        private async Task <DataAccess.Entities.Cart> CreateNewCart(AddProductToCartDto item)
        {
            var cart = new DataAccess.Entities.Cart()
            {
                CartId = item.CartId
            };

            var result = await _context.Carts.AddAsync(cart);

            await _context.SaveChangesAsync();

            var cartItem = new CartItem()
            {
                CartId         = result.Entity.Id,
                ProductId      = item.ProductId,
                ForBonusPoints = item.ForBonusPoints,
                Quantity       = 1
            };

            await _context.CartItems.AddAsync(cartItem);

            return(cart);
        }