Esempio n. 1
0
        /// <summary>
        /// Execute block entry point
        /// </summary>
        /// <param name="arg"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public override async Task <ImportCatalogEntityArgument> Run(ImportCatalogEntityArgument arg, CommercePipelineExecutionContext context)
        {
            CommerceEntity entity          = null;
            var            entityDataModel = context.GetModel <CatalogEntityDataModel>();

            Condition.Requires(entityDataModel, "CatalogEntityDataModel is required to exist in order for CommercePipelineExecutionContext to run").IsNotNull();
            Condition.Requires(entityDataModel.EntityId, "EntityId is reguired in input JSON data").IsNotNullOrEmpty();
            Condition.Requires(entityDataModel.CommerceEntityId, "Commerce Entity ID cannot be identified based on input JSON data").IsNotNullOrEmpty();

            if (entityDataModel != null)
            {
                entity = await _commerceCommander.Command <FindEntityCommand>().Process(context.CommerceContext, typeof(CommerceEntity), entityDataModel.CommerceEntityId);

                if (entity == null)
                {
                    var errorMessage = $"Error: Commerce Entity with ID={entityDataModel.EntityId} not found, UpdateComposerFieldsBlock cannot be executed.";
                    Log.Error(errorMessage);
                    context.Abort(errorMessage, this);
                    return(arg);
                }
                await ImportComposerViewsFields(entity, entityDataModel.EntityFields, context.CommerceContext);
            }
            else
            {
                var errorMessage = $"Error: SellableItemEntityData or CategoryEntityData model is required to be present in CommercePipelineExecutionContext for UpdateComposerFieldsBlock to run.";
                Log.Error(errorMessage);
                context.Abort(errorMessage, this);
                return(arg);
            }


            return(arg);
        }
        public async Task <bool> Process(CommerceContext commerceContext, string id)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                Setting setting = await _commerceCommander.Command <GetSettingCommand>().Process(commerceContext, id);

                if (setting == null)
                {
                    return(false);
                }

                setting.IsActive = true;
                await _commerceCommander.PersistEntity(commerceContext, setting);

                CommerceList <Setting> settings = await _commerceCommander.Command <FindEntitiesInListCommand>().Process <Setting>(commerceContext, CommerceEntity.ListName <Setting>(), 0, int.MaxValue);

                foreach (var listSetting in settings.Items)
                {
                    if (listSetting.Id.Equals(setting.Id))
                    {
                        continue;
                    }

                    listSetting.IsActive = false;
                    await _commerceCommander.PersistEntity(commerceContext, listSetting);
                }
            }

            return(true);
        }
Esempio n. 3
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            if (entityView == null ||
                !entityView.Action.Equals(context.GetPolicy <SettingsUiPolicy>().ActivateSettingActionName, StringComparison.OrdinalIgnoreCase))
            {
                return(entityView);
            }

            string targetId = string.IsNullOrEmpty(entityView.EntityId)
                ? entityView.ItemId
                : entityView.EntityId;

            try
            {
                var setting = await _commerceCommander.Command <GetSettingCommand>().Process(context.CommerceContext, targetId);

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

                await _commerceCommander.Command <ActivateSettingCommand>().Process(context.CommerceContext, setting.Id);
            }

            catch (Exception ex)
            {
                context.Logger.LogError($"{this.Name}.PathNotFound: Message={ex.Message}");
            }

            return(entityView);
        }
Esempio n. 4
0
        public async void Execute(IRuleExecutionContext context)
        {
            var commerceContext = context.Fact <CommerceContext>();
            var cart            = commerceContext?.GetObject <Cart>();

            var totals = commerceContext?.GetObject <CartTotals>();

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

            Commander.Command <ApplyFreeGiftEligibilityCommand>().Process(commerceContext, cart, GetType().Name);

            var matchingLines = MatchingLines(context);

            if (!matchingLines.Any() && AutoAddToCart.Yield(context))
            {
                await Commander.Command <AddCartLineCommand>().Process(commerceContext, cart, new CartLineComponent
                {
                    ItemId   = TargetItemId.Yield(context),
                    Quantity = QUANTITY_TO_ADD
                });
            }

            foreach (var matchingLine in matchingLines)
            {
                Commander.Command <ApplyFreeGiftDiscountCommand>().Process(commerceContext, matchingLine, GetType().Name);
                Commander.Command <ApplyFreeGiftAutoRemoveCommand>().Process(commerceContext, matchingLine, AutoRemove.Yield(context));
            }
        }
