/// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">
        /// The pipeline argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="PipelineArgument"/>.
        /// </returns>
        public async override Task <IEnumerable <LocalizedTerm> > Run(LocalizedProductFeaturesArgument arg, CommercePipelineExecutionContext context)
        {
            var cachePolicy = context.GetPolicy <ProductFeaturesCachePolicy>();

            if (!cachePolicy.AllowCaching)
            {
                context.CommerceContext.AddUniqueObjectByType((object)new KeyValuePair <string, bool>("IsFromCache", false));
                return(null);
            }

            var policy = context.GetPolicy <ProductFeaturesControlPanelPolicy>();

            string cacheKey      = policy.AvailableProductFeaturesPath + "|" + context.CommerceContext.CurrentLanguage();
            var    cachePipeline = this.Commander.Pipeline <IGetEnvironmentCachePipeline>();

            EnvironmentCacheArgument environmentCacheArgument = new EnvironmentCacheArgument();

            environmentCacheArgument.CacheName = cachePolicy.CacheName;

            var result = (await cachePipeline.Run(environmentCacheArgument, context))?.Get(cacheKey)?.Result as IEnumerable <LocalizedTerm>;

            if (result == null)
            {
                context.CommerceContext.AddUniqueObjectByType((object)new KeyValuePair <string, bool>("IsFromCache", false));
                return(null);
            }
            context.CommerceContext.AddUniqueObjectByType((object)new KeyValuePair <string, bool>("IsFromCache", true));
            context.Logger.LogDebug("Mgmt.GetLocMsg." + cacheKey);

            return(result);
        }
        /// <summary>The execute.</summary>
        /// <param name="arg">The pipeline argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="EntityView"/>.</returns>
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The entity view can not be null");

            var policy             = context.GetPolicy <KnownCatalogViewsPolicy>();
            var entityViewArgument = context.CommerceContext.GetObject <EntityViewArgument>();
            var enablementPolicy   = context.GetPolicy <Policies.CatalogFeatureEnablementPolicy>();

            if (!enablementPolicy.CatalogNavigationView ||
                string.IsNullOrEmpty(entityViewArgument?.ViewName) ||
                !entityViewArgument.ViewName.Equals(policy.Master, StringComparison.OrdinalIgnoreCase) &&
                !entityViewArgument.ViewName.Equals(policy.Details, StringComparison.OrdinalIgnoreCase))
            {
                return(await Task.FromResult(entityView).ConfigureAwait(false));
            }

            var category = entityViewArgument.Entity as Category;

            if (category == null)
            {
                return(await Task.FromResult(entityView).ConfigureAwait(false));
            }

            await this.AddCatalogNavigationView(entityView, category, context).ConfigureAwait(false);

            return(await Task.FromResult(entityView).ConfigureAwait(false));
        }
示例#3
0
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">
        /// The pipeline argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="PipelineArgument"/>.
        /// </returns>
        public async override Task <IEnumerable <LocalizedTerm> > Run(IEnumerable <LocalizedTerm> arg, CommercePipelineExecutionContext context)
        {
            if (arg == null)
            {
                return(null);
            }

            KeyValuePair <string, bool> keyValuePair = context.CommerceContext.GetObject <KeyValuePair <string, bool> >((Func <KeyValuePair <string, bool>, bool>)(k => k.Key.Equals("IsFromCache", StringComparison.OrdinalIgnoreCase)));

            string currentLanguage = context.CommerceContext.CurrentLanguage();
            var    cachePolicy     = context.GetPolicy <ProductFeaturesCachePolicy>();

            if (cachePolicy.AllowCaching && !keyValuePair.Value)
            {
                var    policy   = context.GetPolicy <ProductFeaturesControlPanelPolicy>();
                string cacheKey = policy.AvailableProductFeaturesPath + "|" + currentLanguage;
                IGetEnvironmentCachePipeline cachePipeline            = this.Commander.Pipeline <IGetEnvironmentCachePipeline>();
                EnvironmentCacheArgument     environmentCacheArgument = new EnvironmentCacheArgument();
                environmentCacheArgument.CacheName = cachePolicy.CacheName;
                await(await cachePipeline.Run(environmentCacheArgument, context)).Set(cacheKey, (ICachable) new Cachable <IEnumerable <LocalizedTerm> >(arg, 1L), cachePolicy.GetCacheEntryOptions());
                cacheKey = (string)null;
            }

            return(arg);
        }
        public override Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            CommerceContext = context;

            Condition.Requires(arg).IsNotNull($"{Name}: argument cannot be null.");

            SearchIndexMinionArgument indexMinionArgument =
                CommerceContext.CommerceContext
                .GetObjects <SearchIndexMinionArgument>()
                .FirstOrDefault();

            if (string.IsNullOrEmpty(indexMinionArgument?.Policy?.Name))
            {
                return(Task.FromResult(arg));
            }

            var source = GetEntities(indexMinionArgument);

            if (source == null || !source.Any())
            {
                return(Task.FromResult(arg));
            }

            KnownSearchViewsPolicy searchViewNames = context.GetPolicy <KnownSearchViewsPolicy>();

            source.ForEach(si =>
            {
                EntityView entityView = arg.ChildViews
                                        .Cast <EntityView>()
                                        .FirstOrDefault(v => v.EntityId.Equals(si.Id, StringComparison.OrdinalIgnoreCase) && v.Name.Equals(searchViewNames.Document, StringComparison.OrdinalIgnoreCase));

                if (entityView == null)
                {
                    entityView = new EntityView
                    {
                        Name          = context.GetPolicy <KnownSearchViewsPolicy>().Document,
                        EntityId      = si.Id,
                        EntityVersion = si.EntityVersion
                    };

                    arg.ChildViews.Add(entityView);
                }

                BuildProperties(si, entityView);

                BuildCustomProperties(si, entityView);
            });

            //context.Logger.LogInformation($"Processed {source.Count} {typeof(T)} items.");

            return(Task.FromResult(arg));
        }
