示例#1
0
        /// <summary>
        /// Find and return an existing Category or create a new one
        /// </summary>
        /// <param name="entityData"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task <SellableItem> GetOrCreateSellableItem(CatalogEntityDataModel entityData, CommercePipelineExecutionContext context)
        {
            SellableItem sellableItem = await _commerceCommander.Command <FindEntityCommand>().Process(context.CommerceContext, typeof(SellableItem), entityData.CommerceEntityId) as SellableItem;

            if (sellableItem == null)
            {
                sellableItem = await _commerceCommander.Command <CreateSellableItemCommand>().Process(context.CommerceContext,
                                                                                                      entityData.EntityId,
                                                                                                      entityData.EntityName,
                                                                                                      entityData.EntityFields.ContainsKey("DisplayName") ? entityData.EntityFields["DisplayName"] : entityData.EntityName,
                                                                                                      entityData.EntityFields.ContainsKey("Description") ? entityData.EntityFields["Description"] : string.Empty,
                                                                                                      entityData.EntityFields.ContainsKey("Brand") ? entityData.EntityFields["Brand"] : string.Empty,
                                                                                                      entityData.EntityFields.ContainsKey("Manufacturer") ? entityData.EntityFields["Manufacturer"] : string.Empty,
                                                                                                      entityData.EntityFields.ContainsKey("TypeOfGoods") ? entityData.EntityFields["TypeOfGoods"] : string.Empty);
            }
            else
            {
                sellableItem.DisplayName  = entityData.EntityFields.ContainsKey("DisplayName") ? entityData.EntityFields["DisplayName"] : entityData.EntityName;
                sellableItem.Description  = entityData.EntityFields.ContainsKey("Description") ? entityData.EntityFields["Description"] : string.Empty;
                sellableItem.Brand        = entityData.EntityFields.ContainsKey("Brand") ? entityData.EntityFields["Brand"] : string.Empty;
                sellableItem.Manufacturer = entityData.EntityFields.ContainsKey("Manufacturer") ? entityData.EntityFields["Manufacturer"] : string.Empty;
                sellableItem.TypeOfGood   = entityData.EntityFields.ContainsKey("TypeOfGoods") ? entityData.EntityFields["TypeOfGoods"] : string.Empty;

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


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

            return(await _commerceCommander.Command <FindEntityCommand>().Process(context.CommerceContext, typeof(SellableItem), sellableItem.Id) as SellableItem);
        }
        private async Task PerformEntityVariantsLocalization(ImportLocalizeContentArgument arg,
                                                             CommercePipelineExecutionContext context, ILanguageEntity language,
                                                             IList <LocalizableComponentPropertiesValues> componentsPropertiesList)
        {
            foreach (var variant in arg.ImportEntityArgument.ImportHandler.GetVariants(language))
            {
                var itemVariationComponent = arg.CommerceEntity.GetVariation(variant.Id);

                if (itemVariationComponent == null)
                {
                    continue;
                }

                var itemVariantComponentLocalizationMapper = await _commerceCommander
                                                             .Pipeline <IResolveComponentLocalizationMapperPipeline>()
                                                             .Run(new ResolveComponentLocalizationMapperArgument(arg.ImportEntityArgument, arg.CommerceEntity,
                                                                                                                 itemVariationComponent, language, variant), context).ConfigureAwait(false);

                if (itemVariantComponentLocalizationMapper != null)
                {
                    itemVariantComponentLocalizationMapper.Execute(componentsPropertiesList, itemVariationComponent,
                                                                   language);

                    await PerformEntityVariantLocalization(arg, context, language, componentsPropertiesList,
                                                           itemVariationComponent, variant).ConfigureAwait(false);
                }
                else
                {
                    await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Warning, "ItemVariantComponentLocalizationMapperMissing", null, "Item variant component localization mapper instance for not resolved.");
                }
            }
        }