Esempio n. 5
0
        protected async Task ImportInventoryInformation(CommercePipelineExecutionContext context, CommerceEntity commerceEntity, string inventorySetId, string variantId, InventoryDetail inventoryDetail)
        {
            var result = await GetInventoryInformation(context, commerceEntity, inventorySetId, variantId)
                         .ConfigureAwait(false);

            if (inventoryDetail != null)
            {
                if (result.Item2)
                {
                    await _commerceCommander.Command <EditInventoryInformationCommand>()
                    .Process(context.CommerceContext, commerceEntity.Id, variantId, inventorySetId,
                             ConvertToEntityView(inventoryDetail));
                }
                else
                {
                    await _commerceCommander.Command <AssociateSellableItemToInventorySetCommand>()
                    .Process(context.CommerceContext, commerceEntity.Id, variantId, inventorySetId,
                             ConvertToEntityView(inventoryDetail))
                    .ConfigureAwait(false);
                }
            }
            else
            {
                if (result.Item2)
                {
                    await _commerceCommander.Command <DisassociateSellableItemFromInventorySetCommand>()
                    .Process(context.CommerceContext, commerceEntity.Id, variantId, inventorySetId);
                }
                else if (result.Item1 != null)
                {
                    await _commerceCommander.DeleteEntity(context.CommerceContext, result.Item1)
                    .ConfigureAwait(false);
                }
            }
        }
        /// <summary>
        /// Check if Catalog entity exists in Commerce DB and thorw exception if not
        /// </summary>
        /// <param name="context"></param>
        /// <param name="catalogName"></param>
        public void AssertCatalogExists(CommercePipelineExecutionContext context, string catalogName)
        {
            var     commerceCatalogId = $"{CommerceEntity.IdPrefix<Catalog>()}{catalogName}";
            Catalog catalog           = Task.Run <CommerceEntity>(async() => await _commerceCommander.Command <FindEntityCommand>().Process(context.CommerceContext, typeof(Catalog), commerceCatalogId)).Result as Catalog;

            if (catalog == null)
            {
                throw new ArgumentException($"Catalog '{catalogName}' not found");
            }
        }
Esempio n. 7
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            if (entityView == null ||
                !entityView.Action.Equals(context.GetPolicy <SettingsUiPolicy>().AddSettingActionName, StringComparison.OrdinalIgnoreCase))
            {
                return(entityView);
            }

            try
            {
                string name        = entityView.Properties.FirstOrDefault(element => element.Name.Equals("Name"))?.Value ?? string.Empty;;
                string displayName = entityView.Properties.FirstOrDefault(element => element.Name.Equals("Display Name"))?.Value ?? string.Empty;

                if (!string.IsNullOrEmpty(name) &&
                    !string.IsNullOrEmpty(displayName))
                {
                    await _commerceCommander.Command <CreateSettingCommand>().Process(context.CommerceContext, new CreateSettingArg(name, displayName));
                }
            }

            catch (Exception ex)
            {
                context.Logger.LogError($"{this.Name}.PathNotFound: Message={ex.Message}");
            }

            return(entityView);
        }
