示例#1
0
        internal static List <KeyValuePair <string, decimal> > GetCartShippingRates(Cart cart,
                                                                                    IGetSellableItemPipeline getSellableItemPipeline, CommercePipelineExecutionContext context)
        {
            var input = new UpsReqestInput();

            UpsClientPolicy = context.GetPolicy <UpsClientPolicy>();
            if (cart != null && cart.Lines.Any <CartLineComponent>() && cart.HasComponent <PhysicalFulfillmentComponent>())
            {
                var component = cart.GetComponent <PhysicalFulfillmentComponent>();

                var shippingParty = component?.ShippingParty;

                input.AddressLine1  = shippingParty.Address1;
                input.AddressLine2  = shippingParty.Address2;
                input.City          = shippingParty.City;
                input.CountryCode   = shippingParty.CountryCode;
                input.StateCode     = shippingParty.StateCode;
                input.ZipPostalCode = shippingParty.ZipPostalCode;

                input.PriceValue = cart.Totals.SubTotal.Amount;

                decimal height = 0.0M;
                decimal width  = 0.0M;
                decimal length = 0.0m;
                decimal weight = 0.0m;

                foreach (var cartLineComponent in cart.Lines)
                {
                    // get specific weight value
                    var productArgument = ProductArgument.FromItemId(cartLineComponent.ItemId);
                    if (!productArgument.IsValid())
                    {
                        continue;
                    }
                    var     sellableItem = getSellableItemPipeline.Run(productArgument, context).Result;
                    var     product      = context.CommerceContext.Objects.OfType <Product>().FirstOrDefault <Product>((Product p) => p.ProductId.Equals(sellableItem.FriendlyId, StringComparison.OrdinalIgnoreCase));
                    decimal val          = 0m;
                    if (product != null)
                    {
                        if (product.HasProperty(UpsClientPolicy.WeightFieldName) && product[UpsClientPolicy.WeightFieldName].ToString().Trim() != "")
                        {
                            val = GetFirstDecimalFromString(product[UpsClientPolicy.WeightFieldName].ToString());
                        }
                        else
                        {
                            val = GetFirstDecimalFromString(UpsClientPolicy.Weight);
                        }

                        if (val > 0)
                        {
                            weight += val;
                        }

                        val = product.HasProperty(UpsClientPolicy.HeightFieldName) && product[UpsClientPolicy.HeightFieldName].ToString().Trim() != ""
                            ? GetFirstDecimalFromString(product[UpsClientPolicy.HeightFieldName].ToString())
                            : GetFirstDecimalFromString(UpsClientPolicy.Height);

                        if (val > 0)
                        {
                            height += val;
                        }

                        val = product.HasProperty(UpsClientPolicy.WidthFieldName) && product[UpsClientPolicy.WidthFieldName].ToString().Trim() != ""
                            ? GetFirstDecimalFromString(product[UpsClientPolicy.WidthFieldName].ToString())
                            : GetFirstDecimalFromString(UpsClientPolicy.Width);

                        if (val > 0 && val > width)
                        {
                            width = val;
                        }

                        val = product.HasProperty(UpsClientPolicy.LengthFieldName) && product[UpsClientPolicy.LengthFieldName].ToString().Trim() != ""
                            ? GetFirstDecimalFromString(product[UpsClientPolicy.LengthFieldName].ToString())
                            : GetFirstDecimalFromString(UpsClientPolicy.Length);

                        if (val > 0 && val > length)
                        {
                            length = val;
                        }
                    }
                }

                input.Height = Math.Ceiling(height).ToString(CultureInfo.CurrentCulture);
                input.Width  = Math.Ceiling(width).ToString(CultureInfo.CurrentCulture);
                input.Length = Math.Ceiling(length).ToString(CultureInfo.CurrentCulture);
                input.Weight = weight;
            }

            var rates = new List <KeyValuePair <string, decimal> >();

            rates = GetShippingRates(input, context);


            return(rates);
        }
        public override Task <IEnumerable <IndexingResult> > Run(IEnumerable <IndexingResult> arg, CommercePipelineExecutionContext context)
        {
            var indexingResults = arg.ToList();

            context.Status.Report($"Incremental indexing complete - {indexingResults.Count} items.");
            context.Logger.LogInformation($"Incremental indexing complete - {indexingResults.Count} items.");
            return(Task.FromResult(indexingResults.AsEnumerable()));
        }