示例#5
0
        public override async Task <RuleSet> Run(
            IEnumerable <RuleModel> arg,
            CommercePipelineExecutionContext context)
        {
            List <RuleModel> source = arg as List <RuleModel> ?? arg.ToList();

            // ISSUE: explicit non-virtual call
            Condition.Requires(source).IsNotNull($"{Name}: The argument cannot be null");

            if (!source.Any())
            {
                CommercePipelineExecutionContext executionContext = context;
                string error = context.GetPolicy <KnownResultCodes>().Error;
                executionContext.Abort(await context.CommerceContext
                                       .AddMessage(error, "RulesCannotBeNullOrEmpty", null,
                                                   "Rules cannot be null or empty.")
                                       .ConfigureAwait(false), context);
                return(null);
            }

            _ruleBuilder = _services.GetService <IRuleBuilderInit>();
            var ruleSet1 = new RuleSet
            {
                Id = $"{CommerceEntity.IdPrefix<RuleSet>() as object}{Guid.NewGuid() as object:N}"
            };
            RuleSet ruleSet2 = ruleSet1;

            foreach (RuleModel model in source.Where(rm => rm != null))
            {
                try
                {
                    ruleSet2.Rules.Add(BuildRule(model));
                }
                catch (Exception ex)
                {
                    CommercePipelineExecutionContext executionContext = context;
                    string error = context.GetPolicy <KnownResultCodes>().Error;
                    var    args  = new object[] { model.Name, ex };
                    executionContext.Abort(await context.CommerceContext
                                           .AddMessage(error, "RuleNotBuilt", args,
                                                       $"Rule '{model.Name}' cannot be built.")
                                           .ConfigureAwait(false), context);
                    return(null);
                }
            }

            return(ruleSet2);
        }
示例#6
0
        /// <summary>
        ///  Retrieves Shipping method Sitecore items
        /// </summary>
        /// <param name="context"></param>
        /// <param name="currentShopName"></param>
        /// <returns></returns>
        private async Task <List <ItemModel> > GetShippingMethodItems(CommercePipelineExecutionContext context, string currentShopName)
        {
            var itemsPolicy  = context.GetPolicy <SitecoreControlPanelItemsPolicy>();
            var fieldsPolicy = context.GetPolicy <SitecoreItemFieldsPolicy>();

            var path               = context.CommerceContext.GetObject <KeyValuePair <string, string> >(kv => kv.Key.Equals("itemPath", StringComparison.OrdinalIgnoreCase)).Value ?? string.Empty;
            var itemPath           = string.IsNullOrEmpty(path) ? $"{itemsPolicy?.StorefrontsPath}/{currentShopName}" : path;
            List <ItemModel> items = new List <ItemModel>();

            var storefrontConfigurationItem = await this.Commander.Pipeline <IGetItemByPathPipeline>().Run(new ItemModelArgument(itemPath), context).ConfigureAwait(false);

            if (storefrontConfigurationItem != null)
            {
                var storefrontConfigurationItems = await this.Commander.Pipeline <IGetItemsByPathPipeline>().Run(new ItemModelArgument(itemPath), context).ConfigureAwait(false);

                var fulfillmentConfigurationItem = await this.GetFulfillmentConfigurationItem(itemPath, storefrontConfigurationItems, itemsPolicy, context).ConfigureAwait(false);

                if (fulfillmentConfigurationItem != null)
                {
                    var optionsIds = fulfillmentConfigurationItem.ContainsKey(fieldsPolicy.FulfillmentOptions)
                           ? fulfillmentConfigurationItem[fieldsPolicy.FulfillmentOptions] as string
                           : string.Empty;
                    if (!string.IsNullOrEmpty(optionsIds))
                    {
                        var ids = optionsIds.Split('|');
                        if (ids.Any())
                        {
                            foreach (var id in ids)
                            {
                                var fulfillmentOptionItem = await this.Commander.Pipeline <IGetItemByIdPipeline>().Run(new ItemModelArgument(id), context).ConfigureAwait(false);

                                if (fulfillmentOptionItem == null)
                                {
                                    continue;
                                }

                                var methodsItems = await this.Commander.Pipeline <IGetItemsByPathPipeline>()
                                                   .Run(new ItemModelArgument(fulfillmentOptionItem[ItemModel.ItemPath].ToString()), context).ConfigureAwait(false);

                                methodsItems?.ForEach(fo => items.Add(fo));
                            }
                        }
                    }
                }
            }

            return(items);
        }
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">
        /// The pipeline argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="PipelineArgument"/>.
        /// </returns>
        public override async Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name}: The argument can not be null");

            var cartViewsPolicy = context.GetPolicy <KnownCartViewsPolicy>();

            if (!arg.Name.Equals(cartViewsPolicy.CartsDashboard, StringComparison.InvariantCultureIgnoreCase))
            {
                return(arg);
            }

            EntityViewArgument entityViewArgument = context.CommerceContext.GetObjects <EntityViewArgument>().FirstOrDefault <EntityViewArgument>();

            var cartsView = new EntityView()
            {
                Name        = "Carts",
                DisplayName = "Carts",
                UiHint      = "Table"
            };

            arg.ChildViews.Add(cartsView);

            string listName = "Carts";

            await this.SetListMetadata(cartsView, listName, "PaginateCartsViewList", context);

            var carts = (await this.GetEntities(arg, "Carts", context)).OfType <Cart>();

            cartsView.FillWithCarts(carts);

            return(arg);
        }
