Exemple #1
0
        public override async Task <ImportSingleCsvLineArgument> Run(ImportSingleCsvLineArgument arg, CommercePipelineExecutionContext context)
        {
            const string viewName         = "Sizing";
            var          composerTemplate = await GetComposerTemplate(viewName, context);

            if (composerTemplate == null)
            {
                context.Abort("Sizing Composer Template not found", this);
                return(arg);
            }

            var sellableItem = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), arg.Line.ProductId.ToEntityId <SellableItem>()), context);

            if (sellableItem == null)
            {
                context.Abort("Unable to populate EntityView data, SellableItem not found", this);
                return(arg);
            }

            var entityViewComponent = GetPopulatedEntityViewComponent(arg, composerTemplate, viewName);

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

            sellableItem.Components.Add(entityViewComponent);
            await _persistEntityPipeline.Run(new PersistEntityArgument(sellableItem), context);

            return(arg);
        }
        public async override Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            EntityViewArgument request = context.CommerceContext.GetObject <EntityViewArgument>();


            if (request?.ViewName == "LoyaltyCoupons")
            {
                entityView.DisplayName = "Loyalty Coupons";


                var customer =
                    await _findEntity.Run(new FindEntityArgument(typeof(Customer), entityView.EntityId), context) as Customer;

                if (customer == null || !customer.HasComponent <LoyaltySummary>() || customer.GetComponent <LoyaltySummary>().CouponEntities.Count == 0)
                {
                    return(entityView);
                }

                IEnumerable <EntityView> models = await Task.WhenAll(customer.GetComponent <LoyaltySummary>().CouponEntities.Select(id => GetCouponView(id, context)));


                entityView.ChildViews.AddRange(models);
            }

            return(entityView);
        }
        public override async Task <ImportMembershipPricesArgument> Run(ImportMembershipPricesArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{Name}: The argument can not be null");

            var priceBook = await _findEntityPipeline.Run(new FindEntityArgument(typeof(PriceBook), $"{CommerceEntity.IdPrefix<PriceBook>()}{arg.PriceBookName}"),
                                                          context).ConfigureAwait(false) as PriceBook;

            foreach (var price in arg.Prices)
            {
                var priceCardName = $"PriceCard_{price.XCProductId}";
                var priceCard     = await UpdateOrCreatePriceCard(context, priceBook, priceCardName).ConfigureAwait(false);

                if (priceCard != null)
                {
                    priceCard.Snapshots = new List <PriceSnapshotComponent>();

                    foreach (var membershipSnapshot in price.Snapshots)
                    {
                        if (membershipSnapshot.EffectiveDate != null && membershipSnapshot.Prices != null && membershipSnapshot.Prices.Any())
                        {
                            priceCard = await UpdateOrCreatePriceSnapshot(context, priceCard,
                                                                          membershipSnapshot.EffectiveDate, membershipSnapshot.Prices).ConfigureAwait(false);
                        }
                    }

                    if (priceCard != null)
                    {
                        var newSnapshots = priceCard.Snapshots.Where(x => !x.IsApproved(context.CommerceContext)).ToList();

                        foreach (var snapshot in newSnapshots)
                        {
                            snapshot.SetComponent(new ApprovalComponent(context.GetPolicy <ApprovalStatusPolicy>().Approved));
                        }

                        if (newSnapshots.Any())
                        {
                            priceCard = (await _persistEntityPipeline.Run(new PersistEntityArgument(priceCard), context).ConfigureAwait(false)).Entity as PriceCard;
                        }
                    }

                    var sellableItem = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), $"{CommerceEntity.IdPrefix<SellableItem>()}{price.XCProductId}"), context)
                                       .ConfigureAwait(false) as SellableItem;

                    if (sellableItem != null && priceCard != null)
                    {
                        sellableItem.GetPolicy <PriceCardPolicy>().PriceCardName = priceCard.Name;
                        await _persistEntityPipeline.Run(new PersistEntityArgument(sellableItem), context).ConfigureAwait(false);

                        Log.Information($"Product Importer: PriceCard {priceCard.Name} was set for {sellableItem.Id}");
                    }
                }
            }

            return(arg);
        }
Exemple #4
0
        public virtual async Task <CommerceEntity> Process(
            CommerceContext commerceContext,
            string itemId,
            bool filterVariations)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                CommercePipelineExecutionContextOptions pipelineContextOptions = commerceContext.GetPipelineContextOptions();

                if (itemId.Contains("|"))
                {
                    itemId = itemId.Replace("|", ",");
                }

                if (!string.IsNullOrEmpty(itemId))
                {
                    if (itemId.Split(',').Length == 3)
                    {
                        var             strArray        = itemId.Split(',');
                        ProductArgument productArgument = new ProductArgument(strArray[0], strArray[1])
                        {
                            VariantId = strArray[2]
                        };

                        var sellableItem = await _pipeline.Run(productArgument, pipelineContextOptions).ConfigureAwait(false);

                        var catalog = await _findEntityPipeline.Run(new FindEntityArgument(typeof(Catalog), CommerceEntity.IdPrefix <Catalog>() + productArgument.CatalogName), pipelineContextOptions).ConfigureAwait(false) as Catalog;

                        if (catalog != null && sellableItem != null && sellableItem.HasPolicy <PriceCardPolicy>())
                        {
                            var    priceCardName = sellableItem.GetPolicy <PriceCardPolicy>();
                            string entityId      = $"{CommerceEntity.IdPrefix<PriceCard>()}{catalog.PriceBookName}-{priceCardName.PriceCardName}";


                            CommerceEntity commerceEntity = await _findEntityPipeline.Run(new FindEntityArgument(typeof(PriceCard), entityId), pipelineContextOptions).ConfigureAwait(false);

                            return(commerceEntity);
                        }
                    }
                }

                string str = await pipelineContextOptions.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().Error, "ItemIdIncorrectFormat", new object[]
                {
                    itemId
                }, "Expecting a CatalogId and a ProductId in the ItemId: " + itemId);

                return(null);
            }
        }
        public override async Task <SynchronizeProductArgument> Run(SynchronizeProductArgument arg, CommercePipelineExecutionContext context)
        {
            var sellableItem = arg.SellableItem;

            sellableItem.Brand = arg.ImportProduct.Brand;

            //Localize display name
            var localizedEntityComponent = sellableItem.GetComponent <LocalizedEntityComponent>();
            var localizedEntity          = (LocalizationEntity)await _findEntityPipeline.Run(
                new FindEntityArgument(typeof(LocalizationEntity), localizedEntityComponent.Entity.EntityTarget, true),
                context.CommerceContext.GetPipelineContextOptions());

            var displayNames = arg.ImportProduct.ProductName.Select(p => new Parameter(p.Language, p.Name)).ToList();

            localizedEntity.AddOrUpdatePropertyValue("DisplayName", displayNames);
            await _persistEntityPipeline.Run(new PersistEntityArgument(localizedEntity),
                                             context.CommerceContext.GetPipelineContextOptions());

            //Add identifiers
            var identifiersComponent = sellableItem.GetComponent <IdentifiersComponent>();

            identifiersComponent.SKU = arg.ImportProduct.ProductId;
            sellableItem.SetComponent(identifiersComponent);

            sellableItem = (await _persistEntityPipeline.Run(new PersistEntityArgument(sellableItem),
                                                             context.CommerceContext.GetPipelineContextOptions()))?.Entity as SellableItem ?? sellableItem;

            arg.SellableItem = sellableItem;
            return(arg);
        }
