protected virtual string UpdateHierarchy(RelationshipArgument arg, string targetId, string rawChildren, ValueWrapper <bool> changed)
        {
            if (rawChildren == null)
            {
                rawChildren = string.Empty;
            }

            var list = rawChildren.Split(new char[1] {
                '|'
            }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var mode = arg.Mode;

            if (mode.GetValueOrDefault() == RelationshipMode.Create & mode.HasValue && !list.Contains(targetId))
            {
                if (!changed.Value)
                {
                    changed.Value = true;
                }

                list.RemoveAll(c => c.Equals(targetId, StringComparison.OrdinalIgnoreCase));
                list.Add(targetId);
            }
            else if (mode.GetValueOrDefault() == RelationshipMode.Delete & mode.HasValue && list.Contains(targetId))
            {
                if (!changed.Value)
                {
                    changed.Value = true;
                }

                list.RemoveAll(c => c.Equals(targetId, StringComparison.OrdinalIgnoreCase));
            }

            return(string.Join("|", list));
        }
        /// <summary>The execute.</summary>
        /// <param name="arg">The relationship argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="RelationshipArgument"/>.</returns>
        public override async Task <RelationshipArgument> Run(RelationshipArgument arg, CommercePipelineExecutionContext context)
        {
            if (context.CommerceContext.GetPolicy <CatalogNavigationPolicy>().UseUglySitecoreIds)
            {
                return(await base.Run(arg, context).ConfigureAwait(false));
            }

            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");

            var relationshipTypes = new string[4] {
                RelationshipTypes.CatalogToCategory,
                RelationshipTypes.CategoryToCategory,
                RelationshipTypes.CatalogToSellableItem,
                RelationshipTypes.CategoryToSellableItem
            };

            if (!(relationshipTypes).Contains(arg.RelationshipType, StringComparer.OrdinalIgnoreCase))
            {
                return(arg);
            }

            var sourceEntity = await Commander.Command <FindEntityCommand>().Process(context.CommerceContext, typeof(CatalogItemBase), arg.SourceName).ConfigureAwait(false) as CatalogItemBase;

            var stringList = new List <string>();

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

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

            foreach (string entityId in stringList)
            {
                var catalogItemBase = await Commander.Command <FindEntityCommand>().Process(context.CommerceContext, typeof(CatalogItemBase), entityId).ConfigureAwait(false) as CatalogItemBase;

                if (sourceEntity != null && catalogItemBase != null)
                {
                    var changed = new ValueWrapper <bool>(false);
                    var categoryRelationshipsComponent = catalogItemBase.GetComponent <CategoryHierarchyComponent>();
                    switch (arg.RelationshipType)
                    {
                    case RelationshipTypes.CatalogToCategory:
                        sourceEntity.ChildrenCategoryList               = UpdateHierarchy(arg, catalogItemBase.SitecoreId, sourceEntity.ChildrenCategoryList, sourceChanged);
                        catalogItemBase.ParentCatalogList               = UpdateHierarchy(arg, sourceEntity.SitecoreId, catalogItemBase.ParentCatalogList, changed);
                        catalogItemBase.CatalogToEntityList             = UpdateHierarchy(arg, sourceEntity.SitecoreId, catalogItemBase.CatalogToEntityList, changed);
                        categoryRelationshipsComponent.ParentEntityList = UpdateHierarchy(arg, sourceEntity.Id, categoryRelationshipsComponent.ParentEntityList, changed);
                        break;

                    case RelationshipTypes.CategoryToCategory:
                        sourceEntity.ChildrenCategoryList  = UpdateHierarchy(arg, catalogItemBase.SitecoreId, sourceEntity.ChildrenCategoryList, sourceChanged);
                        catalogItemBase.ParentCategoryList = UpdateHierarchy(arg, sourceEntity.SitecoreId, catalogItemBase.ParentCategoryList, changed);
                        catalogItemBase.ParentCatalogList  = UpdateHierarchy(arg, ExtractCatalogId(sourceEntity.Id), catalogItemBase.ParentCatalogList, changed);
                        categoryRelationshipsComponent.ParentEntityList = UpdateHierarchy(arg, sourceEntity.Id, categoryRelationshipsComponent.ParentEntityList, changed);
                        break;

                    case RelationshipTypes.CatalogToSellableItem:
                        sourceEntity.ChildrenSellableItemList           = UpdateHierarchy(arg, catalogItemBase.SitecoreId, sourceEntity.ChildrenSellableItemList, sourceChanged);
                        catalogItemBase.ParentCatalogList               = UpdateHierarchy(arg, sourceEntity.SitecoreId, catalogItemBase.ParentCatalogList, changed);
                        catalogItemBase.CatalogToEntityList             = UpdateHierarchy(arg, sourceEntity.SitecoreId, catalogItemBase.CatalogToEntityList, changed);
                        categoryRelationshipsComponent.ParentEntityList = UpdateHierarchy(arg, sourceEntity.Id, categoryRelationshipsComponent.ParentEntityList, changed);
                        break;

                    case RelationshipTypes.CategoryToSellableItem:
                        sourceEntity.ChildrenSellableItemList           = UpdateHierarchy(arg, catalogItemBase.SitecoreId, sourceEntity.ChildrenSellableItemList, sourceChanged);
                        catalogItemBase.ParentCategoryList              = UpdateHierarchy(arg, sourceEntity.SitecoreId, catalogItemBase.ParentCategoryList, changed);
                        catalogItemBase.ParentCatalogList               = UpdateHierarchy(arg, ExtractCatalogId(sourceEntity.Id), catalogItemBase.ParentCatalogList, changed);
                        categoryRelationshipsComponent.ParentEntityList = UpdateHierarchy(arg, sourceEntity.Id, categoryRelationshipsComponent.ParentEntityList, changed);
                        break;

                    default:
                        break;
                    }

                    if (changed.Value)
                    {
                        await Commander.PersistEntity(context.CommerceContext, catalogItemBase).ConfigureAwait(false);
                    }
                }
            }
            if (sourceChanged.Value)
            {
                await Commander.PersistEntity(context.CommerceContext, sourceEntity).ConfigureAwait(false);
            }

            return(arg);
        }
Exemplo n.º 3
0
        public override async Task <bool> Run(SellableItemInventorySetsArgument argument, CommercePipelineExecutionContext context)
        {
            AssociateStoreInventoryToSellablteItemBlock associateStoreInventoryToSellablteItemBlock = this;

            Condition.Requires(argument).IsNotNull(string.Format("{0}: The argument can not be null", argument));

            string         sellableItemId = argument.SellableItemId;
            CommerceEntity entity         = await associateStoreInventoryToSellablteItemBlock._findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), sellableItemId, false), context).ConfigureAwait(false);

            CommercePipelineExecutionContext executionContext;

            if (!(entity is SellableItem))
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          commerceTermKey = "EntityNotFound";
                object[]        args            = new object[1]
                {
                    argument.SellableItemId
                };
                string defaultMessage = string.Format("Entity {0} was not found.", argument.SellableItemId);
                executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage).ConfigureAwait(false), context);
                executionContext = null;
                return(false);
            }

            SellableItem sellableItem = entity as SellableItem;

            if ((string.IsNullOrEmpty(argument.VariationId)) & sellableItem.HasComponent <ItemVariationsComponent>())
            {
                executionContext = context;
                executionContext.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "AssociateInventoryWithVariant", new object[0], "Can not associate inventory to the base sellable item. Use one of the variants instead.").ConfigureAwait(false), context);
                executionContext = null;
                return(false);
            }

            ItemVariationComponent sellableItemVariation = null;

            if (argument.VariationId != null)
            {
                sellableItemVariation = sellableItem.GetVariation(argument.VariationId);
                if (!string.IsNullOrEmpty(argument.VariationId) && sellableItemVariation == null)
                {
                    executionContext = context;
                    CommerceContext commerceContext = context.CommerceContext;
                    string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                    string          commerceTermKey = "ItemNotFound";
                    object[]        args            = new object[1]
                    {
                        argument.VariationId
                    };
                    string defaultMessage = string.Format("Item '{0}' was not found.", argument.VariationId);
                    executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage).ConfigureAwait(false), context);
                    executionContext = null;
                    return(false);
                }
            }

            List <InventoryAssociation> inventoryAssociations = new List <InventoryAssociation>();

            foreach (var inventorySetId in argument.InventorySetIds)
            {
                bool   isUpdate = false;
                Random rnd      = new Random();
                InventoryInformation inventoryInformation = await associateStoreInventoryToSellablteItemBlock._getInventoryInformationCommand
                                                            .Process(context.CommerceContext, inventorySetId, argument.SellableItemId, argument.VariationId, false)
                                                            .ConfigureAwait(false);

                IFindEntitiesInListPipeline entitiesInListPipeline  = associateStoreInventoryToSellablteItemBlock._findEntitiesInListPipeline;
                FindEntitiesInListArgument  entitiesInListArgument1 = new FindEntitiesInListArgument(typeof(SellableItem), string.Format("{0}-{1}", "InventorySetToInventoryInformation", inventorySetId.SimplifyEntityName()), 0, int.MaxValue);
                entitiesInListArgument1.LoadEntities = false;
                CommercePipelineExecutionContext context1 = context;
                FindEntitiesInListArgument       entitiesInListArgument2 = await entitiesInListPipeline.Run(entitiesInListArgument1, context1).ConfigureAwait(false);

                if (inventoryInformation != null && entitiesInListArgument2 != null)
                {
                    List <ListEntityReference> entityReferences = entitiesInListArgument2.EntityReferences.ToList();
                    string id = inventoryInformation.Id;

                    if (entityReferences != null && entityReferences.Any(er => er.EntityId == id))
                    {
                        inventoryInformation.Quantity = rnd.Next(50);
                        isUpdate = true;
                    }
                }

                if (!isUpdate)
                {
                    string inventorySetName = string.Format("{0}-{1}", inventorySetId.SimplifyEntityName(), sellableItem.ProductId);
                    if (!string.IsNullOrEmpty(argument.VariationId))
                    {
                        inventorySetName += string.Format("-{0}", argument.VariationId);
                    }

                    InventoryInformation inventoryInformation1 = new InventoryInformation();
                    inventoryInformation1.Id = string.Format("{0}{1}", CommerceEntity.IdPrefix <InventoryInformation>(), inventorySetName);

                    inventoryInformation1.FriendlyId = inventorySetName;
                    EntityReference entityReference1 = new EntityReference(inventorySetId, "");
                    inventoryInformation1.InventorySet = entityReference1;
                    EntityReference entityReference2 = new EntityReference(argument.SellableItemId, "");
                    inventoryInformation1.SellableItem = entityReference2;
                    string variationId = argument.VariationId;
                    inventoryInformation1.VariationId = variationId;
                    inventoryInformation1.Quantity    = rnd.Next(50);
                    inventoryInformation = inventoryInformation1;
                }

                inventoryInformation.GetComponent <TransientListMembershipsComponent>().Memberships.Add(CommerceEntity.ListName <InventoryInformation>());
                PersistEntityArgument persistEntityArgument1 = await associateStoreInventoryToSellablteItemBlock._persistEntityPipeline.Run(new PersistEntityArgument((CommerceEntity)inventoryInformation), context).ConfigureAwait(false);

                RelationshipArgument relationshipArgument = await associateStoreInventoryToSellablteItemBlock._createRelationshipPipeline.Run(new RelationshipArgument(inventorySetId, inventoryInformation.Id, "InventorySetToInventoryInformation"), context).ConfigureAwait(false);

                InventoryAssociation inventoryAssociation = new InventoryAssociation()
                {
                    InventoryInformation = new EntityReference(inventoryInformation.Id, ""),
                    InventorySet         = new EntityReference(inventorySetId, "")
                };

                inventoryAssociations.Add(inventoryAssociation);
            }

            (sellableItemVariation != null ? sellableItemVariation.GetComponent <InventoryComponent>() : sellableItem.GetComponent <InventoryComponent>()).InventoryAssociations.AddRange(inventoryAssociations);

            PersistEntityArgument persistEntityArgument2 = await associateStoreInventoryToSellablteItemBlock._persistEntityPipeline.Run(new PersistEntityArgument(sellableItem), context).ConfigureAwait(false);

            return(true);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Interface to Create or Update Catalog
        /// Currently no dissasociation of categories is implemented
        /// </summary>
        /// <param name="context">context</param>
        /// <param name="parameter">parameter</param>
        /// <param name="updateExisting">Flag to determine if an existing catalog should be updated</param>
        /// <returns>Commerce Command</returns>
        public async Task <CommerceCommand> ExecuteImport(CommerceContext context, CreateOrUpdateCategoryParameter parameter, bool updateExisting)
        {
            // Try to get existing Category
            string   categoryId = $"{CommerceEntity.IdPrefix<Category>()}{parameter.CatalogName}-{parameter.Name}";
            Category category   = await this._getCategoryCommand.Process(context, categoryId);

            // If existing - Check if it should be updated
            if (category != null && !updateExisting)
            {
                return(this._getCategoryCommand);
            }

            // If existing - Get Current Category
            bool createdFlag = true;

            if (category == null)
            {
                createdFlag = false;
                category    = await this._createCategoryCommand.Process(context, parameter.CatalogName, parameter.Name, parameter.DisplayName, parameter.Description);
            }

            // Only update category if it was not created previously
            if (!createdFlag)
            {
                CatalogContentArgument editCategoryResult = await this._editCategoryCommand.Process(context, category, parameter.DisplayName, parameter.Description);
            }

            // Workaround to get all Parent Entities for the current Entity
            List <string> parentEntities = await this._associatedItemRetrievalService.GetAllParentEnitites(context, category.Name, parameter.CatalogName);

            // Check with the given paremter.ParentNames and the existing Parents, which ones have to be deleted
            foreach (string parentEntity in parentEntities)
            {
                // If both lists containt the entity, it should not be deleted
                if (parameter.ParentNames.Contains(parentEntity))
                {
                    continue;
                }

                // TargetName = Current Item
                string targetName;
                // SourceName = Parent
                string sourceName;
                // RelationshiptTypes - "CatalogToCategory","CatalogToSellableItem","CategoryToCategory","CategoryToSellableItem"
                string relationshipType;

                // Check if the entity is a catalog or category
                if (parentEntity.Equals(parameter.CatalogName))
                {
                    // Disassociate Catalog To Category
                    targetName       = category.Id;
                    sourceName       = $"{parentEntity}".ToEntityId <Catalog>();
                    relationshipType = "CatalogToCategory";
                }
                else
                {
                    // Disassociate Category To Category
                    targetName       = category.Id;
                    sourceName       = $"{parameter.CatalogName}-{parentEntity}".ToEntityId <Category>();
                    relationshipType = "CategoryToCategory";
                }

                RelationshipArgument relationshipArgument = await this._deleteRelationshipCommand.Process(context, sourceName, targetName, relationshipType);
            }

            // Associate category to parent
            string catalogId = parameter.CatalogName.ToEntityId <Catalog>();

            foreach (string parentName in parameter.ParentNames)
            {
                string entityIdentifier = parentName.Equals(parameter.CatalogName)
                  ? CommerceEntity.IdPrefix <Catalog>()
                  : $"{CommerceEntity.IdPrefix<Category>()}{parameter.CatalogName}-";
                string parentId = $"{entityIdentifier}{parentName}";
                CatalogContentArgument associateCategoryToParentResult = await this._associateCategoryToParentCommand.Process(context, catalogId, parentId, category.Id);
            }

            return(this._associateCategoryToParentCommand);
        }