示例#8
0
        public override bool ShouldViewApply(CommercePipelineExecutionContext context, Sitecore.Commerce.EntityViews.EntityView entityView, SellableItem entity)
        {
            var catalogViewsPolicy = context.GetPolicy <KnownCatalogViewsPolicy>();
            var isConnectView      = entityView.Name.Equals(catalogViewsPolicy.ConnectSellableItem, StringComparison.OrdinalIgnoreCase);

            return(entityView.Name == catalogViewsPolicy.Master || isConnectView);
        }
示例#9
0
        private static void AddSellableItemVariations(EntityView entityView, CommerceEntity entity, CommercePipelineExecutionContext context)
        {
            var policy = context.GetPolicy <KnownCatalogViewsPolicy>();

            if (entity == null || !entityView.Name.Equals(policy.Master, StringComparison.OrdinalIgnoreCase) && !entityView.Name.Equals(policy.Details, StringComparison.OrdinalIgnoreCase) && !entityView.Name.Equals(policy.ConnectSellableItem, StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            var entityView1 = new EntityView
            {
                Name          = policy.SellableItemVariants,
                EntityId      = entity.Id,
                EntityVersion = entity.EntityVersion,
                UiHint        = "Table"
            };
            var entityView2 = entityView1;
            var list        = entity.GetComponent <ItemVariationsComponent>().ChildComponents.OfType <ItemVariationComponent>().ToList();

            if (list.Count > 0)
            {
                foreach (var variationComponent in list)
                {
                    var entityView3 = new EntityView
                    {
                        Name          = policy.Variant,
                        EntityId      = entity.Id,
                        EntityVersion = entity.EntityVersion,
                        ItemId        = variationComponent.Id
                    };
                    var entityView4   = entityView3;
                    var properties1   = entityView4.Properties;
                    var viewProperty1 = new ViewProperty
                    {
                        Name       = "Id",
                        RawValue   = variationComponent.Id,
                        IsReadOnly = true,
                        UiType     = "ItemLink"
                    };
                    properties1.Add(viewProperty1);
                    var properties2   = entityView4.Properties;
                    var viewProperty2 = new ViewProperty
                    {
                        Name       = "DisplayName",
                        RawValue   = variationComponent.DisplayName,
                        IsReadOnly = true
                    };
                    properties2.Add(viewProperty2);
                    var properties3   = entityView4.Properties;
                    var viewProperty3 = new ViewProperty
                    {
                        Name       = "Disabled",
                        RawValue   = variationComponent.Disabled,
                        IsReadOnly = true
                    };
                    properties3.Add(viewProperty3);
                    entityView2.ChildViews.Add(entityView4);
                }
            }
            entityView.ChildViews.Add(entityView2);
        }
示例#10
0
        public void AssociateToCatalogOrCategory(CommercePipelineExecutionContext context, EntityView entityView, EntityViewArgument request, string action)
        {
            var policy1    = context.GetPolicy <KnownCatalogViewsPolicy>();
            var policy2    = context.CommerceContext.Environment.GetComponent <PolicySetsComponent>().GetPolicy <SearchScopePolicy>();
            var policyList = new List <Policy>
            {
                new Policy()
                {
                    PolicyId = "EntityType", Models = new List <Model>()
                    {
                        new Model()
                        {
                            Name = "SellableItem"
                        }
                    }
                },
                policy2
            };
            var properties   = entityView.Properties;
            var viewProperty = new ViewProperty
            {
                DisplayName  = policy1.SellableItem,
                Name         = policy1.SellableItem,
                IsRequired   = true,
                Value        = string.Empty,
                UiType       = "Autocomplete",
                OriginalType = string.Empty.GetType().FullName,
                Policies     = policyList
            };

            properties.Add(viewProperty);
        }
示例#11
0
        private async Task <MoneyDTO> GetShippingResponseRatesAsync(RateShipmentResponse shipmentResponse, string shippingMethod, CommercePipelineExecutionContext context)
        {
            // Func<Rate, bool> shippingMethodMatchDelegate = rate => rate.ServiceCode?.IndexOf(shippingMethod, StringComparison.InvariantCultureIgnoreCase) >= 0;

            var shipmentDetail =
                shipmentResponse
                .RateResponse
                .Rates
                .FirstOrDefault(r => r.ServiceCode?.IndexOf(shippingMethod, StringComparison.InvariantCultureIgnoreCase) >= 0);

            if (shipmentDetail == null)
            {
                if (shipmentResponse.RateResponse.Errors.Count > 0)
                {
                    for (int i = 0; i < shipmentResponse.RateResponse.Errors.Count; i++)
                    {
                        context.Abort(await context.CommerceContext.AddMessage(
                                          context.GetPolicy <KnownResultCodes>().Error,
                                          "UnavailableServiceType",
                                          new object[1] {
                            shipmentResponse.RateResponse.Errors[i].Message
                        }
                                          ).ConfigureAwait(continueOnCapturedContext: false), context);
                    }
                }

                return(null);
            }


            return(shipmentDetail.ShippingAmount);
        }
示例#12
0
        public static async Task UnlockMerchantAccountAsync(Web3 web3, CommercePipelineExecutionContext context)
        {
            var ethPolicy = context.GetPolicy <EthereumClientPolicy>();

            if (ethPolicy == null)
            {
                context.Logger.LogError("Ethereum: missing policy configuration.");
                return;
            }

            var unlockResult = false;

            try
            {
                unlockResult = await web3.Personal.UnlockAccount.SendRequestAsync(ethPolicy.MerchantAccountAddress, ethPolicy.MerchantAccountPassword, 3600);
            }
            catch (Exception ex)
            {
                context.Logger.LogError($"Ethereum: error occured while trying to unlock the {ethPolicy.MerchantAccountAddress} account. Make sure the proper contract address and password was specified in the EthereumClientPolicy.", ex);
                return;
            }

            if (!unlockResult)
            {
                context.Logger.LogError("Ethereum: unable to unlock the account. Make sure the proper contract address and password was specified in the EthereumClientPolicy.");
                throw new Exception($"Ethereum: Unable to unlock account {ethPolicy.MerchantAccountAddress}.");
            }
        }
        protected virtual void CreateTierDetailsViews(PriceCard card, string snapshotId, EntityView pricingView, CommercePipelineExecutionContext context)
        {
            pricingView.UiHint = "Table";

            if (card == null || !card.Snapshots.Any() || string.IsNullOrEmpty(snapshotId))
            {
                return;
            }

            PriceSnapshotComponent snapshotComponent = card.Snapshots.FirstOrDefault(s => s.Id.Equals(snapshotId, StringComparison.OrdinalIgnoreCase));

            if (snapshotComponent == null)
            {
                return;
            }

            var membershipTiersComponent = snapshotComponent.GetComponent <MembershipTiersComponent>();

            if (membershipTiersComponent == null || !membershipTiersComponent.Tiers.Any())
            {
                return;
            }

            List <CustomPriceTier> list = membershipTiersComponent.Tiers.ToList();

            foreach (IGrouping <string, CustomPriceTier> grouping in list.GroupBy(t => t.Currency))
            {
                pricingView.ChildViews.Add(new EntityView
                {
                    EntityId = card.Id,
                    ItemId   = snapshotComponent.Id + "|" + grouping.Key,
                    Name     = context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow
                });
            }
        }
        public override async Task <RuleSet> Run(IEnumerable <RuleModel> arg, CommercePipelineExecutionContext context)
        {
            BuildRuleSetBlock buildRuleSetBlock = this;
            List <RuleModel>  ruleModels        = arg as List <RuleModel> ?? arg.ToList <RuleModel>();

            // ISSUE: explicit non-virtual call
            Condition.Requires <List <RuleModel> >(ruleModels).IsNotNull <List <RuleModel> >(string.Format("{0}: The argument cannot be null", (object)(buildRuleSetBlock.Name)));
            CommercePipelineExecutionContext executionContext;

            if (!ruleModels.Any <RuleModel>())
            {
                executionContext = context;
                executionContext.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, "RulesCannotBeNullOrEmpty", (object[])null, "Rules cannot be null or empty."), (object)context);
                executionContext = (CommercePipelineExecutionContext)null;
                return((RuleSet)null);
            }
            buildRuleSetBlock._ruleBuilder = buildRuleSetBlock._services.GetService <IRuleBuilderInit>();
            RuleSet ruleSet1 = new RuleSet();

            ruleSet1.Id = string.Format("{0}{1:N}", (object)CommerceEntity.IdPrefix <RuleSet>(), (object)Guid.NewGuid());
            RuleSet ruleSet = ruleSet1;

            foreach (RuleModel model in ruleModels.Where <RuleModel>((Func <RuleModel, bool>)(rm => rm != null)))
            {
                try
                {
                    ruleSet.Rules.Add(buildRuleSetBlock.BuildRule(model));
                }
                catch (Exception ex)
                {
                    executionContext = context;
                    CommerceContext commerceContext = context.CommerceContext;
                    string          error           = context.GetPolicy <KnownResultCodes>().Error;
                    string          commerceTermKey = "RuleNotBuilt";
                    object[]        args            = new object[2]
                    {
                        (object)model.Name,
                        (object)ex
                    };
                    string defaultMessage = string.Format("Rule '{0}' cannot be built.", (object)model.Name);
                    executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, args, defaultMessage), (object)context);
                    executionContext = (CommercePipelineExecutionContext)null;
                    return((RuleSet)null);
                }
            }
            return(ruleSet);
        }
        public static async Task <T> GetSettingPolicy <T>(this CommercePipelineExecutionContext context, CommerceCommander commander) where T : Policy
        {
            var activeSetting = await commander.Command <GetActiveSettingCommand>().Process(context.CommerceContext);

            return(activeSetting?.HasPolicy <T>() ?? false
                ? activeSetting.GetPolicy <T>()
                : context.GetPolicy <T>());
        }
        protected override List <string> GetApplicableViewNames(CommercePipelineExecutionContext context)
        {
            var viewsPolicy = context.GetPolicy <KnownPromotionsViewsPolicy>();

            return(new List <string>()
            {
                viewsPolicy?.Master
            });
        }
        public override Task <IEnumerable <NexusAddress> > RunAsync(Cart arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The cart can not be null");
            if (!arg.HasComponent <FulfillmentComponent>())
            {
                return(Task.FromResult <IEnumerable <NexusAddress> >(null));
            }
            var policy = context.GetPolicy <TaxFrameworkPolicy>();

            return(Task.FromResult(policy.NexusAddresses.AsEnumerable()));
        }
