Beispiel #1
0
        protected NewCartItem BuildNewCartItem(string productId, int quantity, decimal productPrice)
        {
            var catalogProductId = _fixture.Create <string>();

            var catalogProduct = new CatalogProduct
            {
                Id = catalogProductId
            };

            var cartProduct = new CartProduct(catalogProduct);

            cartProduct.ApplyPrices(new List <Price>()
            {
                new Price
                {
                    ProductId   = catalogProductId,
                    PricelistId = _fixture.Create <string>(),
                    List        = _fixture.Create <decimal>(),
                    MinQuantity = _fixture.Create <int>(),
                }
            }, GetCurrency());

            var newCartItem = new NewCartItem(productId, quantity)
            {
                Price       = productPrice,
                CartProduct = cartProduct
            };

            return(newCartItem);
        }
Beispiel #2
0
        public async Task <ActionResult <Cart> > CreateCart(NewCartItem newItem)
        {
            var cartItem = new CartItem
            {
                FlowerId = newItem.FlowerId
            };
            var exists = await _context.Carts.AnyAsync(a => a.CartNumber == newItem.CartNumber);

            if (exists)
            {
                var cart = await _context.Carts.FirstOrDefaultAsync(f => f.CartNumber == newItem.CartNumber);

                cart.CartItems.Add(cartItem);
                var flower = await _context.Flowers.FirstOrDefaultAsync(f => f.Id == cartItem.FlowerId);

                flower.NumberInStock--;
                await _context.SaveChangesAsync();

                return(cart);
            }
            else
            {
                var cart = new Cart();
                cart.CartItems.Add(cartItem);
                var flower = await _context.Flowers.FirstOrDefaultAsync(f => f.Id == cartItem.FlowerId);

                flower.NumberInStock--;
                await _context.Carts.AddAsync(cart);

                await _context.SaveChangesAsync();

                return(cart);
            }
        }
        public void AddItemAsync_ShouldThrow_IfQuantityLessOrEqualZero(int quantity)
        {
            // Arrange
            var productId   = _fixture.Create <string>();
            var newCartItem = new NewCartItem(productId, quantity);

            var shoppingCart = _fixture.Create <ShoppingCart>();

            shoppingCart.Items = Enumerable.Empty <LineItem>().ToList();

            _cartProductServiceMock
            .Setup(x => x.GetCartProductsByIdsAsync(It.IsAny <CartAggregate>(), new[] { productId }))
            .ReturnsAsync(new List <CartProduct>()
            {
                new CartProduct(new CatalogProduct())
            });

            // Act
            var aggregateAfterAddItem = aggregate.AddItemAsync(newCartItem).GetAwaiter().GetResult();

            // Assert
            aggregateAfterAddItem.ValidationErrors.Should().NotBeEmpty();
            aggregateAfterAddItem.ValidationErrors.Should().Contain(x => x.ErrorCode == "GreaterThanValidator");
            aggregateAfterAddItem.ValidationErrors.Should().Contain(x => x.ErrorCode == "NotNullValidator");
        }
        public CartItem AddCartItem(NewCartItem newItem, MailingList mailingList = null)
        {
            var addedAmount = newItem?.Quantity ?? 0;

            if (addedAmount < 1)
            {
                throw new ArgumentException(resources.GetResourceString("Kadena.Product.InsertedAmmountValueIsNotValid"));
            }

            var productDocument = DocumentHelper.GetDocument(newItem.DocumentId, new TreeProvider(MembershipContext.AuthenticatedUser));
            var productType     = productDocument.GetValue("ProductType", string.Empty);
            var isTemplatedType = ProductTypes.IsOfType(productType, ProductTypes.TemplatedProduct);

            var cartItem = ECommerceContext.CurrentShoppingCart.CartItems
                           .FirstOrDefault(i => i.SKUID == productDocument.NodeSKUID && i.GetValue("ChilliEditorTemplateID", Guid.Empty) == newItem.TemplateId);
            var isNew = false;

            if (cartItem == null)
            {
                isNew    = true;
                cartItem = isTemplatedType
                    ? CreateCartItem(productDocument, newItem.TemplateId)
                    : CreateCartItem(productDocument);
            }

            var existingAmountInCart = isNew ? 0 : cartItem.CartItemUnits;

            if (productType.Contains(ProductTypes.InventoryProduct))
            {
                EnsureInventoryAmount(productDocument, addedAmount, existingAmountInCart);
            }

            var isMailingType = ProductTypes.IsOfType(productType, ProductTypes.MailingProduct);

            if (isTemplatedType || isMailingType)
            {
                if (isMailingType)
                {
                    if (mailingList?.AddressCount != addedAmount)
                    {
                        throw new ArgumentException(resources.GetResourceString("Kadena.Product.InsertedAmmountValueIsNotValid"));
                    }
                    SetMailingList(cartItem, mailingList);
                }
                SetAmount(cartItem, addedAmount);
            }
            else
            {
                SetAmount(cartItem, addedAmount + existingAmountInCart);
            }

            SetArtwork(cartItem, productDocument.GetStringValue("ProductArtwork", string.Empty));

            RefreshPrice(cartItem, productDocument);
            SetCustomName(cartItem, newItem.CustomProductName);

            ShoppingCartItemInfoProvider.SetShoppingCartItemInfo(cartItem);

            return(GetShoppingCartItems().FirstOrDefault(i => i.Id == cartItem.CartItemID));
        }