Esempio n. 8
0
        public override Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull($"{Name}: The argument cannot be null");
            var mainActionsPolicy = entityView.GetPolicy <ActionsPolicy>();

            var policies = _commerceCommander.Command <PolicyCollectionCommand>().Process(context.CommerceContext);

            foreach (var policy in policies)
            {
                string viewName   = policy.GetViewName();
                string actionName = policy.GetActionName();

                var view = entityView.ChildViews.FirstOrDefault(p => p.Name == viewName);
                if (view != null)
                {
                    var basicDataViewActionsPolicy = view.GetPolicy <ActionsPolicy>();


                    basicDataViewActionsPolicy.Actions.Add(new EntityActionView
                    {
                        Name                 = actionName,
                        DisplayName          = "Edit",
                        Description          = string.Empty,
                        IsEnabled            = true,
                        RequiresConfirmation = false,
                        EntityView           = actionName,
                        UiHint               = string.Empty,
                        Icon                 = "edit"
                    });
                }
            }

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

            if (entityView.Name != "ToolsNavigation")
            {
                return(entityView);
            }

            var pluginPolicy = context.GetPolicy <PluginPolicy>();

            await _commerceCommander.Command <PluginCommander>().CurrentUserSettings(context.CommerceContext, _commerceCommander);

            var newEntityView = new EntityView
            {
                Name        = "Plugins",
                DisplayName = "Plugins",
                Icon        = pluginPolicy.Icon,
                ItemId      = "Plugins"
            };

            entityView.ChildViews.Add(newEntityView);

            return(entityView);
        }
        public async Task <EntityView> ExecuteRun <T>(EntityView entityView, CommercePipelineExecutionContext context, string actionName) where T : Policy
        {
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The argument cannot be null");

            if (entityView.Name != actionName)
            {
                return(entityView);
            }

            string targetId = string.IsNullOrEmpty(entityView.EntityId)
               ? entityView.ItemId
               : entityView.EntityId;

            var setting = await _commerceCommander.Command <GetSettingCommand>().Process(context.CommerceContext, targetId);

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

            var importerPolicy = setting.GetPolicy <T>();

            try
            {
                foreach (var property in importerPolicy.GetType().GetProperties())
                {
                    var editorSetting = property.GetCustomAttribute <EditorSettingAttribute>();
                    if (editorSetting == null)
                    {
                        continue;
                    }

                    object value      = property.GetValue(importerPolicy);
                    string valueToUse = string.Empty;
                    if (value is IList <string> )
                    {
                        valueToUse = string.Join("|", value as IList <string>);
                    }
                    else
                    {
                        valueToUse = value?.ToString() ?? string.Empty;
                    }

                    entityView.Properties.Add(
                        new ViewProperty
                    {
                        Name       = editorSetting.DisplayName,
                        IsHidden   = false,
                        IsRequired = false,
                        RawValue   = valueToUse
                    });
                }
            }
            catch (Exception ex)
            {
                context.Logger.LogError($"Content.SynchronizeContentPath.PathNotFound: Message={ex.Message}");
            }

            return(await Task.FromResult(entityView));
        }
        public static async Task <T> GetSettingPolicy <T>(this CommercePipelineExecutionContext context, CommerceCommander commander) where T : Policy
        {
            var activeSetting = await commander.Command <GetActiveSettingCommand>().Process(context.CommerceContext);

            return(activeSetting?.HasPolicy <T>() ?? false
                ? activeSetting.GetPolicy <T>()
                : context.GetPolicy <T>());
        }
        public async Task <Setting> Process(CommerceContext commerceContext)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                CommerceList <Setting> settings = await _commerceCommander.Command <FindEntitiesInListCommand>().Process <Setting>(commerceContext, CommerceEntity.ListName <Setting>(), 0, int.MaxValue);

                return(settings.Items.FirstOrDefault(element => element.IsActive));
            }
        }
        public override async Task <CommerceEntity> Create()
        {
            Initialize();
            var command = CommerceCommander.Command <AddPromotionCommand>();

            CommerceEntity = await command.Process(Context.CommerceContext, BookName, Name, ValidFrom, ValidTo, Text, CartText, DisplayName, Description, IsExclusive);

            return(CommerceEntity);
        }
Esempio n. 14
0
        public override async Task <CommerceEntity> Create()
        {
            Initialize();
            var command = CommerceCommander.Command <CreateCatalogCommand>();

            CommerceEntity = await command.Process(Context.CommerceContext, Name, DisplayName);

            return(CommerceEntity);
        }
Esempio n. 15
0
        public override async Task <CommerceEntity> Create()
        {
            Initialize();
            var command = CommerceCommander.Command <CreateSellableItemCommand>();

            CommerceEntity = await command.Process(Context.CommerceContext, ProductId, Name, DisplayName, Description, Brand, Manufacturer, TypeOfGood, Tags.ToArray());

            return(CommerceEntity);
        }
