예제 #1
0
        public async Task <IEnumerable <CatalogContextModel> > Process(CommerceContext commerceContext, IEnumerable <string> catalogNameList, bool useCache = true)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                if (catalogNameList == null || catalogNameList.Count().Equals(0))
                {
                    throw new Exception($"{nameof(GetCatalogContextCommand)} no catalogs provided");
                }

                if (useCache == false)
                {
                    commerceContext.RemoveObjects <CatalogContextModel>();
                }

                var allCatalogs = commerceContext.GetObject <IEnumerable <Sitecore.Commerce.Plugin.Catalog.Catalog> >();
                if (allCatalogs == null)
                {
                    allCatalogs = await Command <GetCatalogsCommand>().Process(commerceContext);

                    commerceContext.AddObject(allCatalogs);
                }

                var catalogCategoryModelList = new List <CatalogContextModel>();
                foreach (var catalogName in catalogNameList)
                {
                    var model = commerceContext.GetObject <CatalogContextModel>(m => m.CatalogName.Equals(catalogName));
                    if (model == null)
                    {
                        var catalog       = allCatalogs.FirstOrDefault(c => c.Name.Equals(catalogName));
                        var allCategories = (await Command <GetCategoriesCommand>().Process(commerceContext, catalogName)).ToList();
                        if (allCategories == null)
                        {
                            allCategories = new List <Category>();
                        }

                        allCategories = allCategories.Where(c => c.Id.CatalogNameFromCategoryId().Equals(catalogName)).ToList();

                        model = new CatalogContextModel
                        {
                            CatalogName            = catalog.Name,
                            Catalog                = catalog,
                            CategoriesByName       = allCategories.ToDictionary(c => c.Name),
                            CategoriesBySitecoreId = allCategories.ToDictionary(c => c.SitecoreId)
                        };

                        commerceContext.AddObject(model);
                    }

                    catalogCategoryModelList.Add(model);
                }

                return(catalogCategoryModelList);
            }
        }
예제 #2
0
        public bool Evaluate(IRuleExecutionContext context)

        {
            string          targetItemId    = this.TargetItemId.Yield(context);
            string          storeName       = this.StoreName.Yield(context);
            CommerceContext commerceContext = context.Fact <CommerceContext>((string)null);
            Cart            cart            = commerceContext != null?commerceContext.GetObject <Cart>() : (Cart)null;

            if (cart == null || !cart.Lines.Any <CartLineComponent>() || (string.IsNullOrEmpty(targetItemId) || string.IsNullOrEmpty(storeName)))
            {
                return(false);
            }

            if (this.MatchingLines(context).Any <CartLineComponent>((Func <CartLineComponent, bool>)(l => l.HasComponent <CartProductComponent>())))
            {
                var cartShippingParty = cart.GetComponent <PhysicalFulfillmentComponent>().ShippingParty;
                if (cartShippingParty != null)
                {
                    return(cartShippingParty.AddressName.ToLower() == storeName.ToLower());
                }
                var cartLinesWithParty = cart.Lines.Where <CartLineComponent>(l => l.ItemId.Contains(targetItemId) && l.GetComponent <PhysicalFulfillmentComponent>().ShippingParty != null);
                if (cartLinesWithParty.Count <CartLineComponent>() > 0)
                {
                    return(cartLinesWithParty.Any <CartLineComponent>(
                               (Func <CartLineComponent, bool>)(
                                   l => l.GetComponent <PhysicalFulfillmentComponent>().ShippingParty.AddressName.ToLower() == storeName.ToLower())));
                }
            }
            return(false);
        }
        public static void AddPromotionApplied(this MessagesComponent messageComponent, CommerceContext commerceContext,
                                               string awardingBlock)
        {
            var    propertiesModel = commerceContext.GetObject <PropertiesModel>();
            object promotionName   = propertiesModel?.GetPropertyValue("PromotionId") ?? awardingBlock;

            messageComponent.AddMessage(commerceContext.GetPolicy <KnownMessageCodePolicy>().Promotions,
                                        $"PromotionApplied: {promotionName}");
        }
예제 #4
0
        private IEnumerable <CartLineComponent> GetCartLines(CommerceContext commerceContext)
        {
            var cart = commerceContext.GetObject <Cart>();

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

            return(cart.Lines);
        }