Exemple #6
0
        public virtual async Task <WishList> Process(CommerceContext commerceContext, string wishListId, WishListLineComponent line)
        {
            WishList result = null;

            using (CommandActivity.Start(commerceContext, this))
            {
                var context            = commerceContext.GetPipelineContextOptions();
                var findEntityArgument = new FindEntityArgument(typeof(WishList), wishListId);
                var wishList           = await _getPipeline.Run(findEntityArgument, context) as WishList;

                if (wishList == null)
                {
                    await context.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().ValidationError, "EntityNotFound", new object[] { wishListId }, string.Format("Entity {0} was not found.", wishListId));

                    return(null);
                }
                if (wishList.Lines.FirstOrDefault <WishListLineComponent>(c => c.Id == line.Id) == null)
                {
                    await context.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().ValidationError, "WishListLineNotFound", new object[] { line.Id }, string.Format("WishList line {0} was not found", line.Id));

                    return(wishList);
                }
                result = await _pipeline.Run(new WishListLineArgument(wishList, line), context);

                return(result);
            }
        }
        public override async Task <SynchronizeProductArgument> Run(SynchronizeProductArgument arg, CommercePipelineExecutionContext context)
        {
            if (arg.SellableItem == null || arg.ImportProduct.Categories == null || !arg.ImportProduct.Categories.Any())
            {
                return(arg);
            }

            foreach (var category in arg.ImportProduct.Categories)
            {
                var categoryId = $"{CommerceEntity.IdPrefix<Category>()}{arg.Catalog.Name}-{category.ProposeValidId()}";
                if (await _doesEntityExistPipeline.Run(
                        new FindEntityArgument(typeof(Sitecore.Commerce.Plugin.Catalog.Category), categoryId),
                        context.CommerceContext.GetPipelineContextOptions()))
                {
                    var associateResult = await _associateSellableItemToParentPipeline.Run(
                        new CatalogReferenceArgument(arg.Catalog.Id, categoryId, arg.SellableItem.Id),
                        context.CommerceContext.GetPipelineContextOptions());

                    arg.SellableItem = await _findEntityPipeline.Run(
                        new FindEntityArgument(typeof(Sitecore.Commerce.Plugin.Catalog.SellableItem),
                                               arg.SellableItem.Id), context.CommerceContext.GetPipelineContextOptions()) as SellableItem ?? arg.SellableItem;
                }
            }

            return(arg);
        }
        public virtual async Task <WishList> Process(CommerceContext commerceContext, string wishListId, WishListLineComponent line)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var context            = commerceContext.GetPipelineContextOptions();
                var findEntityArgument = new FindEntityArgument(typeof(WishList), wishListId, true);
                var wishList           = await _getPipeline.Run(findEntityArgument, context) as WishList;

                if (wishList == null)
                {
                    await context.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().ValidationError, "EntityNotFound", new object[] { wishListId }, string.Format("Entity {0} was not found.", wishListId));

                    return(null);
                }

                if (!wishList.IsPersisted)
                {
                    wishList.Id       = wishListId;
                    wishList.Name     = wishListId;
                    wishList.ShopName = commerceContext.CurrentShopName();
                }

                var result = await _addToWishListPipeline.Run(new WishListLineArgument(wishList, line), context);

                await _persistEntityPipeline.Run(new PersistEntityArgument(result), context);

                return(result);
            }
        }
        /// <summary>
        /// Gets all categories and associates the SellableItem to the correct category based on the SyncForce id in the custom Identifiers of the categories.
        /// </summary>
        /// <param name="arg">The arg.</param>
        /// <param name="context">The context.</param>
        /// <returns>The arg with an updated SellableItem property.</returns>
        public override async Task <SynchronizeProductArgument> Run(SynchronizeProductArgument arg, CommercePipelineExecutionContext context)
        {
            var syncForceClientPolicy = context.GetPolicy <SyncForceClientPolicy>();
            var catalog = await _findEntityPipeline.Run(new FindEntityArgument(typeof(Sitecore.Commerce.Plugin.Catalog.Catalog), arg.CatalogId.ToEntityId <Sitecore.Commerce.Plugin.Catalog.Catalog>()), context.CommerceContext.PipelineContextOptions) as Sitecore.Commerce.Plugin.Catalog.Catalog;

            if (catalog == null)
            {
                context.Logger.LogError($"{this.Name}: The Catalog with id {arg.CatalogId} could not be found.");
                return(arg);
            }

            //Get all categories.
            var allCategories = await _getCategoriesPipeline.Run(new GetCategoriesArgument(catalog.Name), context.CommerceContext.PipelineContextOptions);

            arg.Categories.AddRange(allCategories);

            //Get all SyncForce category id's to associate with.
            var categoryIds = arg.MasterProduct.ProductVariants.FirstOrDefault()?.ProductPropositionCategories.Select(c => c.Id);

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

            //For each SyncForce categoryId find the correct Sitecore Commerce category and associate the SellableItem with it.
            foreach (var categoryId in categoryIds)
            {
                var category = arg.Categories.FirstOrDefault(c => c.GetComponent <IdentifiersComponent>().CustomId.FirstOrDefault(i => i.Key.Equals(syncForceClientPolicy.CustomIdentifierKey))?.Value == categoryId.ToString());
                if (category != null && !string.IsNullOrEmpty(category.Id))
                {
                    await _associateSellableItemToParentPipeline.Run(
                        new CatalogReferenceArgument(arg.CatalogId, category.Id, arg.SellableItem.Id),
                        context.CommerceContext.PipelineContextOptions);

                    arg.SellableItem = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), arg.SellableItem.Id, shouldCreate : false), context.CommerceContext.PipelineContextOptions) as SellableItem ?? arg.SellableItem;
                }
            }

            return(arg);
        }
Exemple #10
0
        private async Task <ComposerTemplate> EnsureComposerTemplate(CommerceContext context, string name)
        {
            if (await _doesEntityExistPipeline.Run(new FindEntityArgument(typeof(ComposerTemplate), $"{CommerceEntity.IdPrefix<ComposerTemplate>()}{name}"), context.PipelineContextOptions))
            {
                return(await _findEntityPipeline.Run(new FindEntityArgument(typeof(ComposerTemplate), $"{CommerceEntity.IdPrefix<ComposerTemplate>()}{name}"), context.PipelineContextOptions) as ComposerTemplate);
            }

            return((await _createComposerTemplatePipeline.Run(new CreateComposerTemplateArgument(name)
            {
                Name = name, DisplayName = name
            },
                                                              context.PipelineContextOptions))?.ComposerTemplate);
        }
        public override async Task <ImportLocalizeContentArgument> Run(ImportLocalizeContentArgument arg, CommercePipelineExecutionContext context)
        {
            if (arg.CommerceEntity != null &&
                arg.HasLocalizationContent)
            {
                var localizationEntityId = LocalizationEntity.GetIdBasedOnEntityId(arg.CommerceEntity.Id);
                var localizationEntity   = await _findEntityPipeline.Run(new FindEntityArgument(typeof(LocalizationEntity), localizationEntityId, arg.CommerceEntity.EntityVersion), context).ConfigureAwait(false);

                arg.LocalizationEntity = localizationEntity as LocalizationEntity;
            }

            return(await Task.FromResult(arg));
        }
        public override async Task <List <BreadcrumbModel> > Run(string arg, CommercePipelineExecutionContext context)
        {
            var result = new List <BreadcrumbModel>();

            if (string.IsNullOrWhiteSpace(arg))
            {
                return(result);
            }

            var currentItem =
                await _findEntityPipeline.Run(new FindEntityArgument(typeof(CatalogItemBase), arg, false), context)
                .ConfigureAwait(false) as CatalogItemBase;

            if (currentItem == null)
            {
                return(result);
            }

            var children = await GetChildren(currentItem, context).ConfigureAwait(false);

            foreach (var itm in children)
            {
                var version          = 1;
                var commerceEntities =
                    await _findEntityVersionsPipeline.Run(new FindEntityArgument(itm.GetType(), itm.Id, false),
                                                          context);

                if (commerceEntities != null)
                {
                    var itemVersion = commerceEntities.LastOrDefault();
                    version = itemVersion?.Version ?? 1;
                }

                result.Add(itm.ToBreadcrumbModel(version));
            }

            return(result);
        }
Exemple #13
0
        public virtual async Task <Cart> Process(CommerceContext commerceContext, string wishlistId, CartLineComponent line)
        {
            AddWishListLineItemCommand addCartLineCommand = this;
            Cart result = null;

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

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

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


                        result = await _addWishListLineItemPipeline.Run(new CartLineArgument(cart, line), context);
                    }
                });
            }

            return(result);
        }
