Esempio n. 1
0
        public override async Task <Cart> Run(Cart arg, CommercePipelineExecutionContext context)
        {
            _commerceContext = context.CommerceContext;

            var cartLine = context.CommerceContext.GetObject <CartLineArgument>();
            CartLineComponent addedLine = arg.Lines.FirstOrDefault(line => line.Id.EqualsOrdinalIgnoreCase(cartLine.Line.Id));

            if (addedLine == null)
            {
                return(arg);
            }

            SellableItem sellableItem = await getSellableItemCommand.Process(_commerceContext, addedLine.ItemId, false);

            var categoryComponent = addedLine.GetComponent <CategoryComponent>();

            if (sellableItem.ParentCategoryList != null && !categoryComponent.ParentCategoryList.Any())
            {
                foreach (string categoryId in sellableItem.ParentCategoryList.Split('|'))
                {
                    categoryComponent.ParentCategoryList.Add(await GetCategoryIdPath(categoryId, ""));
                }
            }

            return(arg);
        }
Esempio n. 2
0
        private CartLineComponent CreateLine(Cart cart, CommerceContext commerceContext, string targetItemId, decimal quantity)
        {
            SellableItem gift = AsyncHelper.RunSync(() => _getCommand.Process(commerceContext, targetItemId, false));

            if (gift == null)
            {
                return(null);
            }

            // To make sure all pipeline blocks are executed and do not influence the current cart, we add
            // the gift line to a temporary cart and then copy it to the current cart.
            var temporaryCart = cart.Clone <Cart>();

            temporaryCart.AddComponents(new TemporaryCartComponent(cart.Id));

            var freeGift = new CartLineComponent
            {
                ItemId   = targetItemId,
                Quantity = quantity
            };

            temporaryCart = AsyncHelper.RunSync(() => _addCommand.Process(commerceContext, temporaryCart, freeGift));

            CartLineComponent line = temporaryCart.Lines.Single(x => x.ItemId == targetItemId);

            if (gift.ListPrice.Amount > 0)
            {
                decimal discount = new MoneyEx(commerceContext, gift.ListPrice).Round().Value.Amount;

                line.Adjustments.Add(AwardedAdjustmentFactory.CreateLineLevelAwardedAdjustment(discount * -1,
                                                                                               nameof(CartFreeGiftAction), line.Id, commerceContext));
            }

            return(line);
        }
Esempio n. 3
0
        public async Task Run_UpdateIsGiftBoxToFalse_ShouldReturnCartLineWithIsGiftBoxEqualFalse()
        {
            var inputCart  = new Cart();
            var cartLineId = Guid.NewGuid().ToString();
            var cartLine   = new CartLineComponent()
            {
                Id       = cartLineId,
                ItemId   = TestSellableItemId,
                Quantity = 1
            };

            cartLine.SetComponent(new CartLineGiftBoxComponent()
            {
                IsGiftBox = true
            });
            inputCart.Lines.Add(cartLine);
            var cartLineGiftBoxArgument = new CartLineGiftBoxArgument(inputCart, cartLineId, false);

            var outputCart = await _pipelineBlock.Run(cartLineGiftBoxArgument, _pipelineContextFake);

            var cartLineGiftBoxComponent = outputCart.Lines
                                           .SingleOrDefault(l => l.Id == cartLineId)
                                           .GetComponent <CartLineGiftBoxComponent>();

            Assert.False(cartLineGiftBoxComponent.IsGiftBox);
        }
Esempio n. 4
0
        public async Task Run_UpdateIsGiftBoxToTrueForValidItem_ShouldReturnCartLineWithIsGiftBoxEqualTrue()
        {
            var inputCart  = new Cart();
            var cartLineId = Guid.NewGuid().ToString();
            var cartLine   = new CartLineComponent()
            {
                Id       = cartLineId,
                ItemId   = TestSellableItemId,
                Quantity = 1
            };

            cartLine.SetComponent(new CartLineGiftBoxComponent()
            {
                IsGiftBox = false
            });
            inputCart.Lines.Add(cartLine);
            var cartLineGiftBoxArgument      = new CartLineGiftBoxArgument(inputCart, cartLineId, true);
            var sellableItemValidForGiftWrap = new SellableItem();

            sellableItemValidForGiftWrap.AddComponent(null, new SellableItemGiftBoxComponent()
            {
                AllowGiftBox = true
            });
            _getSellableItemPipelineMock
            .Setup(p => p.Run(It.IsAny <ProductArgument>(), It.IsAny <CommercePipelineExecutionContext>()))
            .Returns(Task.FromResult(sellableItemValidForGiftWrap));

            var outputCart = await _pipelineBlock.Run(cartLineGiftBoxArgument, _pipelineContextFake);

            var cartLineGiftBoxComponent = outputCart.Lines
                                           .SingleOrDefault(l => l.Id == cartLineId)
                                           .GetComponent <CartLineGiftBoxComponent>();

            Assert.True(cartLineGiftBoxComponent.IsGiftBox);
        }