示例#3
0
        private async Task ImportRelationships()
        {
            foreach (var sourceCategory in _synchronizeCatalogArgument.Categories.FindAll(x =>
                                                                                          x.Operation.ToLower() != "delete" &&
                                                                                          string.IsNullOrEmpty(x.ParentId) == false &&
                                                                                          string.IsNullOrEmpty(x.ParentType) == false))
            {
                var result = await _commerceCommander.Pipeline <IAssociateCategoryToParentPipeline>().Run(
                    new CatalogReferenceArgument(
                        sourceCategory.FullCatalogId,
                        sourceCategory.FullParentId,
                        sourceCategory.FullIdWithCatalog), _context.CommerceContext.PipelineContextOptions)
                             .ConfigureAwait(false);
            }

            foreach (var sourceProduct in _synchronizeCatalogArgument.Products.FindAll(x =>
                                                                                       x.Operation.ToLower() != "delete" &&
                                                                                       string.IsNullOrEmpty(x.ParentId) == false &&
                                                                                       string.IsNullOrEmpty(x.ParentType) == false))
            {
                var result = await _commerceCommander.Pipeline <IAssociateSellableItemToParentPipeline>().Run(
                    new CatalogReferenceArgument(
                        sourceProduct.FullCatalogId,
                        sourceProduct.FullParentId,
                        sourceProduct.FullId), _context.CommerceContext.PipelineContextOptions)
                             .ConfigureAwait(false);
            }
        }
        /// <summary>Executes the pipeline block's code logic.</summary>
        /// <param name="arg">The pipeline argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="EntityView"/>.</returns>
        public override async Task <EntityView> RunAsync(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Action) ||
                !arg.Action.Equals(context.GetPolicy <KnownEntityVersionsActionsPolicy>().AddEntityVersion, StringComparison.OrdinalIgnoreCase))
            {
                return(arg);
            }

            var commerceEntity = context.CommerceContext.GetObjects <CommerceEntity>().FirstOrDefault(p => p.Id.Equals(arg.EntityId, StringComparison.OrdinalIgnoreCase));

            if (commerceEntity == null)
            {
                await context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().ValidationError,
                    "EntityNotFound",
                    new object[]
                {
                    arg.EntityId
                },
                    $"Entity {arg.EntityId} was not found.")
                .ConfigureAwait(false);

                return(arg);
            }

            var findArg  = new FindEntityArgument(typeof(VersioningEntity), VersioningEntity.GetIdBasedOnEntityId(commerceEntity.Id));
            var versions = await _commerceCommander.Pipeline <IFindEntityPipeline>()
                           .RunAsync(findArg, context)
                           .ConfigureAwait(false);

            var latestVersion = (versions as VersioningEntity)?.LatestVersion(context.CommerceContext) ?? 1;
            var newVersion    = latestVersion + 1;

            await _commerceCommander.ProcessWithTransaction(context.CommerceContext,
                                                            () => _commerceCommander.Pipeline <IAddEntityVersionPipeline>()
                                                            .RunAsync(new AddEntityVersionArgument(commerceEntity)
            {
                CurrentVersion = commerceEntity.EntityVersion,
                NewVersion     = newVersion
            },
                                                                      context.CommerceContext.PipelineContextOptions)).ConfigureAwait(false);

            context.CommerceContext.AddModel(
                new RedirectUrlModel($"/entityView/Master/{newVersion}/{arg.EntityId}")
                );

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

            var sellableItem = context.CommerceContext.GetEntity <SellableItem>(x => x.Id.Equals(arg.SellableItemId, StringComparison.OrdinalIgnoreCase))
                               ?? await _commander.Pipeline <IFindEntityPipeline>()
                               .Run(new FindEntityArgument(typeof(SellableItem), arg.SellableItemId.EnsurePrefix(CommerceEntity.IdPrefix <SellableItem>())), context)
                               .ConfigureAwait(false) as SellableItem;

            if (sellableItem == null)
            {
                return(null);
            }

            var inventoryInformation = await GetSellableItemInventoryInformation(sellableItem, arg.VariationId, arg, context).ConfigureAwait(false);

            if (inventoryInformation != null)
            {
                context.CommerceContext.AddUniqueEntity(inventoryInformation);
            }

            return(inventoryInformation);
        }
        public override async Task <ItemAvailabilityComponent> Run(ItemAvailabilityComponent arg, CommercePipelineExecutionContext context)
        {
            if (arg == null || string.IsNullOrEmpty(arg.ItemId))
            {
                return(arg);
            }

            var productArgument = ProductArgument.FromItemId(arg.ItemId);
            var sellableItem    = context.CommerceContext.GetEntity <SellableItem>(x => x.Id.Equals($"{CommerceEntity.IdPrefix<SellableItem>()}{productArgument.ProductId}", StringComparison.OrdinalIgnoreCase))
                                  ?? await _commander.Pipeline <IGetSellableItemPipeline>().Run(productArgument, context).ConfigureAwait(false);

            if (sellableItem == null || !sellableItem.Tags.Any(t => t.Name.Equals("D365")))
            {
                return(arg);
            }

            // This is needed if not having an inventory set assoicated to the sellable-item.
            // Without the InventoryComponent on the sellabl-item, inventory won't show on the PDP or within cart.
            if (!string.IsNullOrEmpty(productArgument.VariantId))
            {
                sellableItem.GetComponent <InventoryComponent>(productArgument.VariantId);
            }
            else
            {
                sellableItem.GetComponent <InventoryComponent>();
            }

            return(arg);
        }
        private async Task SetCommerceEntityDetails(CommerceEntity commerceEntity, ImportEntityArgument importEntityArgument, CommercePipelineExecutionContext context)
        {
            if (!importEntityArgument.IsNew)
            {
                if (importEntityArgument.ImportHandler is IEntityMapper mapper)
                {
                    mapper.Map();
                }
                else
                {
                    mapper = await _commerceCommander.Pipeline <IResolveEntityMapperPipeline>()
                             .Run(new ResolveEntityMapperArgument(importEntityArgument, commerceEntity), context)
                             .ConfigureAwait(false);

                    if (mapper == null)
                    {
                        await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Warning, "EntityMapperMissing", null, $"Entity mapper instance for entityType={importEntityArgument.SourceEntityDetail.EntityType} not resolved.");
                    }
                    else
                    {
                        mapper.Map();
                    }
                }
            }
        }
        /// <summary>
        /// Executes the block.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override async Task <string> Run(string arg, CommercePipelineExecutionContext context)
        {
            var artifactSet = "Environment.Habitat.Catalog-1.0";

            // Check if this environment has subscribed to this Artifact Set
            if (!context.GetPolicy <EnvironmentInitializationPolicy>().InitialArtifactSets.Contains(artifactSet))
            {
                return(arg);
            }

            using (var stream = new FileStream(GetPath("Habitat_Inventory.zip"), FileMode.Open, FileAccess.Read))
            {
                var file = new FormFile(stream, 0, stream.Length, stream.Name, stream.Name);

                var argument = new ImportInventorySetsArgument(file, CatalogConstants.Replace)
                {
                    BatchSize      = -1,
                    ErrorThreshold = 10
                };
                await _commander.Pipeline <IImportInventorySetsPipeline>()
                .Run(argument, context.CommerceContext.PipelineContextOptions)
                .ConfigureAwait(false);
            }

            return(arg);
        }
示例#9
0
 public async Task <Order> Process(CommerceContext commerceContext, ConvertGuestOrderToMemberOrderArgument arg)
 {
     using (CommandActivity.Start(commerceContext, this))
     {
         return(await _commerceCommander.Pipeline <IConvertGuestOrderToMemberOrderPipeline>().Run(arg, commerceContext.GetPipelineContextOptions()));
     }
 }