Esempio n. 16
0
        public override async Task <CommerceEntity> Create()
        {
            Initialize();
            var command = CommerceCommander.Command <AddPriceCardCommand>();

            CommerceEntity = await command.Process(Context.CommerceContext, BookName, Name, DisplayName, Description);

            return(CommerceEntity);
        }
Esempio n. 17
0
        public override async Task <CommerceEntity> Create()
        {
            Initialize();
            var command = CommerceCommander.Command <CreateInventorySetCommand>();

            CommerceEntity = await command.Process(Context.CommerceContext, Name, DisplayName, Description);

            return(CommerceEntity);
        }
        public override async Task <CommerceEntity> Create()
        {
            Initialize();
            var command = CommerceCommander.Command <AddPriceBookCommand>();

            CommerceEntity = await command.Process(Context.CommerceContext, Name, DisplayName, Description, ParentBook, CurrencySetId);

            return(CommerceEntity);
        }
Esempio n. 19
0
        public void Execute(IRuleExecutionContext context)
        {
            var commerceContext = context.Fact <CommerceContext>();
            var cart            = commerceContext?.GetObject <Cart>();

            var totals = commerceContext?.GetObject <CartTotals>();

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

            Commander.Command <ApplyFreeGiftEligibilityCommand>().Process(commerceContext, cart, GetType().Name);

            var matchingLines = TargetTag.YieldCartLinesWithTag(context);

            foreach (var matchingLine in matchingLines)
            {
                Commander.Command <ApplyFreeGiftDiscountCommand>().Process(commerceContext, matchingLine, GetType().Name);
                Commander.Command <ApplyFreeGiftAutoRemoveCommand>().Process(commerceContext, matchingLine, AutoRemove.Yield(context));
            }
        }
Esempio n. 20
0
        public override Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Name) ||
                !arg.Name.Equals(context.GetPolicy <KnownInventoryViewsPolicy>().InventorySets,
                                 StringComparison.OrdinalIgnoreCase) || !string.IsNullOrEmpty(arg.Action) &&
                !arg.Action.Equals(context.GetPolicy <KnownImportInventoryActionsPolicy>().InventoryImport,
                                   StringComparison.OrdinalIgnoreCase))
            {
                return(Task.FromResult(arg));
            }
            if (!arg.Properties.Any(p => p.Name.Equals(nameof(InputModel.FileContent))))
            {
                return(Task.FromResult(arg));
            }

            var fileContent = arg.Properties.First(p => p.Name.Equals(nameof(InputModel.FileContent))).Value;
            var command     = ExecuteLongRunningCommand(context.CommerceContext, async() =>
            {
                var importInventorySetsCommand = _commerceCommander.Command <ImportInventorySetsCommand>();
                var baseStream   = new MemoryStream(Convert.FromBase64String(fileContent));
                var fileToImport = new FormFile(baseStream, 0, baseStream.Length, "file.zip", "file.zip");
                using (CommandActivity.Start(context.CommerceContext, importInventorySetsCommand))
                {
                    await importInventorySetsCommand.Process(context.CommerceContext, fileToImport, "replace", 900, 10);
                }

                return(importInventorySetsCommand);
            });

            // here should be import process
            arg.Properties.Add(new ViewProperty()
            {
                Name        = "LongRunningCommand",
                DisplayName = "Inventories import status",
                RawValue    = string.Empty,
                Value       = JsonConvert.SerializeObject(new
                {
                    LongRunningTaskId = command.TaskId,
                    UpdatePeriod      = TimeSpan.FromSeconds(3).TotalMilliseconds,
                    RunningMessage    = "Inventories import is in progress",
                    SuccessMessage    = "Inventories import is finished successfully",
                    ErrorMessage      = "Inventories import is failed. See logs for more details."
                }),
                IsReadOnly = false,
                IsHidden   = false,
                UiType     = "LongRunningCommand"
            });
            context.CommerceContext.AddModel(arg);
            arg.Properties.Remove(arg.Properties.FirstOrDefault(x => x.Name.Equals(nameof(InputModel.FileContent))));
            return(Task.FromResult(arg));
        }
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Contract.Requires(entityView != null);
            Contract.Requires(context != null);
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The argument cannot be null");
            if (entityView.Name != "VatTaxDashboard")
            {
                return(entityView);
            }
            //var pluginPolicy = context.GetPolicy<PluginPolicy>();

            var newEntityViewTable = entityView;

            entityView.UiHint = "Table";
            entityView.Icon   = "money_dollar";
            entityView.ItemId = string.Empty;

            var sampleDashboardEntities = await _commerceCommander.Command <ListCommander>()
                                          .GetListItems <VatTaxEntity>(context.CommerceContext,
                                                                       CommerceEntity.ListName <VatTaxEntity>(), 0, 99).ConfigureAwait(false);

            //var sampleDashboardEntities = await this._commerceCommander.Command<ListCommander>().GetListItems<VatTaxEntity>(context.CommerceContext,CommerceEntity.ListName<VatTaxEntity>(), 0, 99);
            foreach (var sampleDashboardEntity in sampleDashboardEntities)
            {
                newEntityViewTable.ChildViews.Add(
                    new EntityView
                {
                    ItemId     = sampleDashboardEntity.Id,
                    Icon       = "money_dollar",
                    Properties = new List <ViewProperty>
                    {
                        new ViewProperty {
                            Name = "TaxTag", RawValue = sampleDashboardEntity.TaxTag
                        },
                        new ViewProperty {
                            Name = "CountryCode", RawValue = sampleDashboardEntity.CountryCode
                        },
                        new ViewProperty {
                            Name = "TaxPct", RawValue = sampleDashboardEntity.TaxPct
                        }
                    }
                });
            }


            /* STUDENT: Complete the body of the Run method. You should handle the
             * entity view for both a new and existing entity. */
            return(entityView);
        }
        public async Task <bool> Process(CommerceContext commerceContext, string id)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                Setting setting = await _commerceCommander.Command <GetSettingCommand>().Process(commerceContext, id);

                if (setting == null)
                {
                    return(false);
                }

                setting.IsActive = false;
                await _commerceCommander.PersistEntity(commerceContext, setting);
            }

            return(true);
        }