Beispiel #5
0
        public async Task AddItemsAsync_ItemsExist_ShouldAddNewItems()
        {
            // Arrange
            var productId1   = _fixture.Create <string>();
            var newCartItem1 = new NewCartItem(productId1, 1);

            var productId2   = _fixture.Create <string>();
            var newCartItem2 = new NewCartItem(productId2, 2);

            var newCartItems = new List <NewCartItem>()
            {
                newCartItem1, newCartItem2
            };

            _cartProductServiceMock
            .Setup(x => x.GetCartProductsByIdsAsync(It.IsAny <CartAggregate>(), new[] { productId1, productId2 }))
            .ReturnsAsync(
                new List <CartProduct>()
            {
                new CartProduct(new CatalogProduct()
                {
                    Id = productId1, IsActive = true, IsBuyable = true
                }),
                new CartProduct(new CatalogProduct()
                {
                    Id = productId2, IsActive = true, IsBuyable = true
                }),
            });


            _mapperMock.Setup(m => m.Map <LineItem>(It.IsAny <object>())).Returns <object>((arg) =>
            {
                if (arg is CartProduct cartProduct)
                {
                    return(new LineItem()
                    {
                        ProductId = cartProduct.Id
                    });
                }

                return(null);
            });

            var cartAggregate = GetValidCartAggregate();

            cartAggregate.ValidationRuleSet = new string[] { "default" };
            cartAggregate.Cart.Items        = Enumerable.Empty <LineItem>().ToList();

            // Act
            var newAggregate = await cartAggregate.AddItemsAsync(newCartItems);

            // Assert
            cartAggregate.Cart.Items.Should().Contain(x => x.ProductId == newCartItem1.ProductId);
            cartAggregate.Cart.Items.Should().Contain(x => x.ProductId == newCartItem2.ProductId);
        }
        public async Task <BulkCartResult> Handle(AddCartItemsBulkCommand request, CancellationToken cancellationToken)
        {
            var result         = new BulkCartResult();
            var cartItemsToAdd = new List <NewCartItem>();

            // find missing skus
            var products = await FindProductsBySkuAsync(request);

            foreach (var item in request.CartItems)
            {
                var product = products.FirstOrDefault(x => x.Code == item.ProductSku);
                if (product != null)
                {
                    var newCartItem = new NewCartItem(product.Id, item.Quantity);
                    cartItemsToAdd.Add(newCartItem);
                }
                else
                {
                    var error = CartErrorDescriber.BulkInvalidProductError(nameof(CatalogProduct), item.ProductSku);
                    result.Errors.Add(error);
                }
            }

            // send Add to Cart command
            var command = new AddCartItemsCommand
            {
                CartId       = request.CartId,
                StoreId      = request.StoreId,
                CartType     = request.CartType,
                CartName     = request.CartName,
                UserId       = request.UserId,
                CurrencyCode = request.CurrencyCode,
                CultureName  = request.CultureName,
                CartItems    = cartItemsToAdd.ToArray(),
            };

            var cartAggregate = await _mediator.Send(command, cancellationToken);

            result.Cart = cartAggregate;

            // transform cart product unavaliable validation erorrs to human readable
            var lineItemErrors = cartAggregate.ValidationErrors
                                 .OfType <CartValidationError>()
                                 .Where(x => x.ObjectType == "CartProduct" && x.ErrorCode == "CART_PRODUCT_UNAVAILABLE")
                                 .Select(x =>
            {
                var sku   = products.FirstOrDefault(p => p.Id == x.ObjectId)?.Code ?? x.ObjectId;
                var error = CartErrorDescriber.BulkProductUnavailableError(nameof(CatalogProduct), sku);
                return(error);
            });

            result.Errors.AddRange(lineItemErrors);

            return(result);
        }
        public void AddItemAsync_ShouldThrowArgumentNullException_IfNewCartItemIsNull()
        {
            // Arrange
            NewCartItem newCartItem = null;

            // Act
            Action action = () => aggregate.AddItemAsync(newCartItem).GetAwaiter().GetResult();

            // Assert
            action.Should().ThrowExactly <ArgumentNullException>("NewCartItem is null");
        }