示例#10
0
        public async Task <SynchronizeCatalogResult> Process(CommerceContext commerceContext, SynchronizeCatalogArgument arg)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                var result = await _commander.Pipeline <ISynchronizeCatalogPipeline>().Run(arg, new CommercePipelineExecutionContextOptions(commerceContext)).ConfigureAwait(false);

                return(result);
            }
        }
示例#11
0
        public override async Task <ImportEntityArgument> Run(ImportEntityArgument arg, CommercePipelineExecutionContext context)
        {
            var importHandler = await _commerceCommander.Pipeline <IResolveEntityImportHandlerPipeline>()
                                .Run(new ResolveEntityImportHandlerArgument(arg), context)
                                .ConfigureAwait(false);

            if (importHandler == null)
            {
                context.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, "ImportHandlerMissing", null, $"Import handler instance for entityType={arg.SourceEntityDetail.EntityType} not resolved."), context);
            }

            arg.ImportHandler = importHandler;
            return(arg);
        }
示例#12
0
        public override async Task <CommerceEntity> Create()
        {
            var commerceEntity = new CustomCommerceItem();

            commerceEntity.Id          = IdWithPrefix();
            commerceEntity.Name        = SourceEntity.Name;
            commerceEntity.DisplayName = SourceEntity.DisplayName;
            commerceEntity.Description = SourceEntity.Description;

            await CommerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(commerceEntity), Context).ConfigureAwait(false);

            return(commerceEntity);
        }
示例#13
0
        public override async Task <CommerceEntity> Create()
        {
            CommerceEntity    = new TCommerceEntity();
            CommerceEntity.Id = IdWithPrefix();
            Initialize();
            if (CommerceEntity == null)
            {
                Context.Abort(Context.CommerceContext.AddMessage(Context.GetPolicy <KnownResultCodes>().Error, "EntityIsMissing", null, "Entity cannot be null.").Result, Context);
            }

            await CommerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(CommerceEntity), Context).ConfigureAwait(false);

            return(CommerceEntity);
        }
示例#14
0
        /// <summary>
        /// Executes the pipeline block.
        /// </summary>
        /// <param name="arg">The entity view.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull($"{Name}: The argument cannot be null");

            var viewsPolicy        = context.GetPolicy <Policies.KnownInventoryViewsPolicy>();
            var entityViewArgument = context.CommerceContext.GetObject <EntityViewArgument>();
            var enablementPolicy   = context.GetPolicy <Policies.InventoryFeatureEnablementPolicy>();

            if (!enablementPolicy.InventoryFromProductView ||
                string.IsNullOrEmpty(entityViewArgument?.ViewName) ||
                !entityViewArgument.ViewName.Equals(viewsPolicy.SelectInventorySet, StringComparison.OrdinalIgnoreCase))
            {
                return(await Task.FromResult(entityView).ConfigureAwait(false));
            }

            var inventorySets =
                await CommerceCommander.Pipeline <FindEntitiesInListPipeline>().Run(
                    new FindEntitiesInListArgument(
                        typeof(InventorySet),
                        $"{CommerceEntity.ListName<InventorySet>()}",
                        0,
                        int.MaxValue),
                    context).ConfigureAwait(false);

            var availableSelectionsPolicy = new AvailableSelectionsPolicy(
                inventorySets.List.Items.Select(s =>
                                                new Selection {
                DisplayName = s.DisplayName, Name = s.Name
            }).ToList()
                ?? new List <Selection>());

            var viewProperty = new ViewProperty()
            {
                Name     = "Inventory Set",
                UiType   = "SelectList",
                Policies = new List <Policy>()
                {
                    availableSelectionsPolicy
                },
                RawValue =
                    availableSelectionsPolicy.List.Where(s => s.IsDefault).FirstOrDefault()?.Name
                    ?? availableSelectionsPolicy.List?.FirstOrDefault().Name
            };

            entityView.Properties.Add(viewProperty);

            return(entityView);
        }
示例#15
0
        public async Task <Setting> Process(CommerceContext commerceContext, string id)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                var rawEntitiy = await _commerceCommander.Pipeline <IFindEntityPipeline>().Run(new FindEntityArgument(typeof(Setting), id.ToEntityId <Setting>()), commerceContext.PipelineContextOptions);

                if (rawEntitiy == null)
                {
                    return(null);
                }
                else
                {
                    return(rawEntitiy as Setting);
                }
            }
        }
示例#16
0
        public async Task <MinionRunResultsModel> Run(DateTimeOffset start, DateTimeOffset now)
        {
            CartsCleanupMinion minion = this;

            minion.Logger.LogInformation($"{minion.Name} - Review List {minion.Policy.ListToWatch}");

            if (!AllowExecution(start))
            {
                minion.Logger.LogInformation($"{minion.Name} - Skipping execution due to current system time '{start}' being outside of allowed execution windows.");
                return(new MinionRunResultsModel());
            }

            long listCount = await minion.GetListCount(minion.Policy.ListToWatch);

            minion.Logger.LogInformation($"{minion.Name} - Review List {minion.Policy.ListToWatch} - Has Count {listCount}");

            if (listCount <= 0)
            {
                return(new MinionRunResultsModel());
            }

            for (int listIndex = 0; listCount >= listIndex; listIndex += minion.Policy.ItemsPerBatch)
            {
                var cartList = await minion.GetListItems <Cart>(minion.Policy.ListToWatch, minion.Policy.ItemsPerBatch, listIndex);

                if (cartList == null || cartList.Count().Equals(0))
                {
                    break;
                }

                foreach (var cart in (cartList))
                {
                    if (maintenancePolicy.StopOverrun && !AllowExecution(GetNowDateTime(now)))
                    {
                        minion.Logger.LogInformation($"{minion.Name} - Skipping execution due to current system time '{now.TimeOfDay}' being outside of allowed execution window.");
                        return(new MinionRunResultsModel());
                    }

                    minion.Logger.LogDebug($"{minion.Name} - Checking: CartId={cart.Id}");

                    var arg = new CartsCleanupArgument(cart, maintenancePolicy);
                    await CommerceCommander.Pipeline <ICartsCleanupPipeline>().Run(arg, minion.MinionContext.GetPipelineContext());
                }
            }

            return(new MinionRunResultsModel());
        }