Esempio n. 5
0
        public static void DisplayCartLine(CartLineComponent cartLine)
        {
            System.Console.WriteLine($"\t Itemid: {cartLine.ItemId}");
            System.Console.WriteLine($"\t Qty: {cartLine.Quantity} List:{cartLine.UnitListPrice.Amount}  Sell:{cartLine.Policies.OfType<PurchaseOptionMoneyPolicy>().FirstOrDefault()?.SellPrice.Amount}");
            System.Console.WriteLine($"\t SubTotal: {cartLine.Totals.SubTotal.Amount} Adj:{cartLine.Totals.AdjustmentsTotal.Amount}  Grand:{cartLine.Totals.GrandTotal.Amount}");
            System.Console.WriteLine();

            if (cartLine.Adjustments.Count > 0)
            {
                System.Console.WriteLine("\t \t Line adjustments:");
                foreach (var adjustment in cartLine.Adjustments)
                {
                    System.Console.WriteLine($"\t \t \t Name: {adjustment.Name} \t Amount: {adjustment.Adjustment.Amount} ");
                }
            }
            else
            {
                System.Console.WriteLine("\t \t (NO Line adjustments)");
            }

            System.Console.WriteLine("\t \t Line components:");
            foreach (var component in cartLine.CartLineComponents)
            {
                System.Console.WriteLine($"\t \t \t {component.GetType().Name}");
            }

            System.Console.WriteLine();
        }
        public virtual async Task <Cart> Process(CommerceContext commerceContext, string wishlistId, string cartLineId)
        {
            CommerceContext   commerceContext1 = commerceContext;
            CartLineComponent line             = new CartLineComponent();

            line.Id = cartLineId;
            return(await this.Process(commerceContext1, wishlistId, line).ConfigureAwait(false));
        }
        public async void Should_benefit_multiple_times_when_within_action_limit()
        {
            fixture.Factory.ClearAllEntities();

            HttpClient client = fixture.Factory.CreateClient();

            Promotion promotion = await new PromotionBuilder()
                                  .QualifiedBy(new IsCurrentDayConditionBuilder()
                                               .Day(DateTime.Now.Day))
                                  .BenefitBy(new CartEveryXItemsInCategoryPriceDiscountActionBuilder()
                                             .AmountOff(10)
                                             .ForCategory("Laptops")
                                             .ItemsToAward(1)
                                             .ItemsToPurchase(2)
                                             .ApplyActionTo(ApplicationOrder.Ascending)
                                             .ActionLimit(2))
                                  .Build(fixture.Factory);

            fixture.Factory.AddEntityToList(promotion, CommerceEntity.ListName <Promotion>());
            fixture.Factory.AddEntity(promotion);

            fixture.Factory.AddEntity(new Category
            {
                Id         = "Laptops".ToEntityId <Category>(),
                SitecoreId = "435345345"
            });

            Cart cart = await new CartBuilder()
                        .WithLines(new LineBuilder().IdentifiedBy("001").Quantity(1).InCategory("435345345").Price(40),
                                   new LineBuilder().IdentifiedBy("002").Quantity(1).InCategory("435345345").Price(50),
                                   new LineBuilder().IdentifiedBy("003").Quantity(1).InCategory("435345345").Price(40),
                                   new LineBuilder().IdentifiedBy("004").Quantity(1).InCategory("435345345").Price(50))
                        .Build();

            fixture.Factory.AddEntity(cart);

            Cart resultCart =
                await client.GetJsonAsync <Cart>(
                    "api/Carts('Cart01')?$expand=Lines($expand=CartLineComponents($expand=ChildComponents)),Components");

            CartLineComponent firstLine  = resultCart.Lines.Single(x => x.Id == "001");
            AwardedAdjustment adjustment =
                firstLine.Adjustments.Single(x => x.AwardingBlock == nameof(CartEveryXItemsInCategoryPriceDiscountAction));

            Assert.Equal(-10, adjustment.Adjustment.Amount);

            CartLineComponent secondLine       = resultCart.Lines.Single(x => x.Id == "003");
            AwardedAdjustment secondAdjustment =
                secondLine.Adjustments.Single(x => x.AwardingBlock == nameof(CartEveryXItemsInCategoryPriceDiscountAction));

            Assert.Equal(-10, secondAdjustment.Adjustment.Amount);

            // Subtotal = 160, Tax is 10% = 16, Fulfillment fee = 5
            Assert.Equal(181, resultCart.Totals.GrandTotal.Amount);
        }