Beispiel #8
0
 private void MoqDefaultSetup(NewCartItem cartItem)
 {
     this.productApiConnectorMock
     .Setup(c => c.ProductExists(cartItem.ProductId))
     .Returns(true);
     this.productApiConnectorMock
     .Setup(c => c.GetStock(cartItem.ProductId))
     .Returns(cartItem.Quantity + 1);
     this.userApiMock
     .Setup(c => c.UserExists(cartItem.UserId))
     .Returns(true);
 }
        public async Task <IHttpActionResult> UpdateTemplate([FromBody] NewCartItem item)
        {
            var result = await _templateService.UpdateTemplate(item.TemplateId, item.CustomProductName, item.Quantity);

            if (result)
            {
                return(ResponseJson(result));
            }
            else
            {
                return(ErrorJson("Failed request. See logs for more information."));
            }
        }
Beispiel #10
0
        public async Task Throws_Invalid_Product_Async()
        {
            var cartItem = new NewCartItem(1, 2, 10);

            this.MoqDefaultSetup(cartItem);
            this.productApiConnectorMock
            .Setup(c => c.ProductExists(cartItem.ProductId))
            .Returns(false);
            var service = this.GetService();

            var exc = await Assert.ThrowsAsync <CartException>(
                () => service.AddCartItemAsync(cartItem));

            Assert.Equal(CartErrorCode.InvalidProduct, exc.ErrorCode);
        }
Beispiel #11
0
        public async Task Adds_CartItem_To_DataStore_Async()
        {
            var cartItem = new NewCartItem(1, 2, 10);

            this.MoqDefaultSetup(cartItem);

            var service = this.GetService();
            await service.AddCartItemAsync(cartItem);

            var userCart = await this.dataMock.GetUserCartAsync(cartItem.UserId);

            Assert.Equal(userCart.UserId, cartItem.UserId);
            Assert.Equal(1, userCart.Items.Count);
            Assert.Equal(userCart.Items[cartItem.ProductId].Quantity, cartItem.Quantity);
        }
Beispiel #12
0
        public async Task Throws_InsufficientStock_Async()
        {
            var cartItem = new NewCartItem(1, 2, 10);

            this.MoqDefaultSetup(cartItem);
            this.productApiConnectorMock
            .Setup(c => c.GetStock(cartItem.ProductId))
            .Returns(cartItem.Quantity - 1);
            var service = this.GetService();

            var exc = await Assert.ThrowsAsync <CartException>(
                () => service.AddCartItemAsync(cartItem));

            Assert.Equal(CartErrorCode.InsufficientStock, exc.ErrorCode);
        }