示例#17
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.Action.Equals("VatTaxDashboard-AddDashboardEntity", StringComparison.OrdinalIgnoreCase))
            {
                return(entityView);
            }

            if (entityView != null && entityView.Action.Equals("VatTaxDashboard-AddDashboardEntity", StringComparison.OrdinalIgnoreCase))
            {
                var taxTag      = entityView.Properties.First(p => p.Name == "TaxTag").Value ?? "";
                var countryCode = entityView.Properties.First(p => p.Name == "CountryCode").Value ?? "";
                var taxPct      = Convert.ToDecimal(entityView.Properties.First(p => p.Name == "TaxPct").Value ?? "0");

                using (var sampleDashboardEntity = new VatTaxEntity())
                {
                    try
                    {
                        sampleDashboardEntity.Id          = CommerceEntity.IdPrefix <VatTaxEntity>() + Guid.NewGuid().ToString("N");
                        sampleDashboardEntity.Name        = string.Empty;
                        sampleDashboardEntity.TaxTag      = taxTag;
                        sampleDashboardEntity.CountryCode = countryCode;
                        sampleDashboardEntity.TaxPct      = taxPct;
                        sampleDashboardEntity.GetComponent <ListMembershipsComponent>().Memberships.Add(CommerceEntity.ListName <VatTaxEntity>());
                        await _commerceCommander.Pipeline <IPersistEntityPipeline>().Run(new PersistEntityArgument(sampleDashboardEntity), context).ConfigureAwait(false);
                    }
                    catch (ArgumentNullException ex)
                    {
                        context.Logger.LogError($"Catalog.DoActionAddDashboardEntity.Exception: Message={ex.Message}");
                    }
                }
            }
            else
            {
                System.Diagnostics.Debug.Write($"Error creating the View is", entityView.Name);
            }

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

            foreach (var cartLine in cart.Lines)
            {
                if (cartLine.HasComponent <FreeGiftAutoRemoveComponent>())
                {
                    var freeGiftAutoRemoveComponent = cartLine.GetComponent <FreeGiftAutoRemoveComponent>();
                    var adjustments = cartLine.Adjustments.Where(x =>
                                                                 x.AwardingBlock.Equals(freeGiftAutoRemoveComponent.PromotionId));
                    if (adjustments.Any())
                    {
                        await _commander.Pipeline <IRemoveCartLinePipeline>().Run(new CartLineArgument(cart, cartLine), context);
                    }
                }
            }

            return(cart);
        }