Esempio n. 8
0
        public async void Should_benefit()
        {
            fixture.Factory.ClearAllEntities();

            HttpClient client = fixture.Factory.CreateClient();

            Promotion promotion = await new PromotionBuilder()
                                  .QualifiedBy(new IsCurrentDayConditionBuilder()
                                               .Day(DateTime.Now.Day))
                                  .BenefitBy(new CartFreeGiftActionBuilder()
                                             .Quantity(1)
                                             .Gift("MyCatalog|999|"))
                                  .Build(fixture.Factory);

            var catalog = new Catalog
            {
                Id         = "Entity-Catalog-MyCatalog",
                FriendlyId = "MyCatalog",
                Name       = "MyCatalog"
            };

            SellableItem sellableItem = new SellableItemBuilder()
                                        .IdentifiedBy("001")
                                        .Priced(40)
                                        .Catalog("MyCatalog")
                                        .Build();

            SellableItem gift = new SellableItemBuilder()
                                .IdentifiedBy("999")
                                .Catalog("MyCatalog")
                                .Named("Free Gift")
                                .Priced(99)
                                .Build();

            Cart cart = await new CartBuilder()
                        .WithLines(new LineBuilder()
                                   .IdentifiedBy("001").WithProductId("MyCatalog|001|").Quantity(1).Price(40))
                        .Build();

            fixture.Factory.AddEntities(promotion, gift, sellableItem, catalog, cart);
            fixture.Factory.AddEntityToList(promotion, CommerceEntity.ListName <Promotion>());

            Cart resultCart =
                await client.GetJsonAsync <Cart>(
                    "api/Carts('Cart01')?$expand=Lines($expand=CartLineComponents($expand=ChildComponents)),Components");

            CartLineComponent giftLine = resultCart.Lines.Single(x => x.ItemId == "MyCatalog|999|");

            AwardedAdjustment adjustment = giftLine.Adjustments.Single(x => x.AwardingBlock == nameof(CartFreeGiftAction));

            Assert.Equal(-99, adjustment.Adjustment.Amount);

            // Subtotal = 40, Tax is 10% = 4, Fulfillment fee = 5
            Assert.Equal(49, resultCart.Totals.GrandTotal.Amount);
        }
Esempio n. 9
0
 protected override void Translate(TranslateCartLineToEntityRequest request, CartLineComponent source,
                                   CommerceCartLine destination)
 {
     base.Translate(request, source, destination);
     destination.ExternalCartLineId = source.Id;
     destination.Quantity           = source.Quantity;
     TranslateProduct(request, source, destination);
     TranslateAdjustments(request, source, destination);
     TranslateTotals(request, source, destination);
     TranslateBlockchainInfo(request, source, destination);
 }
        public override Task <Cart> Run(Cart arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull("The cart argument can not be null");

            var cartLine = context.CommerceContext.GetObjects <CartLineArgument>().First();
            CartLineComponent addedLine = arg.Lines.FirstOrDefault <CartLineComponent>(line => line.Id.Equals(cartLine.Line.Id, StringComparison.OrdinalIgnoreCase));

            var loyalty = addedLine.GetComponent <LoyaltyComponent>();

            loyalty.PointsEarned = (int)addedLine.Totals.SubTotal.Amount;
            return(Task.FromResult(arg));
        }
        public virtual void Process(CommerceContext commerceContext, CartLineComponent cartLineComponent, bool autoRemove)
        {
            if (!autoRemove && cartLineComponent.UnitListPrice.Amount != 0.0m)
            {
                return;
            }

            var propertiesModel = commerceContext.GetObject <PropertiesModel>();
            var freeGiftEligibilityComponent = cartLineComponent.GetComponent <FreeGiftAutoRemoveComponent>();

            freeGiftEligibilityComponent.PromotionId = propertiesModel?.GetPropertyValue("PromotionId") as string;
        }