Exemple #14
0
        /// <summary>
        /// Process UpdateCartLineGiftBoxCommand commerce command.
        /// </summary>
        /// <param name="commerceContext">Commerce context.</param>
        /// <param name="cartId">Cart Id.</param>
        /// <param name="cartLineId">Cart line Id.</param>
        /// <param name="isGiftBox">Cart line gift box boolean attribute.</param>
        /// <returns></returns>
        public async Task <Cart> Process(CommerceContext commerceContext, string cartId, string cartLineId, bool isGiftBox)
        {
            try
            {
                Cart cartResult = null;

                using (CommandActivity.Start(commerceContext, this))
                {
                    // find Cart entity
                    var findCartArgument = new FindEntityArgument(typeof(Cart), cartId, false);
                    var pipelineContext  = new CommercePipelineExecutionContextOptions(commerceContext);
                    cartResult = await _findEntityPipeline.Run(findCartArgument, pipelineContext) as Cart;

                    var validationErrorCode = commerceContext.GetPolicy <KnownResultCodes>().ValidationError;

                    if (cartResult == null)
                    {
                        await pipelineContext.CommerceContext.AddMessage(validationErrorCode,
                                                                         "EntityNotFound",
                                                                         new object[] { cartId },
                                                                         $"Cart {cartId} was not found.");
                    }
                    else if (!cartResult.Lines.Any(l => l.Id == cartLineId))
                    {
                        await pipelineContext.CommerceContext.AddMessage(validationErrorCode,
                                                                         "CartLineNotFound",
                                                                         new object[] { cartLineId },
                                                                         $"Cart line {cartLineId} was not found.");
                    }
                    else
                    {
                        var arg = new CartLineGiftBoxArgument(cartResult, cartLineId, isGiftBox);
                        cartResult = await _updateCartLineGiftBoxPipeline.Run(arg, pipelineContext);
                    }

                    return(cartResult);
                }
            }
            catch (Exception ex)
            {
                return(await Task.FromException <Cart>(ex));
            }
        }
        private async Task <PriceBook> CreateOrGetPriceBook(CommercePipelineExecutionContext context, string priceBookName, string currencySetId)
        {
            var priceBook = await _findEntityPipeline.Run(new FindEntityArgument(typeof(PriceBook), $"{CommerceEntity.IdPrefix<PriceBook>()}{priceBookName}"),
                                                          context).ConfigureAwait(false) as PriceBook;

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

            var addedPriceBook = await _addPriceBookPipeline
                                 .Run(new AddPriceBookArgument(priceBookName) { Description = priceBookName, DisplayName = priceBookName, ParentBook = "", CurrencySetId = currencySetId }, context)
                                 .ConfigureAwait(false);

            if (addedPriceBook != null)
            {
                priceBook = addedPriceBook;
            }

            return(priceBook);
        }
Exemple #16
0
        public override async Task <ImportCsvProductsArgument> Run(ImportCsvProductsArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg, nameof(arg)).IsNotNull();
            Condition.Requires(arg.FileLines, nameof(arg.FileLines)).IsNotNull();

            var catalogList = GetDestinctCatalogData(arg);

            foreach (var(catalogName, fullCatalogName, catalogDisplayName) in catalogList)
            {
                var catalog = await _findEntityPipeline.Run(new FindEntityArgument(typeof(Catalog), fullCatalogName, 1), context);

                if (catalog != null)
                {
                    continue;
                }

                await _createCatalogPipeline.Run(new CreateCatalogArgument(catalogName, catalogDisplayName), context);
            }

            return(arg);
        }
Exemple #17
0
        public override async Task <WishList> Run(ResolveWishListArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull("The argument can not be null");
            Condition.Requires(arg.WishListId).IsNotNullOrEmpty("The wishList id can not be null or empty");

            var objects = context.CommerceContext.GetObjects <WishList>();

            if (objects.Any(p => p.Id == arg.WishListId))
            {
                context.Logger.LogWarning(string.Format("{0}.AlreadyLoaded: WishListId:{1}", Name, arg.WishListId), Array.Empty <object>());
            }
            var wishList = await _findEntityPipeline.Run(new FindEntityArgument(typeof(WishList), arg.WishListId, true), context) as WishList;

            if (wishList == null || wishList.IsPersisted)
            {
                return(wishList);
            }
            wishList.Id       = arg.WishListId;
            wishList.Name     = arg.WishListId;
            wishList.ShopName = arg.ShopName;

            return(wishList);
        }