示例#19
0
        /// <summary>
        /// Find and return an existing Category or create a new one
        /// </summary>
        /// <param name="entityData"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private async Task <Category> GetOrCreateCategory(CatalogEntityDataModel entityData, CommercePipelineExecutionContext context)
        {
            Category category = await _commerceCommander.Command <FindEntityCommand>().Process(context.CommerceContext, typeof(Category), entityData.CommerceEntityId) as Category;

            if (category == null)
            {
                category = await _commerceCommander.Command <CreateCategoryCommand>().Process(context.CommerceContext,
                                                                                              entityData.CatalogName,
                                                                                              entityData.EntityName,
                                                                                              entityData.EntityFields.ContainsKey("DisplayName") ? entityData.EntityFields["DisplayName"] : entityData.EntityName,
                                                                                              entityData.EntityFields.ContainsKey("Description") ? entityData.EntityFields["Description"] : string.Empty);
            }
            else
            {
                category.DisplayName = entityData.EntityFields.ContainsKey("DisplayName") ? entityData.EntityFields["DisplayName"] : entityData.EntityName;
                category.Description = entityData.EntityFields.ContainsKey("Description") ? entityData.EntityFields["Description"] : string.Empty;

                var persistResult = await _commerceCommander.Pipeline <IPersistEntityPipeline>().Run(new PersistEntityArgument(category), context);
            }

            return(await _commerceCommander.Command <FindEntityCommand>().Process(context.CommerceContext, typeof(Category), category.Id) as Category);
        }
        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));
        }
        private async Task SetCommerceEntityComponents(CommerceEntity commerceEntity, ImportEntityArgument importEntityArgument, CommercePipelineExecutionContext context)
        {
            if (importEntityArgument.SourceEntityDetail.Components != null && importEntityArgument.SourceEntityDetail.Components.Any())
            {
                foreach (var componentName in importEntityArgument.SourceEntityDetail.Components)
                {
                    var mapper = await _commerceCommander.Pipeline <IResolveComponentMapperPipeline>()
                                 .Run(new ResolveComponentMapperArgument(importEntityArgument, commerceEntity, componentName), context)
                                 .ConfigureAwait(false);

                    if (mapper == null)
                    {
                        await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Warning, "EntityComponentMapperMissing", null, $"Entity component mapper instance for entityType={importEntityArgument.SourceEntityDetail.EntityType} and component={componentName} not resolved.");
                    }
                    else
                    {
                        var component = mapper.Execute();
                        component.SetComponentMetadataPolicy(componentName);
                    }
                }
            }
        }
        /// <summary>
        /// Runs the specified argument.
        /// </summary>
        /// <param name="entityView">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="EntityView"/>.</returns>
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            var views = context.GetPolicy <Policies.KnownInventoryViewsPolicy>();
            var knownActionsPolicy = context.GetPolicy <Policies.KnownInventoryActionsPolicy>();
            var enablementPolicy   = context.GetPolicy <Policies.InventoryFeatureEnablementPolicy>();

            if (!enablementPolicy.InventoryFromProductView ||
                string.IsNullOrEmpty(entityView?.Action) ||
                (string.IsNullOrEmpty(entityView.ItemId) && string.IsNullOrEmpty(entityView.EntityId)) ||
                string.IsNullOrEmpty(entityView.Name) ||
                !entityView.Name.Equals(views.SelectInventorySet, StringComparison.OrdinalIgnoreCase) ||
                !entityView.Action.Equals(knownActionsPolicy.SelectInventorySet, StringComparison.OrdinalIgnoreCase))
            {
                return(entityView);
            }

            var sellableItemId =
                entityView.EntityId.StartsWith(CommerceEntity.IdPrefix <SellableItem>(), StringComparison.OrdinalIgnoreCase)
                    ? entityView.EntityId
                    : entityView.ItemId;

            var inventorySetProperty = entityView.GetProperty("Inventory Set");

            inventorySetProperty.UiType     = string.Empty;
            inventorySetProperty.IsReadOnly = true;

            var inventorySetId = inventorySetProperty.Value;

            // Reset the entity view properties for the inventory set context
            entityView.EntityId      = inventorySetId.ToEntityId <InventorySet>();
            entityView.ItemId        = sellableItemId;
            entityView.EntityVersion = 1;
            entityView.SetPropertyValue("Version", 1);
            var version = entityView.GetProperty("Version");

            version.IsHidden = true;

            var variationId = string.Empty;

            if (sellableItemId.Contains("|"))
            {
                var parts = sellableItemId.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length == 2)
                {
                    sellableItemId = parts[0];
                    variationId    = parts[1];
                }
            }

            var sellableItem =
                await Commander.Pipeline <FindEntityPipeline>().Run(
                    new FindEntityArgument(typeof(SellableItem), sellableItemId),
                    context)
                .ConfigureAwait(false) as SellableItem;

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

            var inventoryInformation =
                await Commander.Command <GetInventoryInformationCommand>().Process(
                    context.CommerceContext,
                    inventorySetId,
                    sellableItem?.Id,
                    variationId,
                    true).ConfigureAwait(false);

            await AddViewProperties(entityView, sellableItem, variationId, inventoryInformation, context).ConfigureAwait(false);

            context.CommerceContext.AddModel(
                new MultiStepActionModel(
                    inventoryInformation != null
                        ? knownActionsPolicy.EditSellableItemInventory
                        : knownActionsPolicy.AssociateSellableItemToInventorySet));

            return(entityView);
        }
示例#23
0
 protected virtual async Task <bool> DoesEntityExists(string entityId)
 {
     return(await CommerceCommander.Pipeline <IDoesEntityExistPipeline>()
            .Run(new FindEntityArgument(typeof(T), entityId), Context)
            .ConfigureAwait(false));
 }