예제 #5
0
        /// <summary>
        /// The process of the command
        /// </summary>
        /// <param name="commerceContext">
        /// The commerce context
        /// </param>
        /// <param name="parameter">
        /// The parameter for the command
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public virtual void Process(CommerceContext commerceContext, [NotNull] Cart cart, [NotNull] string awardingAction)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var propertiesModel = commerceContext.GetObject <PropertiesModel>();
                var freeGiftEligibilityComponent = cart.GetComponent <FreeGiftEligibilityComponent>();

                freeGiftEligibilityComponent.AwardingAction = awardingAction;
                freeGiftEligibilityComponent.PromotionId    = propertiesModel?.GetPropertyValue("PromotionId") as string;
            }
        }
        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;
        }
예제 #7
0
        private async Task TransformCatalog(CommerceContext commerceContext, List <Category> importItems)
        {
            var allCatalogs = commerceContext.GetObject <IEnumerable <Sitecore.Commerce.Plugin.Catalog.Catalog> >();

            if (allCatalogs == null)
            {
                allCatalogs = await Command <GetCatalogsCommand>().Process(commerceContext);

                commerceContext.AddObject(allCatalogs);
            }

            var allCatalogsDictionary = allCatalogs.ToDictionary(c => c.Name);

            foreach (var item in importItems)
            {
                var transientData = item.GetPolicy <TransientImportCategoryDataPolicy>();

                var catalogList = new List <string>();
                foreach (var association in transientData.CatalogAssociationList)
                {
                    allCatalogsDictionary.TryGetValue(association.Name, out Sitecore.Commerce.Plugin.Catalog.Catalog catalog);
                    if (catalog != null)
                    {
                        catalogList.Add(catalog.SitecoreId);
                    }
                    else
                    {
                        commerceContext.Logger.LogWarning($"Warning, Category with id '{item.Id}' attempting import into catalog '{association.Name}' which doesn't exist.");
                    }
                }

                var parentCatalogList = new List <string>();
                foreach (var association in transientData.ParentAssociationsToCreateList)
                {
                    if (association.ParentId.IsEntityId <Sitecore.Commerce.Plugin.Catalog.Catalog>())
                    {
                        allCatalogsDictionary.TryGetValue(association.ParentId.RemoveIdPrefix <Sitecore.Commerce.Plugin.Catalog.Catalog>(), out Sitecore.Commerce.Plugin.Catalog.Catalog catalog);
                        if (catalog != null)
                        {
                            parentCatalogList.Add(catalog.SitecoreId);
                        }
                        else
                        {
                            commerceContext.Logger.LogWarning($"Warning, Category with id {item.Id} attempting import into catalog {association.ParentId} which doesn't exist.");
                        }
                    }
                }

                // Primary responsibility of this method is to set these IDs
                item.CatalogToEntityList = catalogList.Any() ? string.Join("|", catalogList) : null;
                item.ParentCatalogList   = parentCatalogList.Any() ? string.Join("|", parentCatalogList) : null;
            }
        }
        private async Task CopyCategoryAddressRemoved(CommerceContext commerceContext, SellableItem existingItem, List <string> associationsToRemove)
        {
            if (associationsToRemove == null || associationsToRemove.Count().Equals(0))
            {
                return;
            }

            var transientData = existingItem.GetPolicy <TransientImportSellableItemDataPolicy>();

            var allCatalogs = commerceContext.GetObject <IEnumerable <Sitecore.Commerce.Plugin.Catalog.Catalog> >();

            if (allCatalogs == null)
            {
                allCatalogs = await Command <GetCatalogsCommand>().Process(commerceContext);

                commerceContext.AddObject(allCatalogs);
            }

            var existingCatalogSitecoreIdList = existingItem.ParentCatalogList.Split('|');

            var catalogNameList = new List <string>();

            foreach (var catalogSitecoreId in existingCatalogSitecoreIdList)
            {
                var catalog = allCatalogs.FirstOrDefault(c => c.SitecoreId.Equals(catalogSitecoreId));
                catalogNameList.Add(catalog.Name);
            }

            var catalogContextList = await Command <GetCatalogContextCommand>().Process(commerceContext, catalogNameList);

            foreach (var categoryToRemoveSitecoreId in associationsToRemove)
            {
                bool found = false;
                foreach (var catalogContext in catalogContextList)
                {
                    catalogContext.CategoriesBySitecoreId.TryGetValue(categoryToRemoveSitecoreId, out Category category);

                    if (category != null)
                    {
                        transientData.ParentAssociationsToRemoveList.Add(new CatalogItemParentAssociationModel(existingItem.Id, catalogContext.Catalog.Id, category));

                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    commerceContext.Logger.LogWarning($"Unable to find category with SitecoreId {categoryToRemoveSitecoreId}. We need to disacciate it from SellableItem {existingItem.Id}");
                }
            }
        }
예제 #9
0
        /// <summary>
        /// The gets the SQL context in use.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>
        /// The <see cref="ProfilesSqlContext" />.
        /// </returns>
        public static ProfilesSqlContext GetProfilesSqlContext(CommerceContext context)
        {
            var sqlContext  = new ProfilesSqlContext(GetProfilesSqlConnectionPolicy(context).ConnectionString());
            var transaction = context.GetObject <Transaction>();

            // If we have a transaction we need to use it in the SQL Context
            if (transaction != null)
            {
                sqlContext.CurrentTransaction = transaction;
            }

            return(sqlContext);
        }
        private async Task TransformCatalog(CommerceContext commerceContext, List <SellableItem> importItems)
        {
            var allCatalogs = commerceContext.GetObject <IEnumerable <Sitecore.Commerce.Plugin.Catalog.Catalog> >();

            if (allCatalogs == null)
            {
                allCatalogs = await Command <GetCatalogsCommand>().Process(commerceContext);

                commerceContext.AddObject(allCatalogs);
            }

            var allCatalogsDictionary = allCatalogs.ToDictionary(c => c.Name);

            foreach (var item in importItems)
            {
                var transientData = item.GetPolicy <TransientImportSellableItemDataPolicy>();

                if (transientData.CatalogAssociationList == null || transientData.CatalogAssociationList.Count().Equals(0))
                {
                    throw new Exception($"{item.Name}: needs to have at least one definied catalog");
                }

                var catalogList       = new List <string>();
                var parentCatalogList = new List <string>();
                foreach (var catalogAssociation in transientData.CatalogAssociationList)
                {
                    allCatalogsDictionary.TryGetValue(catalogAssociation.Name, out Sitecore.Commerce.Plugin.Catalog.Catalog catalog);
                    if (catalog != null)
                    {
                        catalogList.Add(catalog.SitecoreId);
                        item.GetComponent <CatalogsComponent>().ChildComponents.Add(new CatalogComponent {
                            Name = catalogAssociation.Name
                        });

                        if (catalogAssociation.IsParent)
                        {
                            transientData.ParentAssociationsToCreateList.Add(new CatalogItemParentAssociationModel(item.Id, catalog.Id, catalog));
                            parentCatalogList.Add(catalog.SitecoreId);
                        }
                    }
                    else
                    {
                        commerceContext.Logger.LogWarning($"Warning, Product with id {item.ProductId} attempting import into catalog {catalogAssociation.Name} which doesn't exist.");
                    }
                }

                item.CatalogToEntityList = catalogList.Any() ? string.Join("|", catalogList) : null;
                item.ParentCatalogList   = parentCatalogList.Any() ? string.Join("|", parentCatalogList) : null;
            }
        }
예제 #11
0
        public static CartLevelAwardedAdjustment CreateCartLevelAwardedAdjustment(decimal amountOff, string awardingBlock,
                                                                                  CommerceContext commerceContext)
        {
            var    propertiesModel = commerceContext.GetObject <PropertiesModel>();
            string discount        = commerceContext.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount;

            var adjustment = new CartLevelAwardedAdjustment
            {
                Name           = propertiesModel?.GetPropertyValue("PromotionText") as string ?? discount,
                DisplayName    = propertiesModel?.GetPropertyValue("PromotionCartText") as string ?? discount,
                Adjustment     = new Money(commerceContext.CurrentCurrency(), amountOff),
                AdjustmentType = discount,
                IsTaxable      = false,
                AwardingBlock  = awardingBlock
            };

            return(adjustment);
        }
        /// <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));
            }
        }
        public void Execute(IRuleExecutionContext context)
        {
            CommerceContext commerceContext  = context.Fact <CommerceContext>((string)null);
            CommerceContext commerceContext1 = commerceContext;
            Cart            cart             = commerceContext1 != null?commerceContext1.GetObjects <Cart>().FirstOrDefault <Cart>() : (Cart)null;

            CommerceContext commerceContext2 = commerceContext;
            CartTotals      totals           = commerceContext2 != null?commerceContext2.GetObjects <CartTotals>().FirstOrDefault <CartTotals>() : (CartTotals)null;

            if (cart == null || !cart.Lines.Any <CartLineComponent>() || (totals == null || !totals.Lines.Any <KeyValuePair <string, Totals> >()))
            {
                return;
            }

            List <CartLineComponent> list = new List <CartLineComponent>();

            //Get the valid cartline items that matches specific tag provided
            foreach (var cartLine in cart.Lines.Where(x => x.HasComponent <CartProductComponent>()))
            {
                var firstOrDefault = cartLine.GetComponent <CartProductComponent>().Tags.FirstOrDefault(t => t.Name == this.Tag.Yield(context));
                if (!string.IsNullOrEmpty(firstOrDefault?.Name))
                {
                    list.Add(cartLine);
                }
            }
            if (!list.Any <CartLineComponent>())
            {
                return;
            }

            list.ForEach((Action <CartLineComponent>)(line =>
            {
                if (!totals.Lines.ContainsKey(line.Id))
                {
                    return;
                }
                PropertiesModel propertiesModel = commerceContext.GetObject <PropertiesModel>();
                string discountPolicy           = commerceContext.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount;

                //Extract the coupon code in-order to associate coupon code with adjustment (1 to 1 mapping)
                string couponCode = string.Empty;
                if (cart.HasComponent <CartCouponsComponent>())
                {
                    if (cart.GetComponent <CartCouponsComponent>().List != null && cart.GetComponent <CartCouponsComponent>().List.Any())
                    {
                        couponCode = cart.GetComponent <CartCouponsComponent>().List.FirstOrDefault(c => c.Promotion.EntityTarget == (string)propertiesModel?.GetPropertyValue("PromotionId"))?.CouponId;
                    }
                }

                //calculate discounts on specified custom pricing
                if (line.HasComponent <CustomPriceInfoComponent>())
                {
                    var customPriceInfo = line.GetComponent <CustomPriceInfoComponent>();
                    Decimal discount    = 0;
                    if (this.BasePrice.Yield(context))
                    {
                        discount += (Decimal)((double)this.PercentOff.Yield(context) * 0.01) * (decimal.Parse(customPriceInfo.BasePrice.ToString()));
                    }
                    if (this.ActivationPrice.Yield(context))
                    {
                        discount += (Decimal)((double)this.PercentOff.Yield(context) * 0.01) * (decimal.Parse(customPriceInfo.ActivationPrice.ToString()));
                    }
                    if (this.DeliveryPrice.Yield(context))
                    {
                        discount += (Decimal)((double)this.PercentOff.Yield(context) * 0.01) * (decimal.Parse(customPriceInfo.DeliveryPrice.ToString()));
                    }
                    if (commerceContext.GetPolicy <GlobalPricingPolicy>().ShouldRoundPriceCalc)
                    {
                        discount = Decimal.Round(discount, commerceContext.GetPolicy <GlobalPricingPolicy>().RoundDigits, commerceContext.GetPolicy <GlobalPricingPolicy>().MidPointRoundUp ? MidpointRounding.AwayFromZero : MidpointRounding.ToEven);
                    }
                    Decimal amount = discount * Decimal.MinusOne;

                    //Create an adjustment and associate coupon code with coupon description delimited by '|' [Workaround for known issue with Promotion Plugin]
                    IList <AwardedAdjustment> adjustments = line.Adjustments;
                    adjustments.Add((AwardedAdjustment) new CartLineLevelAwardedAdjustment()
                    {
                        Name           = (propertiesModel?.GetPropertyValue("PromotionText") as string ?? discountPolicy),
                        DisplayName    = couponCode + "|" + (propertiesModel?.GetPropertyValue("PromotionCartText") as string ?? discountPolicy),
                        Adjustment     = new Money(commerceContext.CurrentCurrency(), amount),
                        AdjustmentType = discountPolicy,
                        IsTaxable      = false,
                        AwardingBlock  = nameof(CustomPercentOffAction)
                    });
                    totals.Lines[line.Id].SubTotal.Amount = totals.Lines[line.Id].SubTotal.Amount + amount;
                    line.GetComponent <MessagesComponent>().AddMessage(commerceContext.GetPolicy <KnownMessageCodePolicy>().Promotions, string.Format("PromotionApplied: {0}", propertiesModel?.GetPropertyValue("PromotionId") ?? (object)nameof(CustomPercentOffAction)));
                }
            }));
        }