Esempio n. 12
0
        public async void Should_match_operator(Operator @operator, int numberOfProductsInPromotion, int numberOfProductsInCart,
                                                bool shouldQualify)
        {
            fixture.Factory.ClearAllEntities();

            HttpClient client = fixture.Factory.CreateClient();

            Promotion promotion = await new PromotionBuilder()
                                  .QualifiedBy(new IsCurrentDayConditionBuilder()
                                               .Day(DateTime.Now.Day))
                                  .BenefitBy(new CartItemsMatchingInCategoryPercentageDiscountActionBuilder()
                                             .PercentageOff(50)
                                             .ForCategory("Laptops")
                                             .Operator(@operator)
                                             .NumberOfProducts(numberOfProductsInPromotion)
                                             .ApplyActionTo(ApplicationOrder.Ascending)
                                             .ActionLimit(numberOfProductsInPromotion))
                                  .Build(fixture.Factory);

            fixture.Factory.AddEntityToList(promotion, CommerceEntity.ListName <Promotion>());
            fixture.Factory.AddEntity(promotion);

            fixture.Factory.AddEntity(new Category
            {
                Id         = "Laptops".ToEntityId <Category>(),
                SitecoreId = "435345345"
            });

            Cart cart = await new CartBuilder()
                        .WithLines(new LineBuilder()
                                   .IdentifiedBy("001").Quantity(numberOfProductsInCart).InCategory("435345345").Price(40))
                        .Build();

            fixture.Factory.AddEntity(cart);

            Cart resultCart =
                await client.GetJsonAsync <Cart>(
                    "api/Carts('Cart01')?$expand=Lines($expand=CartLineComponents($expand=ChildComponents)),Components");

            CartLineComponent line = resultCart.Lines.Single(x => x.Id == "001");

            if (shouldQualify)
            {
                Assert.Contains(line.Adjustments,
                                x => x.AwardingBlock == nameof(CartItemsMatchingInCategoryPercentageDiscountAction));
            }
            else
            {
                Assert.DoesNotContain(line.Adjustments,
                                      x => x.AwardingBlock == nameof(CartItemsMatchingInCategoryPercentageDiscountAction));
            }
        }
Esempio n. 13
0
        private Cart CreateInputCart(string cartLineId)
        {
            var cart     = new Cart(TestCartId);
            var cartLine = new CartLineComponent()
            {
                Id       = cartLineId,
                ItemId   = TestSellableItemId,
                Quantity = 1
            };

            cart.Lines.Add(cartLine);
            return(cart);
        }
Esempio n. 14
0
        protected virtual void TranslateBlockchainInfo(TranslateCartLineToEntityRequest request,
                                                       CartLineComponent source, CommerceCartLine destination)
        {
            var blokchainTokenComponent =
                source.CartLineComponents.FirstOrDefault(c => c is DigitalDownloadBlockchainTokenComponent) as
                DigitalDownloadBlockchainTokenComponent;

            if (blokchainTokenComponent == null)
            {
                return;
            }
            destination.SetPropertyValue(Constants.BlockchainDownloadToken,
                                         blokchainTokenComponent.BlockchainDownloadToken);
        }
Esempio n. 15
0
        public async void Should_benefit_in_descending_order_when_category_matches()
        {
            fixture.Factory.ClearAllEntities();

            HttpClient client = fixture.Factory.CreateClient();

            Promotion promotion = await new PromotionBuilder()
                                  .QualifiedBy(new IsCurrentDayConditionBuilder()
                                               .Day(DateTime.Now.Day))
                                  .BenefitBy(new CartItemsMatchingInCategoryPercentageDiscountActionBuilder()
                                             .PercentageOff(50)
                                             .ForCategory("Laptops")
                                             .Operator(Operator.Equal)
                                             .NumberOfProducts(2)
                                             .ApplyActionTo(ApplicationOrder.Descending)
                                             .ActionLimit(1))
                                  .Build(fixture.Factory);

            fixture.Factory.AddEntityToList(promotion, CommerceEntity.ListName <Promotion>());
            fixture.Factory.AddEntity(promotion);

            fixture.Factory.AddEntity(new Category
            {
                Id         = "Laptops".ToEntityId <Category>(),
                SitecoreId = "435345345"
            });

            Cart cart = await new CartBuilder()
                        .WithLines(new LineBuilder().IdentifiedBy("001").Quantity(1).InCategory("435345345").Price(40),
                                   new LineBuilder().IdentifiedBy("002").Quantity(1).InCategory("435345345").Price(50))
                        .Build();

            fixture.Factory.AddEntity(cart);

            Cart resultCart =
                await client.GetJsonAsync <Cart>(
                    "api/Carts('Cart01')?$expand=Lines($expand=CartLineComponents($expand=ChildComponents)),Components");

            CartLineComponent line       = resultCart.Lines.Single(x => x.Id == "002");
            AwardedAdjustment adjustment = line.Adjustments.Single(x =>
                                                                   x.AwardingBlock ==
                                                                   nameof(CartItemsMatchingInCategoryPercentageDiscountAction));

            Assert.Equal(-25, adjustment.Adjustment.Amount);

            // Subtotal = 65, Tax is 10% = 6.5, Fulfillment fee = 5
            Assert.Equal(76.5m, resultCart.Totals.GrandTotal.Amount);
        }