Beispiel #13
0
        public async Task Throws_InvalidUser_Async()
        {
            var cartItem = new NewCartItem(1, 2, 10);

            this.MoqDefaultSetup(cartItem);
            this.userApiMock
            .Setup(c => c.UserExists(cartItem.UserId))
            .Returns(false);
            var service = this.GetService();

            var exc = await Assert.ThrowsAsync <CartException>(
                () => service.AddCartItemAsync(cartItem));

            Assert.Equal(CartErrorCode.InvalidUser, exc.ErrorCode);
        }
        public async Task ValidateAddItem_RuleSetDefault_Valid()
        {
            // Arrange
            var validator   = new NewCartItemValidator();
            var newCartItem = new NewCartItem(Rand.Guid().ToString(), Rand.Int(1, InStockQuantity))
            {
                CartProduct = _fixture.Create <CartProduct>()
            };

            // Act
            var result = await validator.ValidateAsync(newCartItem, ruleSet : "default");

            // Assert
            result.IsValid.Should().BeTrue();
            result.Errors.Should().BeEmpty();
        }
Beispiel #15
0
        public async Task <AddToCartResult> AddToCart(NewCartItem item)
        {
            var mailingList = await mailingService.GetMailingList(item.ContainerId);

            var addedItem = shoppingCart.AddCartItem(item, mailingList);
            var result    = new AddToCartResult
            {
                CartPreview  = ItemsPreview(),
                Confirmation = new RequestResult
                {
                    AlertMessage = resources.GetResourceString("Kadena.Product.ItemsAddedToCart")
                }
            };

            return(result);
        }
        public async Task ValidateAddItem_RuleSetDefault_Invalid()
        {
            // Arrange
            var validator   = new NewCartItemValidator();
            var newCartItem = new NewCartItem(null, 0);

            // Act
            var result = await validator.ValidateAsync(newCartItem, ruleSet : "default");

            // Assert
            result.IsValid.Should().BeFalse();
            result.Errors.Should().NotBeEmpty();
            result.Errors.Should().HaveCount(3);
            result.Errors.Should().Contain(x => x.PropertyName == "Quantity" && x.ErrorCode == nameof(GreaterThanValidator));
            result.Errors.Should().Contain(x => x.PropertyName == "ProductId" && x.ErrorCode == nameof(NotNullValidator));
            result.Errors.Should().Contain(x => x.PropertyName == "CartProduct" && x.ErrorCode == nameof(NotNullValidator));
        }
Beispiel #17
0
        public async Task Throws_InsufficientStock_Cumulative_Async()
        {
            var cartItem      = new NewCartItem(1, 2, 2);
            var secondItem    = new NewCartItem(cartItem.UserId, cartItem.ProductId, 3);
            int totalQuantity = cartItem.Quantity + secondItem.Quantity;

            this.MoqDefaultSetup(cartItem);
            this.productApiConnectorMock
            .Setup(c => c.GetStock(cartItem.ProductId))
            .Returns(totalQuantity - 1);

            var service = this.GetService();
            await service.AddCartItemAsync(cartItem);

            var exc = await Assert.ThrowsAsync <CartException>(
                () => service.AddCartItemAsync(secondItem));

            Assert.Equal(CartErrorCode.InsufficientStock, exc.ErrorCode);

            var userCart = await this.dataMock.GetUserCartAsync(cartItem.UserId);

            Assert.Equal(userCart.Items[cartItem.ProductId].Quantity, cartItem.Quantity);
        }
Beispiel #18
0
        public async Task Increments_Quantity_When_Product_Exists()
        {
            var cartItem      = new NewCartItem(1, 2, 2);
            var secondItem    = new NewCartItem(cartItem.UserId, cartItem.ProductId, 3);
            int totalQuantity = cartItem.Quantity + secondItem.Quantity;

            this.MoqDefaultSetup(cartItem);
            this.productApiConnectorMock
            .Setup(c => c.GetStock(cartItem.ProductId))
            .Returns(totalQuantity + 1);

            var service = this.GetService();
            await service.AddCartItemAsync(cartItem);

            var userCart = await this.dataMock.GetUserCartAsync(cartItem.UserId);

            Assert.Equal(userCart.Items[cartItem.ProductId].Quantity, cartItem.Quantity);

            await service.AddCartItemAsync(secondItem);

            userCart = await this.dataMock.GetUserCartAsync(cartItem.UserId);

            Assert.Equal(userCart.Items[cartItem.ProductId].Quantity, totalQuantity);
        }