示例#3
0
 /// <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>().AddBenefit);
 }
        public static IList <LocalizablePropertyValues> GetEntityLocalizableProperties(this CommercePipelineExecutionContext context, Type type)
        {
            var result = new List <LocalizablePropertyValues>();
            var localizeEntityPolicy = LocalizeEntityPolicy.GetPolicyByType(context.CommerceContext, type);

            if (localizeEntityPolicy?.Properties == null || !localizeEntityPolicy.Properties.Any())
            {
                return(result);
            }

            foreach (var property in localizeEntityPolicy.Properties)
            {
                result.Add(new LocalizablePropertyValues()
                {
                    PropertyName = property
                });
            }

            return(result);
        }
        public override Task <IEnumerable <RegisteredPluginModel> > Run(IEnumerable <RegisteredPluginModel> arg, CommercePipelineExecutionContext context)
        {
            if (arg == null)
            {
                return(Task.FromResult <IEnumerable <RegisteredPluginModel> >(arg));
            }

            List <RegisteredPluginModel> list = arg.ToList <RegisteredPluginModel>();

            PluginHelper.RegisterPlugin(this, list);

            return(Task.FromResult <IEnumerable <RegisteredPluginModel> >(list.AsEnumerable <RegisteredPluginModel>()));
        }
 public InstallationSellableItemToSellableItemRelationshipMapper(CommerceCommander commerceCommander,
                                                                 CommercePipelineExecutionContext context)
     : base(commerceCommander, context)
 {
 }
 public SellableItemInventoryImportHandler(string sourceEntity,
                                           CommerceCommander commerceCommander,
                                           CommercePipelineExecutionContext context)
     : base(sourceEntity, commerceCommander, context)
 {
 }
示例#8
0
 /// <summary>
 ///     Returns the name of the views that determines whether this is the display view for the entity
 /// </summary>
 /// <param name="context"></param>
 /// <returns>The name of the master view</returns>
 protected abstract List <string> GetApplicableViewNames(CommercePipelineExecutionContext context);
示例#9
0
 protected BaseRelationshipMapper(CommerceCommander commerceCommander,
                                  CommercePipelineExecutionContext context)
 {
     CommerceCommander = commerceCommander;
     Context           = context;
 }
示例#10
0
 public static bool IsNullOrHasErrors(this CommercePipelineExecutionContext context)
 {
     return(context?.CommerceContext == null || context.CommerceContext.AnyMessage(m => m.Code == context.GetPolicy <KnownResultCodes>().Error));
 }
示例#11
0
        public override async Task <EntityViewConditionsArgument> Run(EntityViewConditionsArgument arg, CommercePipelineExecutionContext context)
        {
            var applicableViewNames = GetApplicableViewNames(context);

            arg.ValidateEntity(ent => ent is EntityType);
            arg.ValidateDisplayView(viewName => applicableViewNames.Count(av => viewName.Equals(av, StringComparison.OrdinalIgnoreCase)) > 0);
            arg.ValidateEditView(action => action.StartsWith("Edit-", StringComparison.OrdinalIgnoreCase));

            return(await Task.FromResult(arg));
        }