Esempio n. 16
0
        private int GetPoints(CartLineComponent line)
        {
            if (!line.HasComponent <LoyaltyPointsComponent>())
            {
                return(0);
            }

            var loyaltyPoints = line.GetComponent <LoyaltyPointsComponent>();

            if (loyaltyPoints.HasComponent <Applied>())
            {
                return(0);
            }

            loyaltyPoints.SetComponent(new Applied());

            return((int)Math.Floor(line.Quantity * loyaltyPoints.Points));
        }
        public override async Task <Cart> Run(CartLineArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires <CartLineArgument>(arg).IsNotNull <CartLineArgument>("The argument can not be null");
            Condition.Requires <Cart>(arg.Cart).IsNotNull <Cart>("The cart can not be null");
            Condition.Requires <CartLineComponent>(arg.Line).IsNotNull <CartLineComponent>("The lines can not be null");
            Cart cart = arg.Cart;
            List <CartLineComponent> lines        = cart.Lines.ToList <CartLineComponent>();
            CartLineComponent        existingLine = lines.FirstOrDefault <CartLineComponent>((Func <CartLineComponent, bool>)(l => l.Id.Equals(arg.Line.Id, StringComparison.OrdinalIgnoreCase)));

            if (existingLine != null)
            {
                string str = await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Information, (string)null, (object[])null, string.Format("Removed Line '{0}' from Cart '{1}'.", (object)existingLine.Id, (object)cart.Id));

                lines.Remove(existingLine);
            }
            cart.Lines = (IList <CartLineComponent>)lines;
            return(cart);
        }
Esempio n. 18
0
        public async void Should_not_benefit_when_category_does_not_match()
        {
            fixture.Factory.ClearAllEntities();

            HttpClient client = fixture.Factory.CreateClient();

            Promotion promotion = await new PromotionBuilder()
                                  .QualifiedBy(new IsCurrentDayConditionBuilder()
                                               .Day(DateTime.Now.Day))
                                  .BenefitBy(new CartEveryXItemsInCategoryPercentageDiscountActionBuilder()
                                             .PercentageOff(50)
                                             .ForCategory("Laptops")
                                             .ItemsToAward(1)
                                             .ItemsToPurchase(2)
                                             .ApplyActionTo(ApplicationOrder.Ascending)
                                             .ActionLimit(1))
                                  .Build(fixture.Factory);

            fixture.Factory.AddEntityToList(promotion, CommerceEntity.ListName <Promotion>());
            fixture.Factory.AddEntity(promotion);

            fixture.Factory.AddEntity(new Category
            {
                Id         = "Laptops".ToEntityId <Category>(),
                SitecoreId = "435345345"
            });

            Cart cart = await new CartBuilder()
                        .WithLines(new LineBuilder().IdentifiedBy("001").Quantity(1).InCategory("34345454").Price(40),
                                   new LineBuilder().IdentifiedBy("002").Quantity(1).InCategory("454545454").Price(50))
                        .Build();

            fixture.Factory.AddEntity(cart);

            Cart resultCart =
                await client.GetJsonAsync <Cart>(
                    "api/Carts('Cart01')?$expand=Lines($expand=CartLineComponents($expand=ChildComponents)),Components");

            CartLineComponent line = resultCart.Lines.Single(x => x.Id == "002");

            Assert.DoesNotContain(line.Adjustments,
                                  x => x.AwardingBlock == nameof(CartEveryXItemsInCategoryPercentageDiscountAction));
        }
        public override async Task <Cart> Run(CartLineArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull("The argument can not be null");
            Condition.Requires(arg.Cart).IsNotNull("The cart can not be null");
            Condition.Requires(arg.Line).IsNotNull("The lines can not be null");

            Cart cart = arg.Cart;
            List <CartLineComponent> lines        = cart.Lines.ToList();
            CartLineComponent        existingLine = lines.FirstOrDefault(l => l.Id.Equals(arg.Line.Id, StringComparison.OrdinalIgnoreCase));

            if (existingLine != null)
            {
                string str = await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Information, null, null, $"Removed Line '{existingLine.Id}' from Wishlist '{cart.Id}'.");

                lines.Remove(existingLine);
            }

            cart.Lines = lines;
            return(cart);
        }