示例#18
0
        private async Task <List <Selection> > TryGetFormats(CommercePipelineExecutionContext context)
        {
            var policy           = context.GetPolicy <SelectOptionControlPanelPolicy>();
            var termPath         = $"{policy.StoreFrontPath}/{context.CommerceContext.CurrentShopName()}/{policy.CommerceTermsPath}";
            var localizedOptions = await this.Commander.Pipeline <IGetLocalizedLanguagesPipeline>().Run(new LocalizedTermArgument(policy.FormatsPath, termPath), context);

            return(localizedOptions?.Select(term => new Selection()
            {
                DisplayName = term.Value, Name = term.Key
            }).ToList() ?? new List <Selection>());
        }
        public override Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The argument cannot be null");
            EntityViewArgument entityViewArgument = context.CommerceContext.GetObjects <EntityViewArgument>().FirstOrDefault();

            if (string.IsNullOrEmpty(entityViewArgument?.ViewName) ||
                !(entityViewArgument.Entity is PriceCard) ||
                !entityViewArgument.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().Master, StringComparison.OrdinalIgnoreCase) &&
                !entityViewArgument.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceCardSnapshots, StringComparison.OrdinalIgnoreCase) &&
                (!entityViewArgument.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, StringComparison.OrdinalIgnoreCase) &&
                 !entityViewArgument.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing, StringComparison.OrdinalIgnoreCase)) ||
                (entityViewArgument.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing, StringComparison.OrdinalIgnoreCase) &&
                 string.IsNullOrEmpty(entityViewArgument.ItemId) ||
                 entityViewArgument.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, StringComparison.OrdinalIgnoreCase) &&
                 !string.IsNullOrEmpty(entityViewArgument.ForAction)))
            {
                return(Task.FromResult(arg));
            }

            PriceCard card = (PriceCard)entityViewArgument.Entity;

            if (entityViewArgument.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing, StringComparison.OrdinalIgnoreCase))
            {
                CreateTierDetailsViews(card, entityViewArgument.ItemId, arg, context);
                return(Task.FromResult(arg));
            }

            List <EntityView> views = new List <EntityView>();

            FindViews(views, arg, context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, context.CommerceContext);

            views.ForEach(snapshotDetailsView =>
            {
                EntityView pricingView = new EntityView()
                {
                    EntityId = card.Id,
                    ItemId   = snapshotDetailsView.ItemId,
                    Name     = context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing
                };
                snapshotDetailsView.ChildViews.Add(pricingView);
                CreateTierDetailsViews(card, snapshotDetailsView.ItemId, pricingView, context);
            });

            return(Task.FromResult(arg));
        }