Esempio n. 23
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Contract.Requires(entityView != null);
            Contract.Requires(context != null);
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The argument cannot be null");

            if (entityView != null && entityView.Name != "VatTaxDashboard")
            {
                return(entityView);
            }
            var pluginPolicy = context != null?context.GetPolicy <PluginPolicy>() : null;

            if (entityView != null)
            {
                var newEntityViewTable = entityView;
                entityView.UiHint = "Table";
                entityView.Icon   = "cubes";
                entityView.ItemId = string.Empty;

                var sampleDashboardEntities = await _commerceCommander.Command <ListCommander>().GetListItems <VatTaxEntity>(context.CommerceContext, CommerceEntity.ListName <VatTaxEntity>(), 0, 99).ConfigureAwait(false);

                foreach (var sampleDashboardEntity in sampleDashboardEntities)
                {
                    newEntityViewTable.ChildViews.Add(
                        new EntityView
                    {
                        ItemId     = sampleDashboardEntity.Id,
                        Icon       = "cubes",
                        Properties = new List <ViewProperty>
                        {
                            new ViewProperty {
                                Name = "TaxTag", RawValue = sampleDashboardEntity.TaxTag
                            },
                            new ViewProperty {
                                Name = "CountryCode", RawValue = sampleDashboardEntity.CountryCode
                            },
                            new ViewProperty {
                                Name = "TaxPct", RawValue = sampleDashboardEntity.TaxPct
                            }
                        }
                    });
                }
            }
            return(entityView);
        }