Esempio n. 20
0
        /// <summary>
        /// To add the new shared cart data to the line item
        /// </summary>
        /// <param name="entityView"></param>
        /// <param name="line"></param>
        /// <param name="context"></param>
        private void PopulateLineChildView(EntityView entityView, CartLineComponent line, CommercePipelineExecutionContext context)
        {
            var lineEntityView = entityView.ChildViews.OfType <EntityView>().FirstOrDefault(p => p.ItemId == line.Id);

            if (line.HasComponent <SharedCartLineComponent>())
            {
                var sharedCartLineComponent = line.GetComponent <SharedCartLineComponent>();
                //Add shop name property to the line item view
                lineEntityView.Properties.Add(new ViewProperty {
                    Name = "ShopName", DisplayName = "Store", IsReadOnly = true, RawValue = sharedCartLineComponent.ShopName
                });
            }
            else
            {
                //Add blank value if component doesn't exist, because Headers
                lineEntityView.Properties.Add(new ViewProperty {
                    Name = "ShopName", DisplayName = "Store", IsReadOnly = true, RawValue = string.Empty
                });
            }
        }
Esempio n. 21
0
        public override async Task <CartLineArgument> Run(CartLineArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires <CartLineArgument>(arg).IsNotNull <CartLineArgument>("The argument can not be null");
            Condition.Requires <Cart>(arg.Cart).IsNotNull <Cart>("The cart can not be null");
            Condition.Requires <CartLineComponent>(arg.Line).IsNotNull <CartLineComponent>("The lines can not be null");
            Cart cart = arg.Cart;

            List <CartLineComponent> lines        = cart.Lines.ToList <CartLineComponent>();
            CartLineComponent        existingLine = lines.FirstOrDefault <CartLineComponent>((Func <CartLineComponent, bool>)(l => l.Id.Equals(arg.Line.Id, StringComparison.OrdinalIgnoreCase)));

            if (existingLine != null)
            {
                FindEntityArgument getProductArg  = new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-" + (existingLine.ItemId.Split('|').Count() > 1 ? existingLine.ItemId.Split('|')[1] : existingLine.ItemId), false);
                SellableItem       carLineProduct = await this._findEntityPipeline.Run(getProductArg, (CommercePipelineExecutionContext)context).ConfigureAwait(false) as SellableItem;

                bool hasTag = carLineProduct.Tags.Any <Tag>((Func <Tag, bool>)(t => t.Name.Equals("bundle", StringComparison.OrdinalIgnoreCase)));
                if (hasTag)
                {
                    string listId          = String.Format("relatedproduct-{0}", existingLine.ItemId.Split('|').Count() > 1 ? existingLine.ItemId.Split('|')[1] : existingLine.ItemId);
                    var    relatedProducts = await _findEntitiesInListPipeline.Run(
                        new FindEntitiesInListArgument(typeof(CommerceEntity), listId, 0, 10)
                    {
                        LoadEntities = true
                    },
                        context);

                    foreach (var relProd in relatedProducts.List.Items)
                    {
                        if (cart.Lines.Any(l => l.ItemId.Contains(relProd.FriendlyId)))
                        {
                            var relatedProductCartLine = cart.Lines.FirstOrDefault <CartLineComponent>(l => l.ItemId.Contains(relProd.FriendlyId));
                            if (relatedProductCartLine != null)
                            {
                                cart.Lines.Remove(relatedProductCartLine);
                            }
                        }
                    }
                }
            }
            return(arg);
        }