示例#24
0
        public override async Task <Cart> RunAsync(Cart arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The cart can not be null");
            //Only calculate tax if there is a shipping address provided
            if (!arg.HasComponent <FulfillmentComponent>())
            {
                return(arg);
            }
            //Don't calculate if there is a split shipment
            if (arg.GetComponent <FulfillmentComponent>() is SplitFulfillmentComponent)
            {
                return(arg);
            }

            if (!arg.Lines.Any())
            {
                //if there are no cart lines, remove the tax calculation from the cart
                arg.Adjustments.Where(a =>
                {
                    if (!string.IsNullOrEmpty(a.Name) && a.Name.Equals("TaxFee", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(a.AdjustmentType))
                    {
                        return(a.AdjustmentType.Equals(context.GetPolicy <KnownCartAdjustmentTypesPolicy>().Tax, StringComparison.OrdinalIgnoreCase));
                    }
                    return(false);
                }).ToList().ForEach(a => arg.Adjustments.Remove(a));
                return(arg);
            }

            var taxJarPolicy = context.GetPolicy <TaxFrameworkPolicy>();
            var fulfillment  = arg.GetComponent <PhysicalFulfillmentComponent>();

            if (fulfillment != null && fulfillment.ShippingParty != null)
            {
                var address = fulfillment.ShippingParty;
                var lines   = arg.Lines;

                try
                {
                    var model = new TaxableCartModel()
                    {
                        LineItems      = new List <TaxableLineItem>(),
                        NexusAddresses = new List <NexusAddress>(),
                        ToStreet       = address.Address1,
                        ToCity         = address.City,
                        ToState        = address.StateCode,
                        ToCountry      = address.CountryCode,
                        ToZip          = address.ZipPostalCode
                    };

                    //Cart level discounts are marked as non-taxable, for more accurate tax calculations we should total cart discounts (excluding discounts to shipping) to split amoungst cart lines
                    var adjustments = arg.Adjustments
                                      .Where(p => p.IsTaxable || p.AdjustmentType ==
                                             context.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount&& !taxJarPolicy.FulfillmentDiscountActions.Contains(p.AwardingBlock))
                                      .Aggregate(decimal.Zero, (current, adjustment) => current + adjustment.Adjustment.Amount);

                    //Spread cart level discounts across each item
                    var cartLineAdjustment = adjustments / lines.Count;
                    var subTotal           = 0M;
                    foreach (var line in lines)
                    {
                        var lineTotal       = line.Totals.SubTotal.Amount;
                        var lineAdjustments = line.Adjustments.Where(p => p.IsTaxable).Aggregate(Decimal.Zero,
                                                                                                 (current, adjustment) => current + adjustment.Adjustment.Amount);

                        subTotal += (lineTotal + lineAdjustments + cartLineAdjustment);

                        var lineItem = new TaxableLineItem()
                        {
                            Id       = line.Id,
                            Quantity = line.Quantity,
                            Price    = line.Totals.SubTotal.Amount,
                            Discount = (lineAdjustments + cartLineAdjustment) * -1,
                        };

                        model.LineItems.Add(lineItem);
                    }

                    //Shipping is considered taxable in some states. Let the tax provider figure out what should be considered taxable
                    var shipping = arg.Adjustments
                                   .Where(p => p.AdjustmentType == context.GetPolicy <KnownCartAdjustmentTypesPolicy>().Fulfillment)
                                   .Aggregate(Decimal.Zero, (current, adjustment) => current + adjustment.Adjustment.Amount);

                    //Subtract discounts that alter shipping
                    var shippingDiscounts = arg.Adjustments.Where(x => x.AdjustmentType == context.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount&& taxJarPolicy.FulfillmentDiscountActions.Contains(x.AwardingBlock))
                                            .Aggregate(Decimal.Zero, (current, adjustment) => current + adjustment.Adjustment.Amount);

                    model.Shipping = (shipping + shippingDiscounts);

                    var nexusAddresses = await _commerceCommander.Pipeline <IPopulateNexusAddressPipeline>().RunAsync(arg, context);

                    model.NexusAddresses = nexusAddresses.ToList();

                    model.Amount   = subTotal - shipping;
                    model.Shipping = shipping;

                    if (model.Amount > 0)
                    {
                        context.Logger.Log(LogLevel.Information,
                                           "Total: " + model.Amount + " shipping: " + model.Shipping +
                                           " Line item total: " + subTotal);

                        var result = await _commerceCommander.Pipeline <ICallExternalServiceToCalculateTaxPipeline>()
                                     .RunAsync(model, context);

                        if (result != null)
                        {
                            context.Logger.Log(LogLevel.Information,
                                               "Total: " + result.TaxableAmount + " shipping: " + result.IsShippingTaxable +
                                               " Tax Payable: " + result.AmountToCollect + " Has Nexus: " + result.HasNexus);

                            var awardedAdjustment = new CartLevelAwardedAdjustment();
                            awardedAdjustment.Name           = "TaxFee";
                            awardedAdjustment.DisplayName    = "TaxFee";
                            awardedAdjustment.Adjustment     = new Money(result.AmountToCollect);
                            awardedAdjustment.AdjustmentType = context.GetPolicy <KnownCartAdjustmentTypesPolicy>().Tax;
                            awardedAdjustment.AwardingBlock  = (Name);
                            awardedAdjustment.IsTaxable      = (false);
                            arg.Adjustments.Add(awardedAdjustment);

                            var allAdjustments = arg.Adjustments
                                                 .Where(p => p.AdjustmentType ==
                                                        context.GetPolicy <KnownCartAdjustmentTypesPolicy>().Fulfillment);
                            foreach (var adjustment in allAdjustments)
                            {
                                adjustment.IsTaxable = result.IsShippingTaxable;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    context.Logger.LogCritical(ex, "Error calculating tax with Framework provider");
                }
            }

            return(arg);
        }
示例#25
0
        private async Task CreateExampleBundles(CommercePipelineExecutionContext context)
        {
            // First bundle
            var bundle1 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle1), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-Connected home",
                                      bundle1.Id)).ConfigureAwait(false);

            // Second bundle
            var bundle2 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle2), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-Fitness Activity Trackers",
                                      bundle2.Id)).ConfigureAwait(false);

            // Third bundle
            var bundle3 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle3), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-Appliances",
                                      bundle3.Id)).ConfigureAwait(false);

            // Fourth bundle with digital items
            var bundle4 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle4), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                                      bundle4.Id)).ConfigureAwait(false);

            // Preorderable bundle
            var bundle5 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle5), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-Phones",
                                      bundle5.Id)).ConfigureAwait(false);

            // Backorderable bundle
            var bundle6 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle6), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-Phones",
                                      bundle6.Id)).ConfigureAwait(false);

            // Backorderable bundle
            var bundle7 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle7), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-Audio",
                                      bundle7.Id)).ConfigureAwait(false);

            // Eigth bundle with a gift card only
            var bundle8 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle8), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                                      bundle8.Id)).ConfigureAwait(false);

            // Warranty bundle
            var bundle9 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle9), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                                      bundle9.Id)).ConfigureAwait(false);

            // Service bundle
            var bundle10 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle10), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                                      bundle10.Id)).ConfigureAwait(false);

            // Subscription bundle
            var bundle11 =
                await CreateBundle(
                    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 _commerceCommander.Pipeline <IPersistEntityPipeline>()
            .Run(new PersistEntityArgument(bundle11), context).ConfigureAwait(false);

            // Associate bundle to parent category
            await AssociateEntity(context.CommerceContext, new CatalogReferenceArgument(
                                      "Entity-Catalog-Habitat_Master",
                                      "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping",
                                      bundle11.Id)).ConfigureAwait(false);
        }