Esempio n. 24
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull($"{Name}: The argument cannot be null");

            if (entityView.Name != "ToolsNavigation")
            {
                return(entityView);
            }

            var pluginPolicy      = context.GetPolicy <ServiceBusOrderPlacedPolicy>();
            var userPluginOptions = await _commerceCommander.Command <PluginCommander>().CurrentUserSettings(context.CommerceContext, _commerceCommander);

            if (userPluginOptions.EnabledPlugins.Contains("Feature.Orders.ServiceBus"))
            {
                if (userPluginOptions.HasPolicy <ServiceBusOrderPlacedPolicy>())
                {
                    pluginPolicy = userPluginOptions.GetPolicy <ServiceBusOrderPlacedPolicy>();
                }
                else
                {
                    pluginPolicy.Enabled = false;
                }
            }
            else
            {
                pluginPolicy.Enabled = true;
            }

            if (!pluginPolicy.Enabled)
            {
                return(entityView);
            }

            var newEntityView = new EntityView
            {
                Name        = "ServiceBus",
                DisplayName = "Service Bus",
                Icon        = pluginPolicy.Icon,
                ItemId      = "ServiceBus"
            };

            entityView.ChildViews.Add(newEntityView);
            return(entityView);
        }
        public override async Task <CommerceEntity> Create()
        {
            if (ParentEntityIds == null || !ParentEntityIds.Any())
            {
                Context.Abort(await Context.CommerceContext.AddMessage(Context.GetPolicy <KnownResultCodes>().Error, "CategoryCatalogNotDefined", null, "Catalog must be defined to create a new category."), Context);
                return(CommerceEntity);
            }

            var firstParent = ParentEntityIds.FirstOrDefault();

            CatalogId = firstParent.Key;

            Initialize();
            var command = CommerceCommander.Command <CreateCategoryCommand>();

            CommerceEntity = await command.Process(Context.CommerceContext, CatalogId, Name, DisplayName, Description);

            return(CommerceEntity);
        }
Esempio n. 26
0
        /// <summary>
        /// Associate SellableItem with parent Catalog and Category(if exists)
        /// </summary>
        /// <param name="catalogName"></param>
        /// <param name="parentCategoryName"></param>
        /// <param name="sellableItem"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task <SellableItem> AssociateSellableItemWithParent(string catalogName, string parentCategoryName, SellableItem sellableItem, bool allowSyncToRoot, CommerceContext context)
        {
            string parentCategoryCommerceId = null;

            if (!string.IsNullOrEmpty(parentCategoryName))
            {
                var categoryCommerceId = $"{CommerceEntity.IdPrefix<Category>()}{catalogName}-{parentCategoryName}";
                var parentCategory     = await _commerceCommander.Command <FindEntityCommand>().Process(context, typeof(Category), categoryCommerceId) as Category;

                parentCategoryCommerceId = parentCategory?.Id;
            }

            //TODO: Delete old relationships
            //var deassociateResult = await _commerceCommander.Command<DeleteRelationshipCommand>().Process(context, oldParentCategory.Id, sellableItem.Id, "CategoryToSellableItem");

            var catalogCommerceId = $"{CommerceEntity.IdPrefix<Catalog>()}{catalogName}";

            if (!string.IsNullOrEmpty(parentCategoryCommerceId))
            {
                await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(context,
                                                                                                  catalogCommerceId,
                                                                                                  parentCategoryCommerceId,
                                                                                                  sellableItem.Id);

                return(await _commerceCommander.Command <FindEntityCommand>().Process(context, typeof(SellableItem), sellableItem.Id) as SellableItem);
            }
            else if (allowSyncToRoot)
            {
                await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process(context,
                                                                                                  catalogCommerceId,
                                                                                                  catalogCommerceId,
                                                                                                  sellableItem.Id);

                return(await _commerceCommander.Command <FindEntityCommand>().Process(context, typeof(SellableItem), sellableItem.Id) as SellableItem);
            }

            return(sellableItem);
        }