Exemple #18
0
        public override async Task <RelationshipArgument> Run(
            RelationshipArgument arg,
            CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The argument can not be null");
            Condition.Requires(arg.TargetName).IsNotNullOrEmpty(Name + ": The target name can not be null or empty");
            Condition.Requires(arg.SourceName).IsNotNullOrEmpty(Name + ": The source name can not be null or empty");
            Condition.Requires(arg.RelationshipType).IsNotNullOrEmpty(Name + ": The relationship type can not be null or empty");

            if (!((IEnumerable <string>) new string[4]
            {
                CatalogToCategory,
                CatalogToSellableItem,
                CategoryToCategory,
                CategoryToSellableItem
            })
                .Contains(arg.RelationshipType, StringComparer.OrdinalIgnoreCase))
            {
                return(arg);
            }

            CatalogItemBase source = await _findEntityPipeline.Run(new FindEntityArgument(typeof(CatalogItemBase), arg.SourceName, false), context) as CatalogItemBase;

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

            if (arg.TargetName.Contains("|"))
            {
                string[] strArray = arg.TargetName.Split('|');
                stringList.AddRange(strArray);
            }
            else
            {
                stringList.Add(arg.TargetName);
            }

            ValueWrapper <bool> sourceChanged = new ValueWrapper <bool>(false);

            if (!source.HasComponent <ExtendedCatalogItemComponent>())
            {
                source.SetComponent(new ExtendedCatalogItemComponent());
            }

            var sourceComponent = source.GetComponent <ExtendedCatalogItemComponent>();

            foreach (string entityId in stringList)
            {
                CatalogItemBase catalogItemBase = await _findEntityPipeline.Run(new FindEntityArgument(typeof(CatalogItemBase), entityId, false), context) as CatalogItemBase;

                if (source != null && catalogItemBase != null)
                {
                    if (!catalogItemBase.HasComponent <ExtendedCatalogItemComponent>())
                    {
                        catalogItemBase.SetComponent(new ExtendedCatalogItemComponent());
                    }

                    var catalogItemBaseComponent = catalogItemBase.GetComponent <ExtendedCatalogItemComponent>();
                    ValueWrapper <bool> changed  = new ValueWrapper <bool>(false);

                    if (arg.RelationshipType.Equals(CatalogToCategory, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceComponent.ChildrenCategoryEntitiesList       = UpdateHierarchy(arg, catalogItemBase.Id, sourceComponent.ChildrenCategoryEntitiesList, sourceChanged);
                        catalogItemBaseComponent.ParentCatalogEntitiesList = UpdateHierarchy(arg, source.Id, catalogItemBaseComponent.ParentCatalogEntitiesList, changed);
                    }
                    else if (arg.RelationshipType.Equals(CategoryToCategory, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceComponent.ChildrenCategoryEntitiesList        = UpdateHierarchy(arg, catalogItemBase.Id, sourceComponent.ChildrenCategoryEntitiesList, sourceChanged);
                        catalogItemBaseComponent.ParentCategoryEntitiesList = UpdateHierarchy(arg, source.Id, catalogItemBaseComponent.ParentCategoryEntitiesList, changed);
                        catalogItemBaseComponent.ParentCatalogEntitiesList  = UpdateHierarchy(arg, ExtractCatalogId(source.Id), catalogItemBaseComponent.ParentCatalogEntitiesList, changed);
                    }
                    else if (arg.RelationshipType.Equals(CatalogToSellableItem, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceComponent.ChildrenSellableItemEntitiesList   = UpdateHierarchy(arg, catalogItemBase.Id, sourceComponent.ChildrenSellableItemEntitiesList, sourceChanged);
                        catalogItemBaseComponent.ParentCatalogEntitiesList = UpdateHierarchy(arg, source.Id, catalogItemBaseComponent.ParentCatalogEntitiesList, changed);
                    }
                    else if (arg.RelationshipType.Equals(CategoryToSellableItem, StringComparison.OrdinalIgnoreCase))
                    {
                        sourceComponent.ChildrenSellableItemEntitiesList    = UpdateHierarchy(arg, catalogItemBase.Id, sourceComponent.ChildrenSellableItemEntitiesList, sourceChanged);
                        catalogItemBaseComponent.ParentCategoryEntitiesList = UpdateHierarchy(arg, source.Id, catalogItemBaseComponent.ParentCategoryEntitiesList, changed);
                        catalogItemBaseComponent.ParentCatalogEntitiesList  = UpdateHierarchy(arg, ExtractCatalogId(source.Id), catalogItemBaseComponent.ParentCatalogEntitiesList, changed);
                    }
                    if (changed.Value)
                    {
                        PersistEntityArgument persistEntityArgument = await _persistEntityPipeline.Run(new PersistEntityArgument(catalogItemBase), context);
                    }
                }
            }
            if (sourceChanged.Value)
            {
                await _persistEntityPipeline.Run(new PersistEntityArgument(source), context);
            }
            return(arg);
        }
        private async Task UpsertSellableItem(SellableItem item, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(item.ProductId))
            {
                item.ProductId = item.Id.SimplifyEntityName().ProposeValidId();
            }

            if (string.IsNullOrEmpty(item.FriendlyId))
            {
                item.FriendlyId = item.Id.SimplifyEntityName();
            }

            if (string.IsNullOrEmpty(item.SitecoreId))
            {
                item.SitecoreId = GuidUtility.GetDeterministicGuidString(item.Id);
            }

            CommerceEntity entity = await _findEntityPipeline
                                    .Run(new FindEntityArgument(typeof(SellableItem), item.Id), context)
                                    .ConfigureAwait(false);

            if (entity == null)
            {
                await _persistEntityPipeline.Run(new PersistEntityArgument(item), context).ConfigureAwait(false);

                return;
            }

            if (!(entity is SellableItem))
            {
                return;
            }

            var existingSellableItem = entity as SellableItem;

            // Try to merge the items.
            existingSellableItem.Name = item.Name;

            foreach (Policy policy in item.EntityPolicies)
            {
                if (existingSellableItem.HasPolicy(policy.GetType()))
                {
                    existingSellableItem.RemovePolicy(policy.GetType());
                }

                existingSellableItem.SetPolicy(policy);
            }

            if (item.HasComponent <ItemVariationsComponent>())
            {
                var variations = existingSellableItem.GetComponent <ItemVariationsComponent>();

                foreach (ItemVariationComponent variation in item
                         .GetComponent <ItemVariationsComponent>().ChildComponents
                         .OfType <ItemVariationComponent>())
                {
                    ItemVariationComponent existingVariation = existingSellableItem.GetVariation(variation.Id);
                    if (existingVariation != null)
                    {
                        existingVariation.Name = variation.Name;

                        foreach (Policy policy in variation.Policies)
                        {
                            if (existingVariation.Policies.Any(x => x.GetType() == policy.GetType()))
                            {
                                existingVariation.RemovePolicy(policy.GetType());
                            }

                            existingVariation.SetPolicy(policy);
                        }
                    }
                    else
                    {
                        variations.ChildComponents.Add(variation);
                    }
                }
            }

            await _persistEntityPipeline.Run(new PersistEntityArgument(existingSellableItem), context).ConfigureAwait(false);
        }
Exemple #20
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            int    limitValue   = -999;
            string strCode      = string.Empty;
            string regClassCode = string.Empty;

            EntityView entityView1 = entityView;

            if (string.IsNullOrEmpty(entityView1 != null ? entityView1.Action : null) || !entityView.Action.Equals(context.GetPolicy <KnownCouponActionsPolicy>().AddPublicCoupon, StringComparison.OrdinalIgnoreCase) || (!entityView.Name.Equals(context.GetPolicy <KnownCouponViewsPolicy>().PublicCoupons, StringComparison.OrdinalIgnoreCase) || string.IsNullOrEmpty(entityView.EntityId)))
            {
                return(entityView);
            }

            Promotion promotion = context.CommerceContext.GetObject <Promotion>(p => p.Id.Equals(entityView.EntityId, StringComparison.OrdinalIgnoreCase));

            if (promotion == null)
            {
                return(entityView);
            }

            ViewProperty code = entityView.Properties.FirstOrDefault(p => p.Name.Equals("Code", StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrEmpty(code != null ? code.Value : null))
            {
                strCode = code == null ? "Code" : code.DisplayName;
                string result = await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[1]
                {
                    strCode
                }, "Invalid or missing value for property 'Code'.");

                return(entityView);
            }

            ViewProperty limitViewProperty = entityView.Properties.FirstOrDefault(p => p.Name.Equals("Coupon Usage Limit", StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrEmpty(limitViewProperty != null ? limitViewProperty.Value : null))
            {
                string errorCode = limitViewProperty == null ? "Coupon Usage Limit" : limitViewProperty.DisplayName;
                string result    = await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[1]
                {
                    errorCode
                }, "Invalid or missing value for property 'Code'.");

                return(entityView);
            }

            if (limitViewProperty.Value != null)
            {
                bool isSuccess = int.TryParse(limitViewProperty.Value, out limitValue);
                if (!isSuccess)
                {
                    string errorCode = code == null ? "Coupon Usage Limit" : limitViewProperty.DisplayName;
                    string result    = await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[1]
                    {
                        errorCode
                    }, "Invalid or missing value for property 'Coupon Usage Limit'.");

                    return(entityView);
                }
            }

            CommerceContext commerceContext = context.CommerceContext;


            string couponCode = code != null ? code.Value : null;

            Promotion promotion2 = await _addPublicCouponCommand.Process(commerceContext, promotion, couponCode);

            string couponId = $"{CommerceEntity.IdPrefix<Coupon>()}{couponCode}";

            var couponData = await _findEntityPipeline.Run(new FindEntityArgument(typeof(Coupon), couponId, false), context);

            if (couponData != null && couponData is Coupon)
            {
                var coupon = couponData as Coupon;
                if (coupon != null)
                {
                    coupon.Policies = new List <Policy>()
                    {
                        new LimitUsagesPolicy()
                        {
                            LimitCount = limitValue
                        }
                    };

                    PersistEntityArgument persistEntityArgument = await _persistEntityPipeline.Run(new PersistEntityArgument((CommerceEntity)coupon), context);
                }
            }

            return(entityView);
        }
        private async Task CreateExampleBundles(CommercePipelineExecutionContext context)
        {
            var bundle1 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001001"), context).ConfigureAwait(false);

            if (bundle1 == null)
            {
                // First bundle
                bundle1 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001001",
                        "SmartWiFiBundle",
                        "Smart WiFi Bundle",
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        new[] { "smart", "wifi", "bundle" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042964|56042964",
                        Quantity       = 1
                    },
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042971|56042971",
                        Quantity       = 1
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle1.GetComponent <ImagesComponent>().Images.Add("65703328-1456-48da-a693-bad910d7d1fe");

                bundle1.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 200.00M),
                    new Money("CAD", 250.00M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle1), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-Connected home",
                    bundle1.Id).ConfigureAwait(false);
            }

            var bundle2 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001002"), context).ConfigureAwait(false);

            if (bundle2 == null)
            {
                // Second bundle
                bundle2 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001002",
                        "ActivityTrackerCameraBundle",
                        "Activity Tracker & Camera Bundle",
                        "Sample bundle containting two activity trackers and two cameras.",
                        "Striva Wearables",
                        string.Empty,
                        string.Empty,
                        new[] { "activitytracker", "camera", "bundle" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042896|56042896",
                        Quantity       = 2
                    },
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-7042066|57042066",
                        Quantity       = 2
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle2.GetComponent <ImagesComponent>().Images.Add("003c9ee5-2d97-4a6c-bb9e-24e110cd7645");

                bundle2.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 220.00M),
                    new Money("CAD", 280.00M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle2), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-Fitness Activity Trackers",
                    bundle2.Id).ConfigureAwait(false);
            }

            var bundle3 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001003"), context).ConfigureAwait(false);

            if (bundle3 == null)
            {
                // Third bundle
                bundle3 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001003",
                        "RefrigeratorFlipPhoneBundle",
                        "Refrigerator & Flip Phone Bundle",
                        "Sample bundle containting a refrigerator and two flip phones.",
                        "Viva Refrigerators",
                        string.Empty,
                        string.Empty,
                        new[] { "refrigerator", "flipphone", "bundle" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042567|56042568",
                        Quantity       = 1
                    },
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042331|56042331",
                        Quantity       = 2
                    },
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042896|56042896",
                        Quantity       = 3
                    },
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-7042066|57042066",
                        Quantity       = 4
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle3.GetComponent <ImagesComponent>().Images.Add("372d8bc6-6888-4375-91c1-f3bee2d31558");

                bundle3.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 10.00M),
                    new Money("CAD", 20.00M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle3), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-Appliances",
                    bundle3.Id).ConfigureAwait(false);
            }

            var bundle4 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001004"), context).ConfigureAwait(false);

            if (bundle4 == null)
            {
                // Fourth bundle with digital items
                bundle4 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001004",
                        "GiftCardAndSubscriptionBundle",
                        "Gift Card & Subscription Bundle",
                        "Sample bundle containting a gift card and two subscriptions.",
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        new[] { "bundle", "giftcard", "entitlement" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042986|56042987",
                        Quantity       = 1
                    },
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042453|56042453",
                        Quantity       = 2
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle4.GetComponent <ImagesComponent>().Images.Add("7b57e6e0-a4ef-417e-809c-572f2e30aef7");

                bundle4.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 10.00M),
                    new Money("CAD", 20.00M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle4), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                    bundle4.Id).ConfigureAwait(false);
            }

            var bundle5 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001005"), context).ConfigureAwait(false);

            if (bundle5 == null)
            {
                // Preorderable bundle
                bundle5 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001005",
                        "PreorderableBundle",
                        "Preorderable Bundle",
                        "Sample bundle containting a phone and headphones.",
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        new[] { "bundle" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042305|56042305",
                        Quantity       = 1
                    },
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042059|56042059",
                        Quantity       = 1
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle5.GetComponent <ImagesComponent>().Images.Add("b0b07d7b-ddaf-4798-8eb9-af7f570af3fe");

                bundle5.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 44.99M),
                    new Money("CAD", 59.99M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle5), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-Phones",
                    bundle5.Id).ConfigureAwait(false);
            }

            var bundle6 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001006"), context).ConfigureAwait(false);

            if (bundle6 == null)
            {
                // Backorderable bundle
                bundle6 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001006",
                        "BackorderableBundle",
                        "Backorderable Bundle",
                        "Sample bundle containting a phone and headphones.",
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        new[] { "bundle" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042305|56042305",
                        Quantity       = 1
                    },
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042058|56042058",
                        Quantity       = 1
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle6.GetComponent <ImagesComponent>().Images.Add("b0b07d7b-ddaf-4798-8eb9-af7f570af3fe");

                bundle6.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 44.99M),
                    new Money("CAD", 59.99M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle6), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-Phones",
                    bundle6.Id).ConfigureAwait(false);
            }

            var bundle7 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001007"), context).ConfigureAwait(false);

            if (bundle7 == null)
            {
                // Backorderable bundle
                bundle7 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001007",
                        "PreorderableBackorderableBundle",
                        "Preorderable / Backorderable Bundle",
                        "Sample bundle containting headphones.",
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        new[] { "bundle" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042058|56042058",
                        Quantity       = 1
                    },
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042059|56042059",
                        Quantity       = 1
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle7.GetComponent <ImagesComponent>().Images.Add("b0b07d7b-ddaf-4798-8eb9-af7f570af3fe");

                bundle7.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 44.99M),
                    new Money("CAD", 59.99M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle7), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-Audio",
                    bundle7.Id).ConfigureAwait(false);
            }

            var bundle8 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001008"), context).ConfigureAwait(false);

            if (bundle8 == null)
            {
                // Eigth bundle with a gift card only
                bundle8 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001008",
                        "GiftCardBundle",
                        "Gift Card Bundle",
                        "Sample bundle containting a gift card.",
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        new[] { "bundle", "entitlement", "giftcard" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042986|56042987",
                        Quantity       = 1
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle8.GetComponent <ImagesComponent>().Images.Add("7b57e6e0-a4ef-417e-809c-572f2e30aef7");

                bundle8.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 40.00M),
                    new Money("CAD", 50.00M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle8), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                    bundle8.Id).ConfigureAwait(false);
            }

            var bundle9 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001009"), context).ConfigureAwait(false);

            if (bundle9 == null)
            {
                // Warranty bundle
                bundle9 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001009",
                        "WarrantyBundle",
                        "Warranty Bundle",
                        "Sample bundle containting a warranty.",
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        new[] { "bundle", "warranty" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-7042259|57042259",
                        Quantity       = 1
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle9.GetComponent <ImagesComponent>().Images.Add("eebf49f2-74df-4fe6-b77f-f2d1d447827c");

                bundle9.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 150.00M),
                    new Money("CAD", 200.00M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle9), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                    bundle9.Id).ConfigureAwait(false);
            }

            var bundle10 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001010"), context).ConfigureAwait(false);

            if (bundle10 == null)
            {
                // Service bundle
                bundle10 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001010",
                        "ServiceBundle",
                        "Service Bundle",
                        "Sample bundle containting a service.",
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        new[] { "bundle", "service" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042418|56042418",
                        Quantity       = 1
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle10.GetComponent <ImagesComponent>().Images.Add("8b59fe2a-c234-4f92-b84b-7515411bf46e");

                bundle10.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 150.00M),
                    new Money("CAD", 200.00M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle10), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                    bundle10.Id).ConfigureAwait(false);
            }

            var bundle11 = await _findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-6001011"), context).ConfigureAwait(false);

            if (bundle11 == null)
            {
                // Subscription bundle
                bundle11 =
                    await this._commerceCommander.Command <CreateBundleCommand>().Process(
                        context.CommerceContext,
                        "Static",
                        "6001011",
                        "SubscriptionBundle",
                        "Subscription Bundle",
                        "Sample bundle containting a subscription.",
                        string.Empty,
                        string.Empty,
                        string.Empty,
                        new[] { "bundle", "subscription" },
                        new List <BundleItem>
                {
                    new BundleItem
                    {
                        SellableItemId = "Entity-SellableItem-6042453|56042453",
                        Quantity       = 1
                    }
                }).ConfigureAwait(false);

                // Set image and list price for bundle
                bundle11.GetComponent <ImagesComponent>().Images.Add("22d74215-8e5f-4de3-a9d6-ece3042bd64c");

                bundle11.SetPolicy(
                    new ListPricingPolicy(
                        new List <Money>
                {
                    new Money("USD", 10.00M),
                    new Money("CAD", 15.00M)
                }));

                await this._commerceCommander.Pipeline <IPersistEntityPipeline>()
                .Run(new PersistEntityArgument(bundle11), context).ConfigureAwait(false);

                // Associate bundle to parent category
                await this._commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(
                    context.CommerceContext,
                    "Entity-Catalog-Habitat_Master",
                    "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                    bundle11.Id).ConfigureAwait(false);
            }
        }