示例#26
0
        /// <summary>
        /// Runs the specified argument.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="Order"/></returns>
        public override async Task <Order> Run(Order arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{Name}: The order cannot be null.");

            if (!arg.HasComponent <FederatedPaymentComponent>() ||
                !arg.Status.Equals(context.GetPolicy <KnownOrderStatusPolicy>().Released, StringComparison.OrdinalIgnoreCase))
            {
                return(arg);
            }

            var knownOrderStatuses = context.GetPolicy <KnownOrderStatusPolicy>();

            var payment = arg.GetComponent <FederatedPaymentComponent>();
            var salesActivityReference = arg.SalesActivity.FirstOrDefault(sa => sa.Name.Equals(payment.Id, StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrEmpty(payment.TransactionId) || salesActivityReference == null)
            {
                payment.TransactionStatus = knownOrderStatuses.Problem;
                arg.Status = knownOrderStatuses.Problem;

                await context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    "InvalidOrMissingPropertyValue",
                    new object[]
                {
                    "TransactionId"
                },
                    "Invalid or missing value for property 'TransactionId'.")
                .ConfigureAwait(false);

                return(arg);
            }

            var salesActivity = await _commander
                                .GetEntity <SalesActivity>(context.CommerceContext, salesActivityReference.EntityTarget, salesActivityReference.EntityTargetUniqueId)
                                .ConfigureAwait(false);

            if (salesActivity == null)
            {
                payment.TransactionStatus = knownOrderStatuses.Problem;
                arg.Status = knownOrderStatuses.Problem;

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

                return(arg);
            }

            var knowSalesActivitiesStatus = context.GetPolicy <KnownSalesActivityStatusesPolicy>();

            if (payment.TransactionStatus.Equals(knownOrderStatuses.Problem, StringComparison.OrdinalIgnoreCase))
            {
                salesActivity.PaymentStatus = knowSalesActivitiesStatus.Problem;
            }

            await SettleSalesActivity(salesActivity, context).ConfigureAwait(false);

            payment.TransactionStatus = salesActivity.GetComponent <FederatedPaymentComponent>().TransactionStatus;
            if (salesActivity.PaymentStatus.Equals(knowSalesActivitiesStatus.Problem, StringComparison.OrdinalIgnoreCase))
            {
                arg.Status = knownOrderStatuses.Problem;
            }

            var knownSalesActivityLists = context.GetPolicy <KnownOrderListsPolicy>();
            var listToAssignTo          = !salesActivity.PaymentStatus.Equals(knowSalesActivitiesStatus.Settled, StringComparison.OrdinalIgnoreCase)
                ? knownSalesActivityLists.ProblemSalesActivities
                : knownSalesActivityLists.SettledSalesActivities;
            var argument = new MoveEntitiesInListsArgument(knownSalesActivityLists.SettleSalesActivities, listToAssignTo, new List <string>
            {
                salesActivity.Id
            });
            await _commander.Pipeline <IMoveEntitiesInListsPipeline>().Run(argument, context.CommerceContext.PipelineContextOptions).ConfigureAwait(false);

            await _commander.PersistEntity(context.CommerceContext, salesActivity).ConfigureAwait(false);

            return(arg);
        }
示例#27
0
 public ImportPriceBooksPrepareBlock(
     CommerceCommander commander) : base(commander)
 {
     this.RemoveAllInventorySetsPipeline = commander.Pipeline <IRemoveAllPriceBooksPipeline>();
 }
        public override async Task <ImportEntityArgument> Run(ImportEntityArgument arg, CommercePipelineExecutionContext context)
        {
            if (arg.ImportHandler.HasRelationships())
            {
                var relationships = arg.ImportHandler.GetRelationships();

                var commerceEntity = arg.ImportHandler.GetCommerceEntity();

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

                        if (relationShipMapper == null)
                        {
                            continue;
                        }

                        if (!string.IsNullOrEmpty(relationShipMapper.Name))
                        {
                            IList <string> targetIds = new List <string>();
                            if (relationshipDetail.Ids != null && relationshipDetail.Ids.Any())
                            {
                                targetIds = await relationShipMapper.GetEntityIds(relationshipDetail.Ids)
                                            .ConfigureAwait(false);
                            }

                            var listName = $"{relationShipMapper.Name}-{commerceEntity.FriendlyId}";

                            if (commerceEntity.EntityVersion > 1)
                            {
                                listName = $"{listName}-{commerceEntity.EntityVersion}";
                            }

                            IDictionary <string, IList <string> > dictionary = await _commerceCommander.Pipeline <IGetListsEntityIdsPipeline>().Run(new GetListsEntityIdsArgument(listName), context).ConfigureAwait(false);

                            var deleteIdsFromList = new List <string>();

                            if (dictionary != null && dictionary.Values.Any())
                            {
                                var firstList = dictionary.ElementAt(0);
                                foreach (var entityId in firstList.Value)
                                {
                                    if (targetIds != null &&
                                        targetIds.Contains(entityId))
                                    {
                                        targetIds.Remove(entityId);
                                    }
                                    else
                                    {
                                        deleteIdsFromList.Add(entityId);
                                    }
                                }
                            }

                            if (targetIds != null &&
                                targetIds.Any())
                            {
                                var targetName = targetIds.JoinIds();

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

                            if (deleteIdsFromList.Any())
                            {
                                var targetName = deleteIdsFromList.JoinIds();

                                await _commerceCommander.Command <DeleteRelationshipCommand>().Process(
                                    context.CommerceContext,
                                    commerceEntity.Id,
                                    targetName, relationShipMapper.Name);
                            }
                        }
                    }
                }
            }

            return(await Task.FromResult(arg));
        }