Esempio n. 22
0
        public async Task <IActionResult> AddWishListLineItem([FromBody] ODataActionParameters value)
        {
            CommandsController commandsController = this;

            if (!commandsController.ModelState.IsValid || value == null)
            {
                return((IActionResult) new BadRequestObjectResult(commandsController.ModelState));
            }
            if (value.ContainsKey("wishlistId"))
            {
                object obj1 = value["wishlistId"];
                if (!string.IsNullOrEmpty(obj1 != null ? obj1.ToString() : (string)null) && value.ContainsKey("itemId"))
                {
                    object obj2 = value["itemId"];
                    if (!string.IsNullOrEmpty(obj2 != null ? obj2.ToString() : (string)null) && value.ContainsKey("quantity"))
                    {
                        object obj3 = value["quantity"];
                        if (!string.IsNullOrEmpty(obj3 != null ? obj3.ToString() : (string)null))
                        {
                            string  cartId = value["wishlistId"].ToString();
                            string  str    = value["itemId"].ToString();
                            Decimal result;
                            if (!Decimal.TryParse(value["quantity"].ToString(), out result))
                            {
                                return((IActionResult) new BadRequestObjectResult((object)value));
                            }
                            AddWishListLineItemCommand command = commandsController.Command <AddWishListLineItemCommand>();
                            CartLineComponent          line    = new CartLineComponent()
                            {
                                ItemId   = str,
                                Quantity = result
                            };
                            Cart cart = await command.Process(commandsController.CurrentContext, cartId, line).ConfigureAwait(false);

                            return((IActionResult) new ObjectResult((object)command));
                        }
                    }
                }
            }
            return((IActionResult) new BadRequestObjectResult((object)value));
        }
        protected override void TranslateProduct(
            TranslateCartLineToEntityRequest request,
            CartLineComponent source,
            CommerceCartLine destination,
            bool isSubLine = false)
        {
            base.TranslateProduct(request, source, destination, isSubLine);

            if (destination == null || destination.Product == null)
            {
                return;
            }

            if (source.CartLineComponents != null && !string.IsNullOrEmpty(source.ItemId))
            {
                CartProductComponent productComponent = source.CartLineComponents.OfType <CartProductComponent>().FirstOrDefault();
                if (productComponent != null)
                {
                    destination.SetPropertyValue("ItemType", string.IsNullOrEmpty(productComponent.ItemType) ? null : productComponent.ItemType);
                }
            }
        }
        /// <summary>
        /// The process of the command
        /// </summary>
        /// <param name="commerceContext">
        /// The commerce context
        /// </param>
        /// <param name="cartLineComponent"></param>
        /// <param name="awardingAction"></param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public virtual void Process(CommerceContext commerceContext, [NotNull] CartLineComponent cartLineComponent, [NotNull] string awardingAction)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var discountAdjustmentType = commerceContext.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount;
                var propertiesModel        = commerceContext.GetObject <PropertiesModel>();
                var totals         = commerceContext?.GetObject <CartTotals>();
                var discountAmount = cartLineComponent.UnitListPrice.Amount * decimal.MinusOne;

                cartLineComponent.Adjustments.Add(new CartLineLevelAwardedAdjustment
                {
                    Name           = (propertiesModel?.GetPropertyValue("PromotionText") as string ?? discountAdjustmentType),
                    DisplayName    = (propertiesModel?.GetPropertyValue("PromotionCartText") as string ?? discountAdjustmentType),
                    Adjustment     = new Money(commerceContext.CurrentCurrency(), discountAmount),
                    AdjustmentType = discountAdjustmentType,
                    IsTaxable      = false,
                    AwardingBlock  = propertiesModel?.GetPropertyValue("PromotionId") as string
                });

                totals.Lines[cartLineComponent.Id].SubTotal.Amount = totals.Lines[cartLineComponent.Id].SubTotal.Amount + discountAmount;
                cartLineComponent.GetComponent <MessagesComponent>().AddMessage(commerceContext.GetPolicy <KnownMessageCodePolicy>().Promotions, string.Format("PromotionApplied: {0}", propertiesModel?.GetPropertyValue("PromotionId") ?? awardingAction));
            }
        }
