/// <summary>
        /// Runs the specified argument.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override async Task <bool> Run(MigrateListArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name}: the argument cannot be null.");
            context.Logger.LogInformation($"{this.Name} - Migrating the list:{arg.ListName}");

            var count = await this._getListCountCommand.Process(context.CommerceContext, arg.ListName);

            if (count > 0)
            {
                context.Logger.LogInformation($"{this.Name} - List {arg.ListName} was already migrated. Skipping it.");
                return(true);
            }

            var migrateEnvironmentArgument = context.CommerceContext?.GetObjects <MigrateEnvironmentArgument>()?.FirstOrDefault();

            context.CommerceContext.AddUniqueObjectByType(arg);
            var newEnvironment = context.CommerceContext.Environment;
            var result         = true;

            try
            {
                context.CommerceContext.Environment = migrateEnvironmentArgument?.SourceEnvironment;
                var entitiesArgument = await _findEntitiesInListPipeline.Run(
                    new FindEntitiesInListArgument(
                        typeof(CommerceEntity),
                        arg.ListName,
                        0,
                        arg.MaxCount)
                {
                    LoadEntities = false
                },
                    context);

                context.CommerceContext.Environment = newEnvironment;
                foreach (var id in entitiesArgument.IdList)
                {
                    var migratedEntity = await this._migrateEntityMetadataPipeline.Run(new FindEntityArgument(typeof(CommerceEntity), id), context);

                    if (migratedEntity == null)
                    {
                        context.Logger.LogInformation($"{this.Name} - Entity {id} was not migrated.");
                        result = false;
                    }
                }
            }
            catch (Exception ex)
            {
                await context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    this.Name,
                    new object[] { ex },
                    $"{this.Name}.Exception: {ex.Message}");

                context.CommerceContext.Environment = newEnvironment;
                context.CommerceContext.LogException($"{this.Name}. Exception when migrating the list {arg.ListName}", ex);
                return(false);
            }

            return(result);
        }
Пример #2
0
        public override async Task <Cart> Run(Cart arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires <Cart>(arg).IsNotNull <Cart>(string.Format("{0}: the cart can not be null.", (object)this.Name));
            if (arg.HasComponent <TemporaryCartComponent>())
            {
                return(arg);
            }

            AddToCartKitsBlock addKitsBlock = this;

            context.CommerceContext.AddObject((object)arg);
            Cart cart = arg;

            FindEntityArgument getSavedCartArg = new FindEntityArgument(typeof(Cart), arg.Id, false);
            Cart savedCart = await this._findEntityPipeline.Run(getSavedCartArg, (CommercePipelineExecutionContext)context).ConfigureAwait(false) as Cart;

            CartLineComponent existingLine;

            if (savedCart == null)
            {
                existingLine = arg.Lines.FirstOrDefault <CartLineComponent>();
            }
            else
            {
                var savedCartLines   = savedCart.Lines;
                var currentCartLines = cart.Lines;
                var addedCartLine    = cart.Lines.Where(l => savedCartLines.Where(sc => sc.Id == l.Id).FirstOrDefault() == null).FirstOrDefault();
                existingLine = addedCartLine;
            }
            if (existingLine != null)
            {
                //var cartLineProductComponent = existingLine.GetComponent<CartProductComponent>();
                //bool hasTag = cartLineProductComponent.Tags.Any<Tag>((Func<Tag, bool>)(t => t.Name.Equals("kit", StringComparison.OrdinalIgnoreCase)));

                FindEntityArgument getProductArg  = new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-" + (existingLine.ItemId.Split('|').Count() > 1 ? existingLine.ItemId.Split('|')[1] : existingLine.ItemId), false);
                SellableItem       carLineProduct = await this._findEntityPipeline.Run(getProductArg, (CommercePipelineExecutionContext)context).ConfigureAwait(false) as SellableItem;

                bool hasTag = carLineProduct.Tags.Any <Tag>((Func <Tag, bool>)(t => t.Name.Equals("kit", StringComparison.OrdinalIgnoreCase)));

                if (hasTag)
                {
                    string listId = String.Format("relatedproduct-{0}", existingLine.ItemId.Split('|').Count() > 1 ? existingLine.ItemId.Split('|')[1] : existingLine.ItemId);

                    var relatedProducts = await _findEntitiesInListPipeline.Run(
                        new FindEntitiesInListArgument(typeof(CommerceEntity), listId, 0, 10)
                    {
                        LoadEntities = true
                    },
                        context);

                    foreach (var relProd in relatedProducts.List.Items)
                    {
                        existingLine.Comments += relProd.Id + ',' + relProd.DisplayName + '|';
                    }
                }
            }

            return(cart);
        }