示例#20
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The argument cannot be null");
            var viewsPolicy = context.GetPolicy <KnownCatalogViewsPolicy>();
            var request     = context.CommerceContext.GetObject <EntityViewArgument>();

            if (string.IsNullOrEmpty(request?.ViewName) || !request.ViewName.Equals(viewsPolicy.Master, StringComparison.OrdinalIgnoreCase) && !request.ViewName.Equals(viewsPolicy.Details, StringComparison.OrdinalIgnoreCase) && (!request.ViewName.Equals(viewsPolicy.Variant, StringComparison.OrdinalIgnoreCase) && !request.ViewName.Equals(viewsPolicy.ConnectSellableItem, StringComparison.OrdinalIgnoreCase)))
            {
                return(entityView);
            }
            if (request.ForAction.Equals("AssociateSellableItemToCatalog", StringComparison.OrdinalIgnoreCase) || request.ForAction.Equals("AssociateSellableItemToCategory", StringComparison.OrdinalIgnoreCase))
            {
                this.AssociateToCatalogOrCategory(context, entityView, request, request.ForAction);
                return(entityView);
            }
            var num          = request.ForAction.Equals("AddSellableItem", StringComparison.OrdinalIgnoreCase) ? 1 : 0;
            var isEditAction = request.ForAction.Equals("EditSellableItemDetails", StringComparison.OrdinalIgnoreCase);

            if (num != 0 && request.ViewName.Equals(viewsPolicy.Details, StringComparison.OrdinalIgnoreCase))
            {
                await this.AddEntityProperties(context, entityView, entityView, null, true, false, request.ViewName);

                return(await Task.FromResult(entityView));
            }
            if (isEditAction && request.ViewName.Equals(viewsPolicy.Details, StringComparison.OrdinalIgnoreCase))
            {
                await this.AddEntityProperties(context, entityView, entityView, (SellableItem)request.Entity, false, true, request.ViewName);

                return(await Task.FromResult(entityView));
            }
            if (!(request.Entity is SellableItem) || !string.IsNullOrEmpty(request.ForAction))
            {
                return(entityView);
            }
            var detailsView = entityView;

            if (request.ViewName.Equals(viewsPolicy.Master, StringComparison.OrdinalIgnoreCase) || request.ViewName.Equals(viewsPolicy.Variant, StringComparison.OrdinalIgnoreCase) || request.ViewName.Equals(viewsPolicy.ConnectSellableItem, StringComparison.OrdinalIgnoreCase))
            {
                var entityView1 = new EntityView
                {
                    EntityId      = request.Entity.Id ?? string.Empty,
                    EntityVersion = request.Entity.EntityVersion,
                    Name          = viewsPolicy.Details,
                    UiHint        = "Flat"
                };
                detailsView = entityView1;
                entityView.ChildViews.Add(detailsView);
            }
            await this.AddEntityProperties(context, entityView, detailsView, (SellableItem)request.Entity, false, false, request.ViewName);

            return(await Task.FromResult(entityView));
        }