Esempio n. 27
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull($"{Name}: The argument cannot be null");
            if (entityView.Name != "ProductImport-Dashboard")
            {
                return(entityView);
            }

            entityView.EntityId = string.Empty;
            entityView.Name     = "Product Import";
            entityView.UiHint   = "Table";

            try
            {
                _commerceCommander.Command <ChildViewProductImport>().Process(context.CommerceContext, entityView);
            }
            catch (Exception ex)
            {
                context.Logger.LogError(ex, "ProductImport.DashBoard.Exception");
            }
            return(entityView);
        }
        public override async Task <ImportEntityArgument> Run(ImportEntityArgument arg, CommercePipelineExecutionContext context)
        {
            if (arg.ImportHandler.HasRelationships())
            {
                var relationships = arg.ImportHandler.GetRelationships();

                foreach (var relationshipDetail in relationships)
                {
                    if (!string.IsNullOrEmpty(relationshipDetail.Name) && relationshipDetail.Ids != null &&
                        relationshipDetail.Ids.Any())
                    {
                        var relationShipMapper = await _commerceCommander.Pipeline <IResolveRelationshipMapperPipeline>()
                                                 .Run(new ResolveRelationshipMapperArgument(arg, relationshipDetail.Name), context).ConfigureAwait(false);

                        if (relationShipMapper == null)
                        {
                            continue;
                        }

                        if (!string.IsNullOrEmpty(relationShipMapper.Name))
                        {
                            var targetIds = await relationShipMapper.GetEntityIds(relationshipDetail.Ids).ConfigureAwait(false);

                            if (targetIds.Any())
                            {
                                var targetName = targetIds.Aggregate(new StringBuilder(),
                                                                     (sb, id) => sb.Append(id).Append("|"), sb => sb.ToString().Trim('|'));

                                await _commerceCommander.Command <CreateRelationshipCommand>().Process(context.CommerceContext,
                                                                                                       arg.ImportHandler.GetCommerceEntity().Id,
                                                                                                       targetName, relationShipMapper.Name);
                            }
                        }
                    }
                }
            }

            return(await Task.FromResult(arg));
        }
Esempio n. 29
0
        public virtual async Task <IEnumerable <GiftCard> > Process(CommerceContext commerceContext,
                                                                    DateTimeOffset startDate, DateTimeOffset endDate)
        {
            // Filter order on activation date
            var filterQuery = new FilterQuery(new AndFilterNode(new LessThanFilterNode(
                                                                    new FieldNameFilterNode("activationdate"),
                                                                    new FieldValueFilterNode(endDate
                                                                                             .ToString(SearchConstants.DateTimeSearchFormat, CultureInfo.InvariantCulture),
                                                                                             FilterNodeValueType.Date)),
                                                                new GreaterThanFilterNode(new FieldNameFilterNode("activationdate"),
                                                                                          new FieldValueFilterNode(
                                                                                              startDate
                                                                                              .ToString(SearchConstants.DateTimeSearchFormat, CultureInfo.InvariantCulture),
                                                                                              FilterNodeValueType.Date))));

            var scope = SearchScopePolicy.GetPolicyByType(commerceContext, commerceContext.Environment,
                                                          typeof(GiftCard));

            var searchResults = await _commander.Command <SearchEntitiesCommand>()
                                .Process <GiftCard>(commerceContext, scope.Name, new SearchQuery(), filterQuery).ConfigureAwait(false);

            return(searchResults.OrderByDescending(g => g.ActivationDate));
        }
Esempio n. 30
0
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">The SampleArgument argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="SampleEntity"/>.</returns>
        public override async Task <SampleEntity> Run(TransactionArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{Name}: The argument can not be null");

            if (arg.ErrorBeforeInnerScope)
            {
                await context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    "ForcedError",
                    new object[] { nameof(arg.ErrorBeforeInnerScope) },
                    $"Error in {nameof(arg.ErrorBeforeInnerScope)}.").ConfigureAwait(false);
            }

            await Commander.Command <InnerCommand>().Process(context.CommerceContext, arg).ConfigureAwait(false);

            var result = new SampleEntity()
            {
                Id = $"{CommerceEntity.IdPrefix<SampleEntity>()}Outer-{Guid.NewGuid().ToString()}"
            };

            await Commander.PersistEntity(context.CommerceContext, result).ConfigureAwait(false);

            if (arg.ErrorOnOuterScope)
            {
                context.Abort(
                    await context.CommerceContext.AddMessage(
                        context.GetPolicy <KnownResultCodes>().ValidationError,
                        "ForcedError",
                        new object[] { nameof(arg.ErrorOnOuterScope) },
                        $"Error in {nameof(arg.ErrorOnOuterScope)}.").ConfigureAwait(false),
                    context);

                return(null);
            }

            return(result);
        }