Пример #3
0
        public override async Task <CartLineArgument> Run(CartLineArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires <CartLineArgument>(arg).IsNotNull <CartLineArgument>("The argument can not be null");
            Condition.Requires <Cart>(arg.Cart).IsNotNull <Cart>("The cart can not be null");
            Condition.Requires <CartLineComponent>(arg.Line).IsNotNull <CartLineComponent>("The lines can not be null");
            Cart cart = arg.Cart;

            List <CartLineComponent> lines        = cart.Lines.ToList <CartLineComponent>();
            CartLineComponent        existingLine = lines.FirstOrDefault <CartLineComponent>((Func <CartLineComponent, bool>)(l => l.Id.Equals(arg.Line.Id, StringComparison.OrdinalIgnoreCase)));

            if (existingLine != null)
            {
                FindEntityArgument getProductArg  = new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-" + (existingLine.ItemId.Split('|').Count() > 1 ? existingLine.ItemId.Split('|')[1] : existingLine.ItemId), false);
                SellableItem       carLineProduct = await this._findEntityPipeline.Run(getProductArg, (CommercePipelineExecutionContext)context).ConfigureAwait(false) as SellableItem;

                bool hasTag = carLineProduct.Tags.Any <Tag>((Func <Tag, bool>)(t => t.Name.Equals("bundle", StringComparison.OrdinalIgnoreCase)));
                if (hasTag)
                {
                    string listId          = String.Format("relatedproduct-{0}", existingLine.ItemId.Split('|').Count() > 1 ? existingLine.ItemId.Split('|')[1] : existingLine.ItemId);
                    var    relatedProducts = await _findEntitiesInListPipeline.Run(
                        new FindEntitiesInListArgument(typeof(CommerceEntity), listId, 0, 10)
                    {
                        LoadEntities = true
                    },
                        context);

                    foreach (var relProd in relatedProducts.List.Items)
                    {
                        if (cart.Lines.Any(l => l.ItemId.Contains(relProd.FriendlyId)))
                        {
                            var relatedProductCartLine = cart.Lines.FirstOrDefault <CartLineComponent>(l => l.ItemId.Contains(relProd.FriendlyId));
                            if (relatedProductCartLine != null)
                            {
                                cart.Lines.Remove(relatedProductCartLine);
                            }
                        }
                    }
                }
            }
            return(arg);
        }
        public override async Task <Customer> Run(Customer customer, CommercePipelineExecutionContext context)
        {
            string listName = string.Format("Orders-ByCustomer-{0}", (object)customer.Id);
            FindEntitiesInListArgument result = await _findEntitiesInListPipeline.Run(new FindEntitiesInListArgument(typeof(Order), listName, 0, int.MaxValue), context);

            int customerOrderPoints = 0;

            if (result != null && result.List != null && result.List.Items.Any())
            {
                foreach (var entity in result.List.Items)
                {
                    var order = (Order)entity;
                    if (order != null)
                    {
                        customerOrderPoints += order.HasComponent <LoyaltyComponent>() ? order.GetComponent <LoyaltyComponent>().PointsEarned : 0;
                    }
                }
                var loyaltyComponent = customer.GetComponent <LoyaltyComponent>();
                loyaltyComponent.PointsEarned = customerOrderPoints;

                var persistEntityArgument = await _persistEntityPipeline.Run(new PersistEntityArgument(customer), context);
            }
            return(customer);
        }
Пример #5
0
 protected virtual async Task <IEnumerable <SellableItem> > GetListItems(string listName, int take, CommercePipelineExecutionContext context)
 {
     return((await _findEntitiesInListPipeline.Run(new FindEntitiesInListArgument(typeof(SellableItem), listName, 0, take), context).ConfigureAwait(false)).List.Items.OfType <SellableItem>());
 }
Пример #6
0
        public override async Task <bool> Run(SellableItemInventorySetsArgument argument, CommercePipelineExecutionContext context)
        {
            AssociateStoreInventoryToSellablteItemBlock associateStoreInventoryToSellablteItemBlock = this;

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

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

            CommercePipelineExecutionContext executionContext;

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

            SellableItem sellableItem = entity as SellableItem;

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

            ItemVariationComponent sellableItemVariation = null;

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

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

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

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

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

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

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

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

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

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

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

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

                inventoryAssociations.Add(inventoryAssociation);
            }

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

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

            return(true);
        }