示例#12
0
 public static async Task AbortWithError(this CommercePipelineExecutionContext context, string message, string key,
                                         string id)
 {
     context.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, key,
                                                            new object[] { id }, message), context);
 }
 protected BaseComponentMapper(IComponentHandler componentHandler, CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
 {
     ComponentHandler  = componentHandler;
     CommerceCommander = commerceCommander;
     Context           = context;
 }
        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>().WarrantyTags;
            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 Warranty();
                        var id          = Guid.NewGuid().ToString("N");
                        entitlement.Id         = $"{CommerceEntity.IdPrefix<Warranty>()}{id}";
                        entitlement.FriendlyId = id;
                        entitlement.SetComponent(
                            new ListMembershipsComponent
                        {
                            Memberships =
                                new List <string>
                            {
                                $"{CommerceEntity.ListName<Warranty>()}",
                                $"{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(
                            $"Warranty Entitlement Created - Order={order.Id}, LineId={line.Id}, EntitlementId={entitlement.Id}");
                    }
                    catch
                    {
                        hasErrors = true;
                        context.Logger.LogError(
                            $"Warranty 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);
        }
        public override async Task <List <string> > Run(string catalogName, CommercePipelineExecutionContext context)
        {
            List <InventorySet> inventorySets = new List <InventorySet>();

            GetProductsToUpdateInventoryBlock getProductsToUpdateInventoryBlock = this;

            // get the sitecoreid from catalog based on catalogname
            var catalogSitecoreId = "";
            FindEntitiesInListArgument entitiesInListArgumentCatalog = await getProductsToUpdateInventoryBlock._findEntitiesInListPipeline.Run(new FindEntitiesInListArgument(typeof(Catalog), string.Format("{0}", (object)CommerceEntity.ListName <Catalog>()), 0, int.MaxValue), context);

            foreach (CommerceEntity commerceEntity in (await getProductsToUpdateInventoryBlock._findEntitiesInListPipeline.Run(entitiesInListArgumentCatalog, (IPipelineExecutionContextOptions)context.ContextOptions)).List.Items)
            {
                var item = commerceEntity as Catalog;

                if (item.Name == catalogName)
                {
                    catalogSitecoreId = item.SitecoreId;
                    break;
                }
            }


            if (string.IsNullOrEmpty(catalogSitecoreId))
            {
                return(null);
            }

            List <string> productIds = new List <string>();

            string             cacheKey    = string.Format("{0}|{1}|{2}", context.CommerceContext.Environment.Name, context.CommerceContext.CurrentLanguage(), context.CommerceContext.CurrentShopName() ?? "");
            CatalogCachePolicy cachePolicy = context.GetPolicy <CatalogCachePolicy>();

            IList <SellableItem> sellableItems = null;

            if (cachePolicy.AllowCaching)
            {
                sellableItems = await _commerceCommander.GetCacheEntry <IList <SellableItem> >(context.CommerceContext, cachePolicy.CacheName, cacheKey).ConfigureAwait(false);
            }

            if (sellableItems != null)
            {
                foreach (var item in sellableItems)
                {
                    await GetProductId(context, getProductsToUpdateInventoryBlock, catalogSitecoreId, productIds, item);
                }
            }
            else
            {
                sellableItems = new List <SellableItem>();
                FindEntitiesInListArgument entitiesInListArgument = new FindEntitiesInListArgument(typeof(SellableItem), string.Format("{0}", (object)CommerceEntity.ListName <SellableItem>()), 0, int.MaxValue);
                foreach (CommerceEntity commerceEntity in (await getProductsToUpdateInventoryBlock._findEntitiesInListPipeline.Run(entitiesInListArgument, context.ContextOptions).ConfigureAwait(false)).List.Items)
                {
                    await GetProductId(context, getProductsToUpdateInventoryBlock, catalogSitecoreId, productIds, commerceEntity as SellableItem).ConfigureAwait(false);
                }

                if (cachePolicy.AllowCaching)
                {
                    await _commerceCommander.SetCacheEntry <IList <SellableItem> >(context.CommerceContext, cachePolicy.CacheName, cacheKey, (ICachable) new Cachable <IList <SellableItem> >(sellableItems, 1L), cachePolicy.GetCacheEntryOptions()).ConfigureAwait(false);
                }
            }

            return(productIds);
        }
示例#16
0
        public override async Task <IEnumerable <ComposerTemplate> > Run(GetComposerTemplatesArgument arg, CommercePipelineExecutionContext context)
        {
            GetComposerTemplatesBlock getComposerTemplatesBlock = this;

            Condition.Requires(arg).IsNotNull(getComposerTemplatesBlock.Name + ": The entity view cannot be null.");

            IEnumerable <ComposerTemplate> composerTemplates = Enumerable.Empty <ComposerTemplate>();

            if (arg.TemplateIds == null || arg.TemplateIds.Length <= 0)
            {
                return(composerTemplates);
            }

            composerTemplates = (await getComposerTemplatesBlock._findEntitiesInListPipeline.Run(new FindEntitiesInListArgument(typeof(ComposerTemplate), CommerceEntity.ListName <ComposerTemplate>() ?? "", 0, int.MaxValue), context).ConfigureAwait(false))
                                ?.List
                                ?.Items
                                .Cast <ComposerTemplate>()
                                .Where(x => arg.TemplateIds.Contains(x.Id))
                                .ToList();

            return(composerTemplates);
        }
示例#17
0
        public static IList <LocalizableComponentPropertiesValues> GetEntityComponentProperties(Type type, CommercePipelineExecutionContext context)
        {
            if (EntityComponentLocalizableProperties.ContainsKey(type))
            {
                return(EntityComponentLocalizableProperties[type]);
            }

            lock (LockEntityComponentProperties)
            {
                if (EntityComponentLocalizableProperties.ContainsKey(type))
                {
                    return(EntityComponentLocalizableProperties[type]);
                }

                EntityComponentLocalizableProperties.Add(type, context.GetEntityComponentsLocalizableProperties(type));
                return(EntityComponentLocalizableProperties[type]);
            }
        }
示例#18
0
 protected CatalogSynchronizerBase(CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
 {
     _commerceCommander = commerceCommander;
     _context           = context;
 }
示例#19
0
        protected override string GetMasterViewName(CommercePipelineExecutionContext context)
        {
            var viewsPolicy = context.GetPolicy <KnownCustomerViewsPolicy>();

            return(viewsPolicy?.Master);
        }
示例#20
0
 protected BaseCommerceEntityComponentMapper(TSourceEntity sourceEntity, IComponentHandler componentHandler, CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
     : base(componentHandler, commerceCommander, context)
 {
     SourceEntity = sourceEntity;
 }
        public static IList <LocalizableComponentPropertiesValues> GetEntityComponentsLocalizableProperties(this CommercePipelineExecutionContext context, Type type)
        {
            var result = new List <LocalizableComponentPropertiesValues>();
            var localizeEntityPolicy = LocalizeEntityPolicy.GetPolicyByType(context.CommerceContext, type);

            if (localizeEntityPolicy?.ComponentsPolicies == null || !localizeEntityPolicy.ComponentsPolicies.Any())
            {
                return(result);
            }

            foreach (var componentsPolicy in localizeEntityPolicy.ComponentsPolicies)
            {
                if (componentsPolicy.Properties == null || !componentsPolicy.Properties.Any())
                {
                    continue;
                }

                var componentProperties = new LocalizableComponentPropertiesValues();
                result.Add(componentProperties);
                componentProperties.Path           = componentsPolicy.Path;
                componentProperties.PropertyValues = new List <LocalizablePropertyValues>();
                foreach (var componentsPolicyProperty in componentsPolicy.Properties)
                {
                    componentProperties.PropertyValues.Add(new LocalizablePropertyValues
                    {
                        PropertyName = componentsPolicyProperty
                    });
                }
            }

            return(result);
        }
 public override Task <List <Sitecore.Commerce.Core.LocalizedTerm> > Run(CommerceTermsArgument arg, CommercePipelineExecutionContext context)
 {
     return(Task.FromResult(new List <LocalizedTerm>(0)));
 }
 /// <inheritdoc />
 public SourceCustomEntityImportHandler(string customEntity, CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
     : base(customEntity, commerceCommander, context)
 {
 }
示例#24
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);
        }
示例#25
0
        /// <summary>
        /// The run.
        /// </summary>
        /// <param name="arg">
        /// The argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The list of <see cref="RegisteredPluginModel"/>
        /// </returns>
        public override Task <IEnumerable <RegisteredPluginModel> > Run(IEnumerable <RegisteredPluginModel> arg, CommercePipelineExecutionContext context)
        {
            if (arg == null)
            {
                return(Task.FromResult((IEnumerable <RegisteredPluginModel>)null));
            }

            var plugins = arg.ToList();

            PluginHelper.RegisterPlugin(this, plugins);

            return(Task.FromResult(plugins.AsEnumerable()));
        }
 /// <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>().EditQualification);
 }
示例#27
0
 protected BaseVariantComponentMapper(TSourceEntity sourceEntity, TSourceVariant sourceVariant, CommerceEntity commerceEntity, Component parentComponent, CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
     : base(sourceEntity, new CommerceParentComponentChildComponentHandler(commerceEntity, parentComponent), commerceCommander, context)
 {
     SourceVariant = sourceVariant;
 }
 protected BaseEntityImportHandler(string sourceEntity, CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
 {
     SourceEntity      = JsonConvert.DeserializeObject <TSourceEntity>(sourceEntity);
     CommerceCommander = commerceCommander;
     Context           = context;
 }
示例#29
0
 /// <summary>Gets the entity view name.</summary>
 /// <param name="context">The context.</param
 /// <returns>The entity view name.</returns>
 protected override string GetEntityViewName(CommercePipelineExecutionContext context)
 {
     return(context.GetPolicy <KnownPromotionsViewsPolicy>().BenefitDetails);
 }
示例#30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="name"></param>
        /// <param name="cart"></param>
        /// <param name="getSellableItemPipeline"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        internal static decimal GetCartShippingRate(string name, Cart cart, IGetSellableItemPipeline getSellableItemPipeline, CommercePipelineExecutionContext context)
        {
            var rates = GetCartShippingRates(cart, getSellableItemPipeline, context);

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

            return(0m);
        }