Exemple #22
0
        public override async Task <SellableItem> Run(
            SellableItem arg,
            CommercePipelineExecutionContext context)
        {
            if (arg == null)
            {
                return(null);
            }

            if (arg.HasPolicy <PurchaseOptionMoneyPolicy>() && arg.GetPolicy <PurchaseOptionMoneyPolicy>().Expires > DateTimeOffset.UtcNow && arg.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice.CurrencyCode.Equals(context.CommerceContext.CurrentCurrency(), StringComparison.OrdinalIgnoreCase))
            {
                return(arg);
            }

            if (arg.HasComponent <PriceSnapshotComponent>())
            {
                arg.Components.Remove(arg.GetComponent <PriceSnapshotComponent>());
            }

            string                 currentCurrency   = context.CommerceContext.CurrentCurrency();
            MessagesComponent      messagesComponent = arg.GetComponent <MessagesComponent>();
            Money                  sellPrice         = null;
            PriceCardPolicy        priceCardPolicy   = arg.Policies.OfType <PriceCardPolicy>().FirstOrDefault();
            PriceSnapshotComponent snapshotComponent = null;
            bool pricingByTags = false;

            if (!string.IsNullOrEmpty(priceCardPolicy?.PriceCardName))
            {
                snapshotComponent = await _resolveSnapshotByCardPipeline.Run(priceCardPolicy.PriceCardName, context);
            }
            else if (arg.Tags.Any())
            {
                snapshotComponent = await _resolveSnapshotByTagsPipeline.Run(arg.Tags, context);

                pricingByTags = true;
            }

            PriceTier priceTier = snapshotComponent?.Tiers.FirstOrDefault(t =>
            {
                return(t.Currency.Equals(currentCurrency, StringComparison.OrdinalIgnoreCase) ? t.Quantity == decimal.One : false);
            });

            Customer customer = await _findEntityPipeline.Run(new FindEntityArgument(typeof(Customer), context.CommerceContext.CurrentCustomerId(), false), context) as Customer;

            bool isMembershipLevelPrice = false;

            if (customer != null && customer.HasComponent <MembershipSubscriptionComponent>())
            {
                var membershipSubscriptionComponent = customer.GetComponent <MembershipSubscriptionComponent>();
                var customerMemerbshipLevelName     = membershipSubscriptionComponent.MemerbshipLevelName;
                var memerbshipLevelName             = membershipSubscriptionComponent.MemerbshipLevelName;

                if (snapshotComponent != null && snapshotComponent.HasComponent <MembershipTiersComponent>())
                {
                    var membershipTiersComponent = snapshotComponent.GetComponent <MembershipTiersComponent>();
                    var membershipPriceTier      = membershipTiersComponent.Tiers.FirstOrDefault(x => x.MembershipLevel == memerbshipLevelName);

                    if (membershipPriceTier != null)
                    {
                        sellPrice = new Money(membershipPriceTier.Currency, membershipPriceTier.Price);
                        isMembershipLevelPrice = true;
                        messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, pricingByTags
                            ? string.Format("SellPrice<=Tags.Snapshot: MembershipLevel={0}|Price={1}|Qty={2}|Tags='{3}'", customerMemerbshipLevelName, sellPrice.AsCurrency(false, null), membershipPriceTier.Quantity, string.Join(", ", snapshotComponent.Tags.Select(c => c.Name)))
                            : string.Format("SellPrice<=PriceCard.Snapshot: MembershipLevel={0}|Price={1}|Qty={2}|PriceCard={3}", customerMemerbshipLevelName, sellPrice.AsCurrency(false, null), membershipPriceTier.Quantity, priceCardPolicy.PriceCardName));
                    }
                }
            }

            if (!isMembershipLevelPrice && priceTier != null)
            {
                sellPrice = new Money(priceTier.Currency, priceTier.Price);
                messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, pricingByTags ? string.Format("SellPrice<=Tags.Snapshot: Price={0}|Qty={1}|Tags='{2}'", sellPrice.AsCurrency(false, null), priceTier.Quantity, string.Join(", ", snapshotComponent.Tags.Select(c => c.Name))) : string.Format("SellPrice<=PriceCard.Snapshot: Price={0}|Qty={1}|PriceCard={2}", sellPrice.AsCurrency(false, null), priceTier.Quantity, priceCardPolicy.PriceCardName));
            }

            if (snapshotComponent != null)
            {
                arg.SetComponent(snapshotComponent);
            }

            if (sellPrice != null)
            {
                arg.SetPolicy(new PurchaseOptionMoneyPolicy()
                {
                    SellPrice = sellPrice
                });
            }

            return(arg);
        }