示例#21
0
 private string GetConnectionString()
 {
     try
     {
         var policy = _context.GetPolicy <Policies.AbandonCartsPolicy>();
         using (var connection = new SqlConnection(policy.ConnectionString))
         {
             // It worked, we can save this as our connection string
             return(policy.ConnectionString);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
        /// <summary>The execute.</summary>
        /// <param name="arg">The pipeline argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="EntityView"/>.</returns>
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The argument can not be null");

            var entityViewArgument = context.CommerceContext.GetObject <EntityViewArgument>();
            var policy             = context.CommerceContext.GetPolicy <KnownCatalogViewsPolicy>();
            var enablementPolicy   = context.GetPolicy <Policies.CatalogFeatureEnablementPolicy>();

            if (string.IsNullOrEmpty(entityViewArgument?.ViewName) ||
                !entityViewArgument.ViewName.Equals(policy.Master, StringComparison.OrdinalIgnoreCase) &&
                !entityViewArgument.ViewName.Equals(policy.Variant, StringComparison.OrdinalIgnoreCase))
            {
                return(await Task.FromResult(entityView).ConfigureAwait(false));
            }

            var sellableItem = entityViewArgument.Entity as SellableItem;

            if (sellableItem == null)
            {
                return(await Task.FromResult(entityView).ConfigureAwait(false));
            }

            if (enablementPolicy.CatalogNavigationView)
            {
                await this.AddCatalogNavigationView(entityView, sellableItem, context).ConfigureAwait(false);
            }

            if (enablementPolicy.RenderVariantSellableItemLink &&
                entityViewArgument.ViewName.Equals(policy.Variant, StringComparison.OrdinalIgnoreCase) &&
                string.IsNullOrEmpty(entityViewArgument.ForAction))
            {
                this.UpdateVariantView(entityView, sellableItem, context);
            }

            var isBundle = sellableItem.HasComponent <BundleComponent>();

            if (enablementPolicy.VariationProperties &&
                !isBundle &&
                entityViewArgument.ViewName.Equals(policy.Master, StringComparison.OrdinalIgnoreCase) &&
                string.IsNullOrEmpty(entityViewArgument.ForAction))
            {
                var variantsView = entityView.ChildViews.FirstOrDefault(c => c.Name == policy.SellableItemVariants) as EntityView;
                UpdateVariantsView(variantsView, sellableItem, context);
            }

            return(await Task.FromResult(entityView).ConfigureAwait(false));
        }
示例#23
0
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">
        /// The pipeline argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="PipelineArgument"/>.
        /// </returns>
        public async override Task <IEnumerable <LocalizedTerm> > Run(IEnumerable <LocalizedTerm> arg, CommercePipelineExecutionContext context)
        {
            if (arg != null)
            {
                return(arg); // Return the argument we retrieved from the cache
            }

            var policy = context.GetPolicy <ProductFeaturesControlPanelPolicy>();

            string currentLanguage = context.CommerceContext.CurrentLanguage();

            ILocalizableTermsPipeline localizableTermsPipeline = this.Commander.Pipeline <ILocalizableTermsPipeline>();
            LocalizableTermArgument   localizableTermArgument  = new LocalizableTermArgument(string.Empty, policy.AvailableProductFeaturesPath);

            localizableTermArgument.Language = currentLanguage;

            return(await localizableTermsPipeline.Run(localizableTermArgument, context));
        }
示例#24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="cart"></param>
        /// <param name="getProductCommand"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        internal static decimal GetCartShippingRate(string name, Cart cart, GetProductCommand getProductCommand, CommercePipelineExecutionContext context)
        {
            var rates = GetCartShippingRates(cart, getProductCommand, context.GetPolicy <FedExClientPolicy>(), context.CommerceContext);

            if (rates == null || !rates.Any())
            {
                return(0m);
            }
            try
            {
                return(rates.FirstOrDefault(x => x.Key == name.ToLower()).Value);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            return(0m);
        }
        /// <summary>
        /// Run
        /// </summary>
        /// <param name="arg">arg</param>
        /// <param name="context">context</param>
        /// <returns>flag if the process was sucessfull</returns>
        public override async Task <bool> Run(IList <CustomComposerTemplate> arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name}: The argument can not be null");
            ComposerTemplatesSyncPolicy policy = context.GetPolicy <ComposerTemplatesSyncPolicy>();

            try
            {
                string json = JsonConvert.SerializeObject(arg);
                using (var writer = File.CreateText(policy.PathToJson))
                {
                    writer.Write(json);
                }
            }
            catch (Exception e)
            {
                Log.Information("WriteEntityViewsToDisc failed to write to disc ... " + e.Message);
                return(await Task.FromResult(false));
            }

            return(await Task.FromResult(true));
        }
示例#26
0
        public override async Task <EntityView> RunAsync(EntityView arg, CommercePipelineExecutionContext context)
        {
            var entityViewArgument = context.CommerceContext.GetObject <EntityViewArgument>();

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

            var knownOrderViewPolicy = context.GetPolicy <KnownOrderViewsPolicy>();

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

            if (!entityViewArgument.ViewName.Contains("OrdersList"))
            {
                return(arg);
            }

            var orderListEntityView = arg.ChildViews.OfType <EntityView>();

            foreach (var entityView in orderListEntityView)
            {
                var orderId = entityView.ItemId;
                var order   = await this.getOrderPipeline.RunAsync(orderId, context);

                if (order != null)
                {
                    entityView.Properties.Add(new ViewProperty()
                    {
                        Name     = "OrderNumber",
                        RawValue = order.GetComponent <OrderNumberComponent>()?.OrderNumber
                    });
                }
            }

            return(arg);
        }
        public override async Task <IEnumerable <CommerceProxy.Sitecore.Commerce.Plugin.Composer.ComposerTemplate> > Run(GetProxyComposerTemplatesArgument arg, CommercePipelineExecutionContext context)
        {
            GetProxyComposerTemplatesBlock getProxyComposerTemplatesBlock = this;

            Condition.Requires(arg).IsNotNull(getProxyComposerTemplatesBlock.Name + ": The GetContainerArgument cannot be null.");

            var appEnvironment = context.GetPolicy <KnownApplicationEnvironmentsPolicy>()?.Environments
                                 .FirstOrDefault(x => x.Name.Equals(arg.ApplicationEnvironmentName, System.StringComparison.InvariantCultureIgnoreCase));
            var getProxyContainerArgument = new GetProxyContainerArgument(
                appEnvironment.BaseUri,
                appEnvironment.ShopName,
                appEnvironment.Environment,
                appEnvironment.ShopperId,
                appEnvironment.CustomerId,
                appEnvironment.Language,
                appEnvironment.Currency,
                appEnvironment.CommerceEngineCertHeaderName,
                appEnvironment.CertThumbprint,
                appEnvironment.CertStoreLocation,
                appEnvironment.CertStoreName);

            var container = await getProxyComposerTemplatesBlock._getProxyContainerPipeline.Run(getProxyContainerArgument, context).ConfigureAwait(false);

            IEnumerable <CommerceProxy.Sitecore.Commerce.Plugin.Composer.ComposerTemplate> composerTemplates;

            if (arg.TemplateIds != null && arg.TemplateIds.Length > 0)
            {
                composerTemplates = Proxy.Execute(container.ComposerTemplatesByIdsExpandComponents(arg.TemplateIds));
            }
            else
            {
                composerTemplates = Proxy.Execute(container.ComposerTemplates.Expand("Components"));
            }

            return(composerTemplates);
        }
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>
        /// The collection of profile definitions <see cref="ProfileDefinition" />.
        /// </returns>
        public override async Task <IEnumerable <ProfileDefinition> > Run(string arg, CommercePipelineExecutionContext context)
        {
            var    cachePolicy = context.GetPolicy <ProfilesCsCachePolicy>();
            var    cacheKey    = string.IsNullOrEmpty(arg) ? "ProfileDefinition.All" : $"{arg}";
            ICache cache       = null;

            if (cachePolicy.AllowCaching)
            {
                cache = await this._cachePipeline.Run(new EnvironmentCacheArgument { CacheName = cachePolicy.CacheName }, context);

                var item = await cache.Get(cacheKey) as List <ProfileDefinition>;

                if (item != null)
                {
                    return(item);
                }
            }

            try
            {
                var schema     = new List <ProfileDefinition>();
                var sqlContext = ConnectionHelper.GetProfilesSqlContext(context.CommerceContext);
                if (string.IsNullOrEmpty(arg))
                {
                    schema = await sqlContext.GetAllProfileDefinitions();

                    if (schema != null && schema.Count > 0)
                    {
                        if (cachePolicy.AllowCaching && cache != null)
                        {
                            await cache.Set(cacheKey, new Cachable <List <ProfileDefinition> >(schema, 1), cachePolicy.GetCacheEntryOptions());
                        }

                        context.CommerceContext.AddUniqueObjectByType(schema);
                        return(schema);
                    }
                }
                else
                {
                    var profileDefinition = await sqlContext.GetProfileDefinition(arg);

                    if (profileDefinition != null)
                    {
                        schema.Add(profileDefinition);
                        if (cachePolicy.AllowCaching && cache != null)
                        {
                            await cache.Set(cacheKey, new Cachable <List <ProfileDefinition> >(schema, 1), cachePolicy.GetCacheEntryOptions());
                        }

                        return(schema);
                    }
                }

                await context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    "EntityNotFound",
                    new object[] { arg },
                    $"Entity {arg} was not found.");

                return(null);
            }
            catch (Exception ex)
            {
                await context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    "EntityNotFound",
                    new object[] { arg, ex },
                    $"Entity {arg} was not found.");

                return(null);
            }
        }