示例#29
0
        public override async Task <RelationshipArgument> Run(RelationshipArgument arg,
                                                              CommercePipelineExecutionContext context)
        {
            if (!(new[]
            {
                "CatalogToCategory",
                "CatalogToSellableItem",
                "CategoryToCategory",
                "CategoryToSellableItem"
            }).Contains(arg.RelationshipType, StringComparer.OrdinalIgnoreCase))
            {
                return(arg);
            }
            CatalogItemBase source = arg.SourceEntity as CatalogItemBase;

            if (source == null)
            {
                source = await _commerceCommander.Pipeline <IFindEntityPipeline>()
                         .Run(new FindEntityArgument(typeof(CatalogItemBase), arg.SourceName), context)
                         .ConfigureAwait(false) as CatalogItemBase;
            }

            List <Tuple <string, CatalogItemBase> > tupleList = new List <Tuple <string, CatalogItemBase> >();

            if (arg.TargetName.Contains("|"))
            {
                string targetName = arg.TargetName;
                char[] chArray    = { '|' };
                foreach (string str in targetName.Split(chArray))
                {
                    tupleList.Add(new Tuple <string, CatalogItemBase>(str, null));
                }
            }
            else
            {
                tupleList.Add(new Tuple <string, CatalogItemBase>(arg.TargetName, arg.TargetEntity as CatalogItemBase));
            }

            foreach (Tuple <string, CatalogItemBase> tuple in tupleList)
            {
                CatalogItemBase catalogItemBase = tuple.Item2 ?? await _commerceCommander.Pipeline <IFindEntityPipeline>()
                                                  .Run(new FindEntityArgument(typeof(CatalogItemBase), tuple.Item1), context).ConfigureAwait(false) as CatalogItemBase;

                if (source != null && catalogItemBase != null)
                {
                    bool changed = false;
                    var  parentEntitiesComponent = catalogItemBase.GetComponent <ParentEntitiesComponent>();

                    if (arg.Mode.HasValue)
                    {
                        if (arg.Mode.Value == RelationshipMode.Create)
                        {
                            if (!parentEntitiesComponent.EntityIds.Contains(source.Id))
                            {
                                parentEntitiesComponent.EntityIds.Add(source.Id);
                                changed = true;
                            }
                        }
                        else if (arg.Mode.Value == RelationshipMode.Delete)
                        {
                            if (parentEntitiesComponent.EntityIds.Contains(source.Id))
                            {
                                parentEntitiesComponent.EntityIds.Remove(source.Id);
                                changed = true;
                            }
                        }
                    }

                    if (changed)
                    {
                        await _commerceCommander
                        .Pipeline <IPersistEntityPipeline>().Run(new PersistEntityArgument(catalogItemBase), context)
                        .ConfigureAwait(false);
                    }
                }
            }

            return(arg);
        }
        private async Task ImportVariants(CommerceEntity commerceEntity, ImportEntityArgument importEntityArgument, CommercePipelineExecutionContext context)
        {
            var orphanVariants = new List <ItemVariationComponent>();
            ItemVariationsComponent itemVariationsComponent = null;
            var sourceEntityHasVariants = importEntityArgument.ImportHandler.HasVariants();

            if (!sourceEntityHasVariants &&
                commerceEntity.HasComponent <ItemVariationsComponent>())
            {
                itemVariationsComponent = commerceEntity.GetComponent <ItemVariationsComponent>();
                if (itemVariationsComponent.Variations != null &&
                    itemVariationsComponent.Variations.Any())
                {
                    orphanVariants = itemVariationsComponent.Variations;
                }
            }

            if (sourceEntityHasVariants)
            {
                itemVariationsComponent =
                    commerceEntity.GetComponent <ItemVariationsComponent>();

                var variants = importEntityArgument.ImportHandler.GetVariants();

                foreach (var variant in variants)
                {
                    var itemVariantMapper = await _commerceCommander.Pipeline <IResolveComponentMapperPipeline>()
                                            .Run(
                        new ResolveComponentMapperArgument(importEntityArgument, commerceEntity,
                                                           itemVariationsComponent, variant, string.Empty), context).ConfigureAwait(false);

                    if (itemVariantMapper == null)
                    {
                        await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Warning, "ItemVariationMapperMissing", null, $"Item variation mapper instance for variantId={variant.Id} not resolved.");

                        continue;
                    }

                    var       action = itemVariantMapper.GetComponentAction();
                    Component itemVariationComponent = itemVariantMapper.Execute(action);

                    if (action != ComponentAction.Remove &&
                        importEntityArgument.SourceEntityDetail.VariantComponents != null &&
                        importEntityArgument.SourceEntityDetail.VariantComponents.Any())
                    {
                        foreach (var variantComponentName in importEntityArgument.SourceEntityDetail.VariantComponents)
                        {
                            var itemVariantChildComponentMapper = await _commerceCommander
                                                                  .Pipeline <IResolveComponentMapperPipeline>().Run(new
                                                                                                                    ResolveComponentMapperArgument(importEntityArgument, commerceEntity,
                                                                                                                                                   itemVariationComponent, variant, variantComponentName), context)
                                                                  .ConfigureAwait(false);

                            if (itemVariantChildComponentMapper != null)
                            {
                                var childComponent = itemVariantChildComponentMapper.Execute();
                                childComponent.SetComponentMetadataPolicy(variantComponentName);
                            }
                            else
                            {
                                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Warning, "ComponentChildComponentMapperMissing", null, $"Component's child component mapper instance for entityType={importEntityArgument.SourceEntityDetail.EntityType} and key={variantComponentName} not resolved.");
                            }
                        }
                    }
                }

                orphanVariants = (from n in itemVariationsComponent.Variations
                                  join o in variants on n.Id equals o.Id into p
                                  where !p.Any()
                                  select n).ToList();
            }

            if (itemVariationsComponent != null &&
                orphanVariants != null &&
                orphanVariants.Any())
            {
                foreach (var orphanVariant in orphanVariants)
                {
                    if (importEntityArgument.CatalogImportPolicy.DeleteOrphanVariant)
                    {
                        itemVariationsComponent.ChildComponents.Remove(orphanVariant);
                    }
                    else
                    {
                        orphanVariant.Disabled = true;
                    }
                }
            }
        }