Exemple #23
0
        public override async Task <PriceCard> Run(PriceCard arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The price card can not be null");
            PriceCard card = arg;
            PriceCardSnapshotCustomTierArgument argument = context.CommerceContext.GetObjects <PriceCardSnapshotCustomTierArgument>().FirstOrDefault();
            CommercePipelineExecutionContext    executionContext;

            if (argument == null)
            {
                executionContext = context;
                var    commerceContext = context.CommerceContext;
                string error           = context.GetPolicy <KnownResultCodes>().Error;
                string defaultMessage  = "Argument of type " + typeof(PriceCardSnapshotCustomTierArgument).Name + " was not found in context.";
                executionContext.Abort(await commerceContext.AddMessage(error, "ArgumentNotFound", new object[] { typeof(PriceCardSnapshotCustomTierArgument).Name }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            Condition.Requires(argument.PriceSnapshot).IsNotNull(Name + ": The price snapshot cannot be null.");
            Condition.Requires(argument.PriceSnapshot.Id).IsNotNullOrEmpty(Name + ": The price snapshot id cannot be null or empty.");
            Condition.Requires(argument.PriceTier).IsNotNull(Name + ": The price tier cannot be null.");
            Condition.Requires(argument.PriceTier.Currency).IsNotNullOrEmpty(Name + ": The price tier currency cannot be null or empty.");
            Condition.Requires(argument.PriceTier.Quantity).IsNotNull(Name + ": The price tier quantity cannot be null.");
            Condition.Requires(argument.PriceTier.Price).IsNotNull(Name + ": The price tier price cannot be null.");

            var snapshot = argument.PriceSnapshot;
            var tier     = argument.PriceTier;
            var membershipTiersComponent = snapshot.GetComponent <MembershipTiersComponent>();

            if (membershipTiersComponent.Tiers.Any(x => x.Currency == tier.Currency && x.MembershipLevel == tier.MembershipLevel && x.Quantity == tier.Quantity))
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          defaultMessage  = "A tier for specified Currency, Membership Level and Quantity already exists for price snapshot '" + snapshot.Id + "' in price card '" + card.FriendlyId + "'.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, "PriceTierAlreadyExists", new object[] { snapshot.Id, card.FriendlyId }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            GlobalPricingPolicy policy = context.GetPolicy <GlobalPricingPolicy>();

            if (argument.PriceTier.Quantity <= policy.MinimumPricingQuantity)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          defaultMessage  = string.Format("Invalid quantity. Quantity must be greater than '{0}'.", policy.MinimumPricingQuantity);
                executionContext.Abort(await commerceContext.AddMessage(error, "InvalidQuantity", new object[] { policy.MinimumPricingQuantity }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            if (argument.PriceTier.Price < policy.MinimumPrice)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          defaultMessage  = string.Format("Invalid price. Minimum price allowed is '{0}'.", policy.MinimumPrice);
                executionContext.Abort(await commerceContext.AddMessage(error, "InvalidPrice", new object[] { policy.MinimumPrice }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            PriceBook priceBook = await _findEntityPipeline.Run(new FindEntityArgument(typeof(PriceBook), card.Book.EntityTarget, false), context)
                                  .ConfigureAwait(false) as PriceBook;

            CurrencySet currencySet = await _getCurrencySetPipeline.Run(priceBook?.CurrencySet?.EntityTarget, context)
                                      .ConfigureAwait(false);

            bool   flag = false;
            string str  = string.Empty;

            if (currencySet != null && currencySet.HasComponent <CurrenciesComponent>())
            {
                CurrenciesComponent component = currencySet.GetComponent <CurrenciesComponent>();
                str = string.Join(", ", component.Currencies.Select(c => c.Code));
                if (component.Currencies.Any(c => c.Code.Equals(argument.PriceTier.Currency, StringComparison.OrdinalIgnoreCase)))
                {
                    flag = true;
                }
            }

            if (!flag)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          defaultMessage  = "Invalid currency '" + argument.PriceTier.Currency + "'. Valid currencies are '" + str + "'.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, "InvalidCurrency", new object[] { argument.PriceTier.Currency, str }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            tier.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
            PriceSnapshotComponent snapshotComponent = card.Snapshots.FirstOrDefault(n => n.Id.Equals(snapshot.Id, StringComparison.OrdinalIgnoreCase));

            if (snapshotComponent != null)
            {
                var component = snapshotComponent.GetComponent <MembershipTiersComponent>();
                if (component != null)
                {
                    component.Tiers.Add(tier);
                }
            }

            PriceTierAdded priceTierAdded = new PriceTierAdded(tier.Id)
            {
                Name = tier.Name
            };

            context.CommerceContext.AddModel(priceTierAdded);

            return(card);
        }
Exemple #24
0
        /// <summary>
        /// Ensures the existence of the Category.
        /// If it doesn't exist it creates the Category, adds DisplayNames, adds identifiers and associates the Category with the parent Category.
        /// </summary>
        /// <param name="propositionCategory"></param>
        /// <param name="catalogId"></param>
        /// <param name="catalogName"></param>
        /// <param name="policy"></param>
        /// <param name="context"></param>
        /// <param name="associateWithCatalog"></param>
        /// <returns></returns>
        private async Task <List <Category> > EnsureCategory(CollectionFolder propositionCategory, string catalogId,
                                                             string catalogName, SyncForceClientPolicy policy, CommerceContext context,
                                                             bool associateWithCatalog = false)
        {
            var result = new List <Category>();

            var categoryName = propositionCategory.Values.FirstOrDefault(l => l.Language == policy.DefaultLanguage)
                               ?.Name;
            //Added sort index to category name to make sure sorting is done right, instead of done on alphabetical order.
            var categoryId =
                $"{CommerceEntity.IdPrefix<Category>()}{catalogName}-{propositionCategory.SortIndex.ToString().PadLeft(3, '0') + propositionCategory.Id + categoryName.ProposeValidId()}";
            Category category = null;

            //Get or create category
            if (await _doesEntityExistPipeline.Run(new FindEntityArgument(typeof(Category), categoryId),
                                                   context.PipelineContextOptions))
            {
                category = await _getCategoryPipeline.Run(new GetCategoryArgument(categoryId),
                                                          context.PipelineContextOptions);
            }
            else
            {
                var createResult = await _createCategoryPipeline.Run(
                    new CreateCategoryArgument(catalogId,
                                               propositionCategory.SortIndex.ToString().PadLeft(3, '0') + propositionCategory.Id +
                                               categoryName.ProposeValidId(), categoryName, ""), context.PipelineContextOptions);

                category = createResult?.Categories?.FirstOrDefault(c => c.Id == categoryId);
            }

            if (category != null)
            {
                //Localize properties
                var localizationEntityId = LocalizationEntity.GetIdBasedOnEntityId(category.Id);
                var localizationEntity   = await _findEntityPipeline.Run(new FindEntityArgument(typeof(LocalizationEntity), localizationEntityId),
                                                                         context.PipelineContextOptions) as LocalizationEntity;

                if (localizationEntity != null)
                {
                    var displayNames = propositionCategory.Values.Select(p => new Parameter(p.Language, p.Name)).ToList();
                    localizationEntity.AddOrUpdatePropertyValue("DisplayName", displayNames);

                    var descriptions = propositionCategory.CategoryContent.Values.Select(p => new Parameter(p.Language, p.Name)).ToList();
                    localizationEntity.AddOrUpdatePropertyValue("Description", descriptions);

                    await _persistEntityPipeline.Run(new PersistEntityArgument(localizationEntity),
                                                     context.PipelineContextOptions);
                }

                //Add identifiers
                var identifiersComponent = category.GetComponent <IdentifiersComponent>();
                if (!identifiersComponent.CustomId.Any(i => i.Key.Equals(policy.CustomIdentifierKey)))
                {
                    identifiersComponent.CustomId.Add(
                        new Sitecore.Commerce.Plugin.Catalogs.SyncForce.Models.CustomIdentifier(
                            policy.CustomIdentifierKey, propositionCategory.Id.ToString()));
                }
                category.SetComponent(identifiersComponent);
                category = (await _persistEntityPipeline.Run(new PersistEntityArgument(category),
                                                             context.PipelineContextOptions))?.Entity as Category ?? category;

                //Add custom properties
                var categoryComponent = category.GetComponent <SyncForceCategoryComponent>();
                categoryComponent.Sortorder = propositionCategory.SortIndex;
                category.SetComponent(categoryComponent);
                category = (await _persistEntityPipeline.Run(new PersistEntityArgument(category), context.PipelineContextOptions))?.Entity as Category ?? category;

                //Create sub-categories
                if (propositionCategory?.ProductPropositionCategories?.Any() ?? false)
                {
                    foreach (var subCategory in propositionCategory.ProductPropositionCategories)
                    {
                        var s = await EnsureCategory(subCategory, catalogId, catalogName, policy, context);

                        result.AddRange(s);

                        foreach (var createdSubCategory in s)
                        {
                            var persistedSubCategory =
                                (await _persistEntityPipeline.Run(new PersistEntityArgument(createdSubCategory),
                                                                  context.PipelineContextOptions))?.Entity;
                            var associateResult = await _associateCategoryToParentPipeline.Run(
                                new CatalogReferenceArgument(catalogId, category.Id,
                                                             persistedSubCategory?.Id ?? createdSubCategory.Id),
                                context.PipelineContextOptions);

                            category = associateResult?.Categories?.FirstOrDefault(c => c.Id == category.Id) ??
                                       category;
                        }
                    }
                }

                //Associate with catalog if top level category
                if (associateWithCatalog)
                {
                    var associateResult = await _associateCategoryToParentPipeline.Run(
                        new CatalogReferenceArgument(catalogId, catalogId, category.Id),
                        context.PipelineContextOptions);

                    category = associateResult?.Categories
                               ?.FirstOrDefault(c => c.Id == category.Id) ?? category;
                }

                result.Add(category);
            }

            return(result);
        }
Exemple #25
0
        public override async Task <List <BreadcrumbModel> > Run(string arg, CommercePipelineExecutionContext context)
        {
            var result    = new List <BreadcrumbModel>();
            var childList = new List <CatalogItemBase>();


            if (arg.StartsWith("Entity-"))
            {
                var currentItem =
                    await _findEntityPipeline.Run(new FindEntityArgument(typeof(CatalogItemBase), arg, false), context)
                    .ConfigureAwait(false) as CatalogItemBase;

                if (currentItem == null)
                {
                    result.Add(new BreadcrumbModel()
                    {
                        Href = "/", Icon = "si si-temple", IsActive = false, Name = "COMMERCE", EntityId = "root"
                    });
                    return(result);
                }

                var model = new List <CatalogItemBase>();

                childList.Add(currentItem);
                await GetParents(currentItem, model, context).ConfigureAwait(false);

                childList.AddRange(model);

                if (currentItem != null && currentItem.HasComponent <ExtendedCatalogItemComponent>())
                {
                    var component = currentItem.GetComponent <ExtendedCatalogItemComponent>();
                    var catalog   = await _findEntityPipeline.Run(new FindEntityArgument(typeof(CatalogItemBase), component.ParentCatalogEntitiesList, false), context) as CatalogItemBase;

                    childList.Add(catalog);
                }
            }

            result.Add(new BreadcrumbModel()
            {
                Href = "/", Icon = "si si-temple", IsActive = false, Name = "COMMERCE", EntityId = "root"
            });
            childList.Reverse();

            foreach (var itm in childList)
            {
                var version          = 1;
                var commerceEntities =
                    await _findEntityVersionsPipeline.Run(new FindEntityArgument(itm.GetType(), itm.Id, false),
                                                          context);

                if (commerceEntities != null)
                {
                    var itemVersion = commerceEntities.LastOrDefault();
                    version = itemVersion?.Version ?? 1;
                }

                result.Add(itm.ToBreadcrumbModel(version));
            }

            return(result);
        }
Exemple #26
0
        public override async Task <PriceCard> Run(PriceCard arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The price card can not be null");
            PriceCard card     = arg;
            var       argument = context.CommerceContext.GetObjects <PriceCardSnapshotCustomTierArgument>().FirstOrDefault();
            CommercePipelineExecutionContext executionContext;

            if (argument == null)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          defaultMessage  = "Argument of type " + typeof(PriceCardSnapshotCustomTierArgument).Name + " was not found in context.";
                executionContext.Abort(await commerceContext.AddMessage(error, "ArgumentNotFound", new object[] { typeof(PriceCardSnapshotCustomTierArgument).Name }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            Condition.Requires(argument.PriceSnapshot).IsNotNull(Name + ": The price snapshot can not be null");
            Condition.Requires(argument.PriceSnapshot.Id).IsNotNullOrEmpty(Name + ": The price snapshot id can not be null or empty");
            Condition.Requires(argument.PriceTier).IsNotNull(Name + ": The price tier can not be null");
            Condition.Requires(argument.PriceTier.Currency).IsNotNullOrEmpty(Name + ": The price tier currency can not be null or empty");

            PriceBook book = await _findEntityPipeline.Run(new FindEntityArgument(typeof(PriceBook), card.Book.EntityTarget, false), context)
                             .ConfigureAwait(false) as PriceBook;

            CurrencySet currencySet = await _getCurrencySetPipeline.Run(book?.CurrencySet?.EntityTarget, context)
                                      .ConfigureAwait(false);

            if (!(currencySet != null &&
                  currencySet.HasComponent <CurrenciesComponent>() &&
                  currencySet.GetComponent <CurrenciesComponent>().Currencies.Any(c => c.Code.Equals(argument.PriceTier.Currency, StringComparison.OrdinalIgnoreCase))))
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          defaultMessage  = "Currency '" + argument.PriceTier.Currency + "' is no longer valid for book '" + book?.FriendlyId + "'. Either remove the tier or modify the book to include the currency.";
                executionContext.Abort(await commerceContext.AddMessage(error, "CurrencyNotLongerValid", new object[] { argument.PriceTier.Currency, book?.FriendlyId }, defaultMessage).ConfigureAwait(false), (object)context);
                executionContext = null;

                return(card);
            }

            GlobalPricingPolicy policy = context.GetPolicy <GlobalPricingPolicy>();

            if (argument.PriceTier.Price < policy.MinimumPrice)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          defaultMessage  = string.Format("Invalid price. Minimum price allowed is '{0}'.", (object)policy.MinimumPrice);
                executionContext.Abort(await commerceContext.AddMessage(error, "InvalidPrice", new object[] { policy.MinimumPrice }, defaultMessage).ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            PriceSnapshotComponent snapshot          = argument.PriceSnapshot;
            PriceSnapshotComponent snapshotComponent = card.Snapshots.FirstOrDefault(n => n.Id.Equals(snapshot.Id, StringComparison.OrdinalIgnoreCase));

            if (snapshotComponent == null)
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "PriceSnapshotNotFound", new object[] { snapshot.Id, card.FriendlyId }, "Price snapshot '" + snapshot.Id + "' on price card '" + card.FriendlyId + "' was not found.")
                .ConfigureAwait(false);

                return(card);
            }

            var tier = argument.PriceTier;

            if (string.IsNullOrEmpty(tier.Id))
            {
                tier.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
            }

            var membershipTiersComponent = snapshotComponent.GetComponent <MembershipTiersComponent>();
            var existingTier             = membershipTiersComponent?.Tiers.FirstOrDefault(t => t.Id.Equals(tier.Id, StringComparison.OrdinalIgnoreCase));

            if (existingTier == null)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          defaultMessage  = "Price tier '" + tier.Id + "' was not found in snapshot '" + snapshot.Id + "' for card '" + card.FriendlyId + ".";
                executionContext.Abort(await commerceContext.AddMessage(validationError, "PriceTierNotFound", new object[] { tier.Id, snapshot.Id, card.FriendlyId }, defaultMessage).ConfigureAwait(false), context);
                executionContext = null;
                return(card);
            }

            await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Information, null, null, "Edited price tier '" + tier.Id + "' from price snapshot '" + snapshot.Id + "'").ConfigureAwait(false);

            existingTier.Price = tier.Price;

            return(card);
        }
Exemple #27
0
        private async Task <bool?> CalculateCartLinePrice(
            CartLineComponent arg,
            CommercePipelineExecutionContext context)
        {
            ProductArgument productArgument = ProductArgument.FromItemId(arg.ItemId);
            SellableItem    sellableItem    = null;

            if (productArgument.IsValid())
            {
                sellableItem = context.CommerceContext.GetEntity((Func <SellableItem, bool>)(s => s.ProductId.Equals(productArgument.ProductId, StringComparison.OrdinalIgnoreCase)));

                if (sellableItem == null)
                {
                    string simpleName = productArgument.ProductId.SimplifyEntityName();
                    sellableItem = context.CommerceContext.GetEntity((Func <SellableItem, bool>)(s => s.ProductId.Equals(simpleName, StringComparison.OrdinalIgnoreCase)));

                    if (sellableItem != null)
                    {
                        sellableItem.ProductId = simpleName;
                    }
                }
            }
            if (sellableItem == null)
            {
                CommercePipelineExecutionContext executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                object[]        args            = new object[] { arg.ItemId };
                string          defaultMessage  = "Item '" + arg.ItemId + "' is not purchasable.";
                executionContext.Abort(await commerceContext.AddMessage(error, "LineIsNotPurchasable", args, defaultMessage), context);
                executionContext = null;
                return(new bool?());
            }

            MessagesComponent messagesComponent = arg.GetComponent <MessagesComponent>();

            messagesComponent.Clear(context.GetPolicy <KnownMessageCodePolicy>().Pricing);

            if (sellableItem.HasComponent <MessagesComponent>())
            {
                List <MessageModel> messages = sellableItem.GetComponent <MessagesComponent>().GetMessages(context.GetPolicy <KnownMessageCodePolicy>().Pricing);
                messagesComponent.AddMessages(messages);
            }
            arg.UnitListPrice = sellableItem.ListPrice;
            string listPriceMessage = "CartItem.ListPrice<=SellableItem.ListPrice: Price=" + arg.UnitListPrice.AsCurrency(false, null);
            string sellPriceMessage = string.Empty;
            PurchaseOptionMoneyPolicy optionMoneyPolicy = new PurchaseOptionMoneyPolicy();

            if (sellableItem.HasPolicy <PurchaseOptionMoneyPolicy>())
            {
                optionMoneyPolicy.SellPrice = sellableItem.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice;
                sellPriceMessage            = "CartItem.SellPrice<=SellableItem.SellPrice: Price=" + optionMoneyPolicy.SellPrice.AsCurrency(false, null);
            }

            PriceSnapshotComponent snapshotComponent;

            if (sellableItem.HasComponent <ItemVariationsComponent>())
            {
                ItemVariationSelectedComponent lineVariant             = arg.ChildComponents.OfType <ItemVariationSelectedComponent>().FirstOrDefault();
                ItemVariationsComponent        itemVariationsComponent = sellableItem.GetComponent <ItemVariationsComponent>();
                ItemVariationComponent         itemVariationComponent;

                if (itemVariationsComponent == null)
                {
                    itemVariationComponent = null;
                }
                else
                {
                    IList <Component> childComponents = itemVariationsComponent.ChildComponents;
                    itemVariationComponent = childComponents?.OfType <ItemVariationComponent>().FirstOrDefault(v =>
                    {
                        return(!string.IsNullOrEmpty(v.Id) ? v.Id.Equals(lineVariant?.VariationId, StringComparison.OrdinalIgnoreCase) : false);
                    });
                }

                if (itemVariationComponent != null)
                {
                    if (itemVariationComponent.HasComponent <MessagesComponent>())
                    {
                        List <MessageModel> messages = itemVariationComponent.GetComponent <MessagesComponent>().GetMessages(context.GetPolicy <KnownMessageCodePolicy>().Pricing);
                        messagesComponent.AddMessages(messages);
                    }

                    arg.UnitListPrice = itemVariationComponent.ListPrice;
                    listPriceMessage  = "CartItem.ListPrice<=SellableItem.Variation.ListPrice: Price=" + arg.UnitListPrice.AsCurrency(false, null);

                    if (itemVariationComponent.HasPolicy <PurchaseOptionMoneyPolicy>())
                    {
                        optionMoneyPolicy.SellPrice = itemVariationComponent.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice;
                        sellPriceMessage            = "CartItem.SellPrice<=SellableItem.Variation.SellPrice: Price=" + optionMoneyPolicy.SellPrice.AsCurrency(false, null);
                    }
                }
                snapshotComponent = itemVariationComponent != null?itemVariationComponent.ChildComponents.OfType <PriceSnapshotComponent>().FirstOrDefault() : null;
            }
            else
            {
                snapshotComponent = sellableItem.Components.OfType <PriceSnapshotComponent>().FirstOrDefault();
            }

            string currentCurrency = context.CommerceContext.CurrentCurrency();

            PriceTier priceTier = snapshotComponent?.Tiers.OrderByDescending(t => t.Quantity).FirstOrDefault(t =>
            {
                return(t.Currency.Equals(currentCurrency, StringComparison.OrdinalIgnoreCase) ? t.Quantity <= arg.Quantity : false);
            });

            Customer customer = await _findEntityPipeline.Run(new FindEntityArgument(typeof(Customer), context.CommerceContext.CurrentCustomerId(), false), context) as Customer;

            bool isMembershipLevelPrice = false;

            if (customer != null && customer.HasComponent <MembershipSubscriptionComponent>())
            {
                var membershipSubscriptionComponent = customer.GetComponent <MembershipSubscriptionComponent>();
                var membershipLevel = membershipSubscriptionComponent.MemerbshipLevelName;

                if (snapshotComponent != null && snapshotComponent.HasComponent <MembershipTiersComponent>())
                {
                    var membershipTiersComponent = snapshotComponent.GetComponent <MembershipTiersComponent>();
                    var membershipPriceTier      = membershipTiersComponent.Tiers.FirstOrDefault(x => x.MembershipLevel == membershipLevel);

                    if (membershipPriceTier != null)
                    {
                        optionMoneyPolicy.SellPrice = new Money(membershipPriceTier.Currency, membershipPriceTier.Price);
                        isMembershipLevelPrice      = true;

                        sellPriceMessage = string.Format("CartItem.SellPrice<=PriceCard.ActiveSnapshot: MembershipLevel={0}|Price={1}|Qty={2}", membershipSubscriptionComponent.MemerbshipLevelName, optionMoneyPolicy.SellPrice.AsCurrency(false, null), membershipPriceTier.Quantity);
                    }
                }
            }

            if (!isMembershipLevelPrice && priceTier != null)
            {
                optionMoneyPolicy.SellPrice = new Money(priceTier.Currency, priceTier.Price);
                sellPriceMessage            = string.Format("CartItem.SellPrice<=PriceCard.ActiveSnapshot: Price={0}|Qty={1}", optionMoneyPolicy.SellPrice.AsCurrency(false, null), priceTier.Quantity);
            }

            arg.Policies.Remove(arg.Policies.OfType <PurchaseOptionMoneyPolicy>().FirstOrDefault());

            if (optionMoneyPolicy.SellPrice == null)
            {
                return(false);
            }

            arg.SetPolicy(optionMoneyPolicy);

            if (!string.IsNullOrEmpty(sellPriceMessage))
            {
                messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, sellPriceMessage);
            }

            if (!string.IsNullOrEmpty(listPriceMessage))
            {
                messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, listPriceMessage);
            }

            return(true);
        }
        private async Task <bool> InventorySetExists(string inventorySetName, CommercePipelineExecutionContext context)
        {
            var inventorySet = await _findEntityPipeline.Run(new FindEntityArgument(typeof(InventorySet), inventorySetName.ToEntityId <InventorySet>(), 1), context);

            return(inventorySet != null);
        }