示例#29
0
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">
        /// The argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// A list of <see cref="Entitlement"/>.
        /// </returns>
        public override async Task <IEnumerable <Entitlement> > Run(IEnumerable <Entitlement> arg, CommercePipelineExecutionContext context)
        {
            var entitlements = arg as List <Entitlement> ?? arg.ToList();

            Condition.Requires(entitlements).IsNotNull($"{this.Name}: The entitlements can not be null");

            var argument = context.CommerceContext.GetObjects <ProvisionEntitlementsArgument>().FirstOrDefault();

            if (argument == null)
            {
                return(entitlements.AsEnumerable());
            }

            var customer = argument.Customer;
            var order    = argument.Order;

            if (order == null)
            {
                return(entitlements.AsEnumerable());
            }

            var digitalTags          = context.GetPolicy <KnownEntitlementsTags>().DigitalProductTags;
            var lineWithDigitalGoods = order.Lines.Where(line => line != null &&
                                                         line.GetComponent <CartProductComponent>().HasPolicy <AvailabilityAlwaysPolicy>() &&
                                                         line.GetComponent <CartProductComponent>().Tags.Select(t => t.Name).Intersect(digitalTags, StringComparer.OrdinalIgnoreCase).Any()).ToList();

            if (!lineWithDigitalGoods.Any())
            {
                return(entitlements.AsEnumerable());
            }

            var hasErrors = false;

            foreach (var line in lineWithDigitalGoods)
            {
                foreach (var index in Enumerable.Range(1, (int)line.Quantity))
                {
                    try
                    {
                        var entitlement = new DigitalProduct();
                        var id          = Guid.NewGuid().ToString("N");
                        entitlement.Id         = $"{CommerceEntity.IdPrefix<DigitalProduct>()}{id}";
                        entitlement.FriendlyId = id;
                        entitlement.SetComponent(
                            new ListMembershipsComponent
                        {
                            Memberships =
                                new List <string>
                            {
                                $"{CommerceEntity.ListName<DigitalProduct>()}",
                                $"{CommerceEntity.ListName<Entitlement>()}"
                            }
                        });
                        entitlement.Order = new EntityReference(order.Id, order.Name);
                        if (customer != null)
                        {
                            entitlement.Customer = new EntityReference(customer.Id, customer.Name);
                        }

                        await this._persistEntityPipeline.Run(new PersistEntityArgument(entitlement), context);

                        entitlements.Add(entitlement);
                        context.Logger.LogInformation(
                            $"DigitalProduct Entitlement Created - Order={order.Id}, LineId={line.Id}, EntitlementId={entitlement.Id}");
                    }
                    catch
                    {
                        hasErrors = true;
                        context.Logger.LogError(
                            $"DigitalProduct Entitlement NOT Created - Order={order.Id}, LineId={line.Id}");
                        break;
                    }
                }

                if (hasErrors)
                {
                    break;
                }
            }

            if (!hasErrors)
            {
                return(entitlements.AsEnumerable());
            }

            context.Abort(
                context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    "ProvisioningEntitlementErrors",
                    new object[] { order.Id },
                    $"Error(s) occurred provisioning entitlements for order '{order.Id}'"),
                context);
            return(null);
        }
 /// <summary>Gets the action name.</summary>
 /// <param name="context">The context.</param
 /// <returns>The action name.</returns>
 protected override string GetActionName(CommercePipelineExecutionContext context)
 {
     return(context.GetPolicy <KnownPromotionsActionsPolicy>().SelectQualification);
 }