Пример #7
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull(string.Format("{0}: The argument cannot be null", Name));
            EntityViewArgument entityViewArgument = context.CommerceContext.GetObject <EntityViewArgument>();

            if (string.IsNullOrEmpty(entityViewArgument != null ? entityViewArgument.ViewName : (string)null) ||
                !entityViewArgument.ViewName.Equals(context.GetPolicy <KnownCouponViewsPolicy>().PublicCoupons,
                                                    StringComparison.OrdinalIgnoreCase) && !entityViewArgument.ViewName.Equals(
                    context.GetPolicy <KnownPromotionsViewsPolicy>().Master, StringComparison.OrdinalIgnoreCase))
            {
                return(entityView);
            }

            var forAction = entityViewArgument.ForAction;

            if (!string.IsNullOrEmpty(forAction) && forAction.Equals(context.GetPolicy <KnownCouponActionsPolicy>().AddPublicCoupon,
                                                                     StringComparison.OrdinalIgnoreCase) &&
                entityViewArgument.ViewName.Equals(context.GetPolicy <KnownCouponViewsPolicy>().PublicCoupons, StringComparison.OrdinalIgnoreCase))
            {
                List <ViewProperty> properties = entityView.Properties;

                ViewProperty viewPropertyCode = new ViewProperty
                {
                    Name       = "Code",
                    RawValue   = string.Empty,
                    IsReadOnly = false
                };

                properties.Add(viewPropertyCode);


                ViewProperty viewPropertyUsageCount = new ViewProperty
                {
                    Name       = "Coupon Usage Limit",
                    RawValue   = string.Empty,
                    IsReadOnly = false,
                    IsRequired = false,
                    UiType     = "Dropdown"
                };

                var limitUsageCountList = new List <Selection>();
                limitUsageCountList.Add(new Selection()
                {
                    Name = "-999", IsDefault = true, DisplayName = "No Limit (Default)"
                });
                limitUsageCountList.Add(new Selection()
                {
                    Name = "100", IsDefault = false, DisplayName = "Limit 100 Usages"
                });
                limitUsageCountList.Add(new Selection()
                {
                    Name = "200", IsDefault = false, DisplayName = "Limit 200 Usages"
                });
                limitUsageCountList.Add(new Selection()
                {
                    Name = "300", IsDefault = false, DisplayName = "Limit 300 Usages"
                });
                limitUsageCountList.Add(new Selection()
                {
                    Name = "400", IsDefault = false, DisplayName = "Limit 400 Usages"
                });
                limitUsageCountList.Add(new Selection()
                {
                    Name = "500", IsDefault = false, DisplayName = "Limit 500 Usages"
                });

                viewPropertyUsageCount.Policies = new List <Policy>()
                {
                    new AvailableSelectionsPolicy()
                    {
                        List = limitUsageCountList
                    }
                };

                properties.Add(viewPropertyUsageCount);
                entityView.UiHint = "Flat";
                return(entityView);
            }

            Promotion entity = entityViewArgument.Entity as Promotion;

            if (entity != null)
            {
                EntityView publicCouponsView;

                if (entityViewArgument.ViewName.Equals(context.GetPolicy <KnownPromotionsViewsPolicy>().Master, StringComparison.OrdinalIgnoreCase))
                {
                    EntityView entityView1 = new EntityView();
                    entityView1.EntityId = (entity != null ? entity.Id : (string)null) ?? string.Empty;
                    string publicCoupons = context.GetPolicy <KnownCouponViewsPolicy>().PublicCoupons;
                    entityView1.Name  = publicCoupons;
                    publicCouponsView = entityView1;
                    entityView.ChildViews.Add(publicCouponsView);
                }
                else
                {
                    publicCouponsView = entityView;
                }

                publicCouponsView.UiHint = "Table";
                FindEntitiesInListArgument entitiesInListArgument = await _findEntitiesInListPipeline.Run(new FindEntitiesInListArgument(typeof(Coupon), string.Format(context.GetPolicy <KnownCouponsListsPolicy>().PublicCoupons, (object)entity.FriendlyId), 0, int.MaxValue), context);

                if (entitiesInListArgument != null)
                {
                    CommerceList <CommerceEntity> list = entitiesInListArgument.List;

                    if (list != null)
                    {
                        list.Items.ForEach((c =>
                        {
                            Coupon coupon = c as Coupon;
                            if (coupon == null)
                            {
                                return;
                            }
                            EntityView entityView1 = new EntityView();
                            entityView1.EntityId = entityView.EntityId;
                            entityView1.ItemId = coupon.Id;
                            string couponDetails = context.GetPolicy <KnownCouponViewsPolicy>().CouponDetails;
                            entityView1.Name = couponDetails;

                            EntityView entityViewCoupon = entityView1;
                            List <ViewProperty> properties1 = entityViewCoupon.Properties;
                            ViewProperty viewPropertyItemId = new ViewProperty();
                            viewPropertyItemId.Name = "ItemId";
                            viewPropertyItemId.RawValue = (coupon.Id ?? string.Empty);
                            viewPropertyItemId.IsReadOnly = true;
                            viewPropertyItemId.IsHidden = false;
                            properties1.Add(viewPropertyItemId);

                            List <ViewProperty> properties2 = entityViewCoupon.Properties;
                            ViewProperty viewPropertyCode = new ViewProperty();
                            viewPropertyCode.Name = "Code";
                            viewPropertyCode.RawValue = (coupon.Code ?? string.Empty);
                            viewPropertyCode.IsReadOnly = true;
                            properties2.Add(viewPropertyCode);


                            List <ViewProperty> propertiesUsage = entityViewCoupon.Properties;
                            ViewProperty propertiesUsageProperty = new ViewProperty();
                            propertiesUsageProperty.Name = "Coupon Usage Limit";
                            var limit = ((LimitUsagesPolicy)coupon.Policies.Where(x => x is LimitUsagesPolicy).FirstOrDefault()).LimitCount;
                            var stringLimit = limit.ToString();
                            propertiesUsageProperty.RawValue = stringLimit;
                            propertiesUsageProperty.IsReadOnly = true;
                            propertiesUsage.Add(propertiesUsageProperty);


                            publicCouponsView.ChildViews.Add(entityViewCoupon);
                        }));
                    }
                }
            }

            return(entityView);
        }