Esempio n. 25
0
        public CartLineComponent Build()
        {
            var line = new CartLineComponent
            {
                Id            = lineId,
                Quantity      = quantity,
                ItemId        = itemId,
                UnitListPrice = new Money(price),
                Policies      =
                {
                    new PurchaseOptionMoneyPolicy
                    {
                        SellPrice = new Money(price)
                    }
                },
                Totals = new Totals
                {
                    GrandTotal = new Money(quantity * price)
                }
            };

            if (fullfilmentMethod != null)
            {
                line.SetComponent(new FulfillmentComponent
                {
                    FulfillmentMethod = fullfilmentMethod
                });
            }

            if (categorySitecoreId != null)
            {
                var categoryComponent = line.GetComponent <CategoryComponent>();
                categoryComponent.ParentCategoryList.Add(categorySitecoreId);
            }

            return(line);
        }
        public async Task Run_CartWithTwoGiftBoxItems_ShouldReturnCartWithNonZeroGitfBoxFee()
        {
            var expectedFeeAmount = new GiftBoxFeeAdjustmentPolicy().FeeAmount * 2;
            var inputCart         = new Cart();
            var cartLine1         = new CartLineComponent()
            {
                Id       = Guid.NewGuid().ToString(),
                ItemId   = "some-item-1",
                Quantity = 1
            };

            cartLine1.SetComponent(new CartLineGiftBoxComponent()
            {
                IsGiftBox = true
            });
            inputCart.Lines.Add(cartLine1);
            var cartLine2 = new CartLineComponent()
            {
                Id       = Guid.NewGuid().ToString(),
                ItemId   = "some-item-2",
                Quantity = 1
            };

            cartLine2.SetComponent(new CartLineGiftBoxComponent()
            {
                IsGiftBox = true
            });
            inputCart.Lines.Add(cartLine2);

            var outputCart = await _pipelineBlock.Run(inputCart, _pipelineContextFake);

            var giftBoxAdjustment = outputCart.Adjustments.SingleOrDefault(a => a.Name == Constants.Adjustments.GiftBox.Name);

            Assert.NotNull(giftBoxAdjustment);
            Assert.True(giftBoxAdjustment.Adjustment.Amount == expectedFeeAmount);
        }
Esempio n. 27
0
        public void Execute(IRuleExecutionContext context)
        {
            var commerceContext = context.Fact <CommerceContext>();
            var cart            = commerceContext?.GetObject <Cart>();

            if (cart == null || !cart.Lines.Any())
            {
                return;
            }

            decimal quantity     = Hc_Quantity.Yield(context);
            string  targetItemId = TargetItemId.Yield(context);

            if (quantity == 0 || string.IsNullOrEmpty(targetItemId))
            {
                return;
            }

            if (cart.Lines.Any(x => x.ItemId == targetItemId && x.Quantity == quantity))
            {
                //After the product is added
                //You only get the product for free once :)
                return;
            }

            cart.GetComponent <MessagesComponent>().AddPromotionApplied(commerceContext, nameof(CartFreeGiftAction));

            CartLineComponent giftLine = CreateLine(cart, commerceContext, targetItemId, quantity);

            if (giftLine == null)
            {
                return;
            }

            cart.Lines.Add(giftLine);
        }
Esempio n. 28
0
 private static Func <CartLineComponent, bool> ProductExistsInOrderAndCart(CartLineComponent cartLine)
 {
     return(orderLine => cartLine.GetComponent <CartProductComponent>().Id == orderLine.GetComponent <CartProductComponent>().Id);
 }
Esempio n. 29
0
        public virtual async Task <Cart> Process(CommerceContext commerceContext, string wishlistId, CartLineComponent line)
        {
            AddWishListLineItemCommand addCartLineCommand = this;
            Cart result = null;

            using (CommandActivity.Start(commerceContext, addCartLineCommand))
            {
                await addCartLineCommand.PerformTransaction(commerceContext, async() =>
                {
                    FindEntityArgument findEntityArgument = new FindEntityArgument(typeof(Cart), wishlistId, true);

                    Cart cart = await _getPipeline.Run(findEntityArgument, commerceContext.PipelineContextOptions).ConfigureAwait(false) as Cart;
                    if (cart == null)
                    {
                        string str = await commerceContext.PipelineContextOptions.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().ValidationError, "EntityNotFound", new object[1]
                        {
                            wishlistId
                        }, $"Entity {wishlistId} was not found.").ConfigureAwait(false);
                    }
                    else
                    {
                        if (!cart.IsPersisted)
                        {
                            cart.Id       = wishlistId;
                            cart.Name     = wishlistId;
                            cart.ShopName = commerceContext.CurrentShopName();
                            cart.SetComponent(new ListMembershipsComponent()
                            {
                                Memberships = new List <string>
                                {
                                    CommerceEntity.ListName <Cart>()
                                }
                            });

                            cart.SetComponent(new CartTypeComponent {
                                CartType = CartTypeEnum.Wishlist.ToString()
                            });
                        }


                        result = await _addWishListLineItemPipeline.Run(new CartLineArgument(cart, line), commerceContext.PipelineContextOptions).ConfigureAwait(false);
                    }
                }).ConfigureAwait(false);
            }

            return(result);
        }
Esempio n. 30
0
 private static bool HasCategory(bool includeSubCategories, CartLineComponent line, string categorySitecoreId)
 {
     return(line.HasComponent <CategoryComponent>() &&
            line.GetComponent <CategoryComponent>().IsMatch(categorySitecoreId, includeSubCategories));
 }