Пример #1
0
        public async Task <PriceCard> Process(CommerceContext commerceContext, string bookName, string priceCardName, string priceCardDisplayName, string priceCardDescription)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var createPriceCardCommand = this._commerceCommander.Command <AddPriceCardCommand>();

                PriceCard createdPriceCard = null;

                await this.PerformTransaction(
                    commerceContext,
                    async() =>
                {
                    createdPriceCard = await createPriceCardCommand
                                       .Process(commerceContext, bookName, priceCardName, priceCardDisplayName, priceCardDescription);

                    if (createdPriceCard == null)
                    {
                    }
                    else
                    {
                        var snapshot = new PriceSnapshotComponent(DateTime.UtcNow);

                        createdPriceCard.Snapshots.Add(snapshot);

                        snapshot.Tiers.Add(new PriceTier("USD", 1, 9.99M));
                        await this._commerceCommander.PersistEntity(commerceContext, createdPriceCard);
                    }
                });

                return(createdPriceCard);
            }
        }
        public override async Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Action) ||
                !arg.Action.Equals(context.GetPolicy <KnownCustomPricingActionsPolicy>().RemoveCustomPriceTier, StringComparison.OrdinalIgnoreCase) ||
                context.CommerceContext.GetObjects <PriceCard>().FirstOrDefault(p => p.Id.Equals(arg.EntityId, StringComparison.OrdinalIgnoreCase)) == null)
            {
                return(arg);
            }

            if (string.IsNullOrEmpty(arg.ItemId))
            {
                string str = await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[] { "ItemId" }, "Invalid or missing value for property 'ItemId'.")
                             .ConfigureAwait(false);

                return(arg);
            }

            string[] strArray = arg.ItemId.Split('|');

            if (strArray.Length != 2 || string.IsNullOrEmpty(strArray[0]) || string.IsNullOrEmpty(strArray[1]))
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[] { "ItemId (Correct format is snapshotId|tierId)" }, "Invalid or missing value for property 'ItemId (Correct format is snapshotId|tierId)'.")
                .ConfigureAwait(false);

                return(arg);
            }

            string snapshotId  = strArray[0];
            string priceTierId = strArray[1];

            PriceCard priceCard = await _removeCustomPriceTierCommand.Process(context.CommerceContext, arg.EntityId, snapshotId, priceTierId)
                                  .ConfigureAwait(false);

            return(arg);
        }
Пример #3
0
        public virtual async Task <PriceCard> Process(CommerceContext commerceContext, PriceCard priceCard, PriceSnapshotComponent priceSnapshot, IEnumerable <CustomPriceTier> priceTiers)
        {
            PriceCard result = null;

            using (CommandActivity.Start(commerceContext, this))
            {
                var snapshot = await GetPriceSnapshot(commerceContext, priceCard, priceSnapshot.Id).ConfigureAwait(false);

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

                await PerformTransaction(commerceContext, async() =>
                {
                    foreach (CustomPriceTier priceTier in priceTiers)
                    {
                        result = await _removeCustomPriceTierPipeline.Run(new PriceCardSnapshotCustomTierArgument(priceCard, priceSnapshot, priceTier), commerceContext.GetPipelineContextOptions())
                                 .ConfigureAwait(false);

                        if (commerceContext.HasErrors())
                        {
                            break;
                        }
                    }
                }).ConfigureAwait(false);

                return(result);
            }
        }
        public async Task <PriceCard> Process(CommerceContext commerceContext, string bookId)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                PriceCard createdPriceCard = null;
                var       bookName         = bookId.Replace("Entity-PriceBook-", "");
                var       listName         = string.Format(commerceContext.GetPolicy <KnownPricingListsPolicy>().PriceBookCards, bookName);

                var cardIds = await this._commerceCommander.Command <ListCommander>()
                              .GetListItemIds <PriceCard>(commerceContext, listName, 0, 100);

                while (cardIds.Count > 0)
                {
                    var tasks = new List <Task>();

                    foreach (var card in cardIds)
                    {
                        tasks.Add(Task.Run(() => this._commerceCommander
                                           .DeleteEntity(commerceContext, card)));
                    }

                    await Task.WhenAll(tasks);

                    cardIds = await this._commerceCommander.Command <ListCommander>()
                              .GetListItemIds <PriceCard>(commerceContext, listName, 0, 100);
                }

                return(createdPriceCard);
            }
        }
Пример #5
0
        public virtual async Task <PriceCard> Process(CommerceContext commerceContext,
                                                      string cardFriendlyId,
                                                      string snapshotId,
                                                      string tierCurrency,
                                                      decimal tierQuantity,
                                                      decimal tierPrice,
                                                      string tierMembershipLevel)
        {
            PriceCard result = null;

            using (CommandActivity.Start(commerceContext, this))
            {
                PriceCard priceCard = await GetPriceCard(commerceContext, cardFriendlyId).ConfigureAwait(false);

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

                PriceSnapshotComponent priceSnapshot = await GetPriceSnapshot(commerceContext, priceCard, snapshotId).ConfigureAwait(false);

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

                await PerformTransaction(commerceContext, async() =>
                {
                    CustomPriceTier priceTier = new CustomPriceTier(tierCurrency, tierQuantity, tierPrice, tierMembershipLevel);
                    result = await _addCustomPriceTierPipeline.Run(new PriceCardSnapshotCustomTierArgument(priceCard, priceSnapshot, priceTier), commerceContext.GetPipelineContextOptions()).ConfigureAwait(false);
                }).ConfigureAwait(false);

                return(result);
            }
        }
        protected virtual void CreateTierDetailsViews(PriceCard card, string snapshotId, EntityView pricingView, CommercePipelineExecutionContext context)
        {
            pricingView.UiHint = "Table";

            if (card == null || !card.Snapshots.Any() || string.IsNullOrEmpty(snapshotId))
            {
                return;
            }

            PriceSnapshotComponent snapshotComponent = card.Snapshots.FirstOrDefault(s => s.Id.Equals(snapshotId, StringComparison.OrdinalIgnoreCase));

            if (snapshotComponent == null)
            {
                return;
            }

            var membershipTiersComponent = snapshotComponent.GetComponent <MembershipTiersComponent>();

            if (membershipTiersComponent == null || !membershipTiersComponent.Tiers.Any())
            {
                return;
            }

            List <CustomPriceTier> list = membershipTiersComponent.Tiers.ToList();

            foreach (IGrouping <string, CustomPriceTier> grouping in list.GroupBy(t => t.Currency))
            {
                pricingView.ChildViews.Add(new EntityView
                {
                    EntityId = card.Id,
                    ItemId   = snapshotComponent.Id + "|" + grouping.Key,
                    Name     = context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow
                });
            }
        }
        public override async Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The argument cannot be null");
            EntityViewArgument request = context.CommerceContext.GetObjects <EntityViewArgument>().FirstOrDefault();

            if (string.IsNullOrEmpty(request?.ViewName) ||
                !(request.Entity is PriceCard) ||
                !request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().Master, StringComparison.OrdinalIgnoreCase) &&
                !request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceCardSnapshots, StringComparison.OrdinalIgnoreCase) &&
                (!request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, StringComparison.OrdinalIgnoreCase) &&
                 !request.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing, StringComparison.OrdinalIgnoreCase)) &&
                !request.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow, StringComparison.OrdinalIgnoreCase) ||
                request.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow, StringComparison.OrdinalIgnoreCase) &&
                string.IsNullOrEmpty(request.ItemId))
            {
                return(arg);
            }

            PriceCard card         = (PriceCard)request.Entity;
            bool      isAddAction  = request.ForAction.Equals(context.GetPolicy <KnownCustomPricingActionsPolicy>().SelectMembershipCurrency, StringComparison.OrdinalIgnoreCase);
            bool      isEditAction = request.ForAction.Equals(context.GetPolicy <KnownCustomPricingActionsPolicy>().EditMembershipCurrency, StringComparison.OrdinalIgnoreCase);

            if (request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().Master, StringComparison.OrdinalIgnoreCase) ||
                request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceCardSnapshots, StringComparison.OrdinalIgnoreCase) ||
                (request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, StringComparison.OrdinalIgnoreCase) ||
                 request.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing, StringComparison.OrdinalIgnoreCase)))
            {
                List <EntityView> views = new List <EntityView>();
                FindViews(views, arg, context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow, context.CommerceContext);

                foreach (EntityView view in views)
                {
                    await PopulateRowDetails(view, card, view.ItemId, isAddAction, isEditAction, context)
                    .ConfigureAwait(false);
                }

                return(arg);
            }

            await PopulateRowDetails(arg, card, request.ItemId, isAddAction, isEditAction, context)
            .ConfigureAwait(false);

            string itemId;

            if (!isAddAction)
            {
                itemId = request.ItemId;
            }
            else
            {
                itemId = request.ItemId.Split('|')[0];
            }

            arg.ItemId = itemId;

            return(arg);
        }
Пример #8
0
        public virtual async Task <PriceCard> Process(CommerceContext commerceContext, PriceCard priceCard, PriceSnapshotComponent priceSnapshot, CustomPriceTier priceTier)
        {
            PriceCard result = null;

            using (CommandActivity.Start(commerceContext, this))
            {
                await PerformTransaction(commerceContext, async() =>
                {
                    result = await _removeCustomPriceTierPipeline.Run(new PriceCardSnapshotCustomTierArgument(priceCard, priceSnapshot, priceTier), commerceContext.GetPipelineContextOptions())
                             .ConfigureAwait(false);
                }).ConfigureAwait(false);
            }
            return(result);
        }
        public override Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The argument cannot be null");
            EntityViewArgument entityViewArgument = context.CommerceContext.GetObjects <EntityViewArgument>().FirstOrDefault();

            if (string.IsNullOrEmpty(entityViewArgument?.ViewName) ||
                !(entityViewArgument.Entity is PriceCard) ||
                !entityViewArgument.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().Master, StringComparison.OrdinalIgnoreCase) &&
                !entityViewArgument.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceCardSnapshots, StringComparison.OrdinalIgnoreCase) &&
                (!entityViewArgument.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, StringComparison.OrdinalIgnoreCase) &&
                 !entityViewArgument.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing, StringComparison.OrdinalIgnoreCase)) ||
                (entityViewArgument.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing, StringComparison.OrdinalIgnoreCase) &&
                 string.IsNullOrEmpty(entityViewArgument.ItemId) ||
                 entityViewArgument.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, StringComparison.OrdinalIgnoreCase) &&
                 !string.IsNullOrEmpty(entityViewArgument.ForAction)))
            {
                return(Task.FromResult(arg));
            }

            PriceCard card = (PriceCard)entityViewArgument.Entity;

            if (entityViewArgument.ViewName.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing, StringComparison.OrdinalIgnoreCase))
            {
                CreateTierDetailsViews(card, entityViewArgument.ItemId, arg, context);
                return(Task.FromResult(arg));
            }

            List <EntityView> views = new List <EntityView>();

            FindViews(views, arg, context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, context.CommerceContext);

            views.ForEach(snapshotDetailsView =>
            {
                EntityView pricingView = new EntityView()
                {
                    EntityId = card.Id,
                    ItemId   = snapshotDetailsView.ItemId,
                    Name     = context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing
                };
                snapshotDetailsView.ChildViews.Add(pricingView);
                CreateTierDetailsViews(card, snapshotDetailsView.ItemId, pricingView, context);
            });

            return(Task.FromResult(arg));
        }
        protected override PriceSnapshotComponent FilterPriceSnapshotsByDate(PriceCard priceCard, CommercePipelineExecutionContext context)
        {
            if (priceCard == null || context == null)
            {
                return(null);
            }

            DateTimeOffset         effectiveDate      = context.CommerceContext.CurrentEffectiveDate();
            PriceSnapshotComponent snapshotComponent1 = priceCard.Snapshots.Where(s =>
            {
                var snapshotEndDateComponent = s.GetComponent <SnapshotEndDateComponent>();
                if (s.IsApproved(context.CommerceContext))
                {
                    bool startDateReached  = s.BeginDate.CompareTo(effectiveDate) <= 0;
                    bool endDateNotReached = snapshotEndDateComponent.EndDate != DateTimeOffset.MinValue
                        ? startDateReached && snapshotEndDateComponent.EndDate.CompareTo(effectiveDate) >= 0
                        : true;
                    return(startDateReached && endDateNotReached);
                }
                return(false);
            }).OrderByDescending(s => s.BeginDate).FirstOrDefault();

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

            PriceSnapshotComponent snapshotComponent2 = new PriceSnapshotComponent(snapshotComponent1.BeginDate)
            {
                Id = snapshotComponent1.Id,
                ChildComponents    = snapshotComponent1.ChildComponents,
                SnapshotComponents = snapshotComponent1.SnapshotComponents,
                Tags = snapshotComponent1.Tags
            };
            string currency = context.CommerceContext.CurrentCurrency();

            snapshotComponent2.Tiers = snapshotComponent1
                                       .Tiers
                                       .Where(t => t.Currency.Equals(currency, StringComparison.OrdinalIgnoreCase))
                                       .ToList();
            return(snapshotComponent2);
        }
Пример #11
0
        public virtual async Task <PriceCard> Process(CommerceContext commerceContext, PriceCard priceCard, PriceSnapshotComponent priceSnapshot, CustomPriceTier priceTier)
        {
            PriceCard result = null;

            using (CommandActivity.Start(commerceContext, this))
            {
                var priceSnapshotById = await GetPriceSnapshot(commerceContext, priceCard, priceSnapshot.Id)
                                        .ConfigureAwait(false);

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

                await PerformTransaction(commerceContext, (async() => result = await _addCustomPriceTierPipeline.Run(new PriceCardSnapshotCustomTierArgument(priceCard, priceSnapshotById, priceTier), commerceContext.GetPipelineContextOptions()).ConfigureAwait(false)))
                .ConfigureAwait(false);

                return(result);
            }
        }
        public override async Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Action) ||
                !arg.Action.Equals(context.GetPolicy <KnownPricingActionsPolicy>().AddPriceSnapshot, StringComparison.OrdinalIgnoreCase) ||
                context.CommerceContext.GetObjects <PriceCard>().FirstOrDefault(p => p.Id.Equals(arg.EntityId, StringComparison.OrdinalIgnoreCase)) == null)
            {
                return(arg);
            }

            ViewProperty beginDateViewProperty = arg.Properties.FirstOrDefault((p => p.Name.Equals("BeginDate", StringComparison.OrdinalIgnoreCase)));

            if (!DateTimeOffset.TryParse(beginDateViewProperty?.Value, null, DateTimeStyles.AdjustToUniversal, out DateTimeOffset resultBeginDate))
            {
                string str1 = beginDateViewProperty == null ? "BeginDate" : beginDateViewProperty.DisplayName;
                string str2 = await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[1]
                {
                    str1
                }, "Invalid or missing value for property 'BeginDate'.").ConfigureAwait(false);

                return(arg);
            }

            ViewProperty endDateViewProperty = arg.Properties.FirstOrDefault(p => p.Name.Equals("EndDate", StringComparison.OrdinalIgnoreCase));

            if (!DateTimeOffset.TryParse(endDateViewProperty?.Value, null, DateTimeStyles.AdjustToUniversal, out DateTimeOffset resultEndDate))
            {
                string str1 = endDateViewProperty == null ? "EndDate" : endDateViewProperty.DisplayName;
                string str2 = await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[1]
                {
                    str1
                }, "Invalid or missing value for property 'BeginDate'.").ConfigureAwait(false);

                return(arg);
            }

            ViewProperty useEndDateViewProerty = arg.Properties.FirstOrDefault((p => p.Name.Equals("UseEndDate", StringComparison.OrdinalIgnoreCase)));

            PriceCard priceCard = await this._addPriceSnapshotCommand.Process(context.CommerceContext, arg.EntityId, resultBeginDate, useEndDateViewProerty.Value.Equals("true")?resultEndDate : DateTimeOffset.MinValue).ConfigureAwait(false);

            return(arg);
        }
        private async Task <PriceCard> UpdateOrCreatePriceSnapshot(CommercePipelineExecutionContext context,
                                                                   PriceCard priceCard, DateTimeOffset beginDate, List <MembershipSnapshotPriceModel> prices)
        {
            if (priceCard == null)
            {
                return(null);
            }

            var priceSnapshotComponent   = new PriceSnapshotComponent(beginDate);
            var membershipTiersComponent = priceSnapshotComponent.GetComponent <MembershipTiersComponent>();

            if (membershipTiersComponent.Tiers != null)
            {
                foreach (var membershipPrice in prices)
                {
                    if (!membershipTiersComponent.Tiers.Any(x => x.MembershipLevel == membershipPrice.MemershipLevel))
                    {
                        membershipTiersComponent.Tiers.Add(new CustomPriceTier("USD", 1, membershipPrice.Price, membershipPrice.MemershipLevel));
                    }
                }
            }

            var snapshotComponent = priceCard.Snapshots.OrderByDescending(s => s.BeginDate).FirstOrDefault(s => s.IsApproved(context.CommerceContext));

            if (snapshotComponent != null &&
                snapshotComponent.BeginDate.CompareTo(priceSnapshotComponent.BeginDate) >= 0)
            {
                return(priceCard);
            }

            if (priceCard.Snapshots.Any(s => DateTimeOffset.Compare(s.BeginDate, priceSnapshotComponent.BeginDate) == 0))
            {
                return(priceCard);
            }

            var updatedPriceCard = await _addPriceSnapshotPipeline.Run(new PriceCardSnapshotArgument(priceCard, priceSnapshotComponent), context)
                                   .ConfigureAwait(false);

            return(updatedPriceCard);
        }
Пример #14
0
        public virtual async Task <PriceCard> Process(CommerceContext commerceContext, string cardFriendlyId, DateTimeOffset beginDate, DateTimeOffset endDate)
        {
            AddPriceSnapshotCommand priceSnapshotCommand = this;
            PriceCard result = null;

            using (CommandActivity.Start(commerceContext, priceSnapshotCommand))
            {
                PriceCard priceCard = await this.GetPriceCard(commerceContext, cardFriendlyId).ConfigureAwait(false);

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

                var pricingSnapshot  = new PriceSnapshotComponent(beginDate);
                var endDateComponent = pricingSnapshot.GetComponent <SnapshotEndDateComponent>();
                endDateComponent.EndDate = endDate;

                await priceSnapshotCommand.PerformTransaction(commerceContext, (async() => result = await this._addPriceSnapshotPipeline.Run(new PriceCardSnapshotArgument(priceCard, pricingSnapshot), commerceContext.PipelineContextOptions).ConfigureAwait(false))).ConfigureAwait(false);

                return(result);
            }
        }
Пример #15
0
        public virtual async Task <PriceCard> Process(CommerceContext commerceContext, string cardFriendlyId, string snapshotId, string priceTierId)
        {
            PriceCard result = null;

            using (CommandActivity.Start(commerceContext, this))
            {
                PriceCard priceCard = await GetPriceCard(commerceContext, cardFriendlyId)
                                      .ConfigureAwait(false);

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

                PriceSnapshotComponent priceSnapshot = await GetPriceSnapshot(commerceContext, priceCard, snapshotId)
                                                       .ConfigureAwait(false);

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

                var priceTier = await GetCustomPriceTier(commerceContext, priceCard, priceSnapshot, priceTierId)
                                .ConfigureAwait(false);

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

                await PerformTransaction(commerceContext, async() => result = await _removeCustomPriceTierPipeline.Run(new PriceCardSnapshotCustomTierArgument(priceCard, priceSnapshot, priceTier), commerceContext.GetPipelineContextOptions()).ConfigureAwait(false))
                .ConfigureAwait(false);

                return(result);
            }
        }
        protected virtual async Task PopulateRowDetails(EntityView view, PriceCard card, string itemId, bool isAddAction, bool isEditAction, CommercePipelineExecutionContext context)
        {
            if (view == null || card == null || string.IsNullOrEmpty(itemId))
            {
                return;
            }

            if (isAddAction)
            {
                CurrencySet currencySet  = null;
                string      entityTarget = (await _findEntityCommand.Process(context.CommerceContext, typeof(PriceBook), card.Book.EntityTarget, false).ConfigureAwait(false) as PriceBook)?.CurrencySet.EntityTarget;

                if (!string.IsNullOrEmpty(entityTarget))
                {
                    currencySet = await _getCurrencySetCommand.Process(context.CommerceContext, entityTarget).ConfigureAwait(false);
                }

                List <Policy> commercePolicies = new List <Policy>()
                {
                    new AvailableSelectionsPolicy(currencySet == null ||
                                                  !currencySet.HasComponent <CurrenciesComponent>() ?  new List <Selection>() :  currencySet.GetComponent <CurrenciesComponent>().Currencies.Select(c =>
                    {
                        return(new Selection()
                        {
                            DisplayName = c.Code,
                            Name = c.Code
                        });
                    }).ToList(), false)
                };

                ViewProperty item = new ViewProperty()
                {
                    Name     = "Currency",
                    RawValue = string.Empty,
                    Policies = commercePolicies
                };
                view.Properties.Add(item);
            }
            else
            {
                string[] strArray = itemId.Split('|');
                if (strArray.Length != 2 || string.IsNullOrEmpty(strArray[0]) || string.IsNullOrEmpty(strArray[1]))
                {
                    context.Logger.LogError("Expecting a SnapshotId and Currency in the ItemId: " + itemId + ". Correct format is 'snapshotId|currency'", Array.Empty <object>());
                }
                else
                {
                    string snapshotId = strArray[0];
                    string currency   = strArray[1];
                    PriceSnapshotComponent snapshotComponent = card.Snapshots.FirstOrDefault(s => s.Id.Equals(snapshotId, StringComparison.OrdinalIgnoreCase));

                    if (snapshotComponent == null)
                    {
                        context.Logger.LogError("Price snapshot " + snapshotId + " on price card " + card.FriendlyId + " was not found.", Array.Empty <object>());
                    }
                    else
                    {
                        var list = snapshotComponent.GetComponent <MembershipTiersComponent>().Tiers;
                        IGrouping <string, CustomPriceTier> currencyGroup = list.GroupBy(t => t.Currency)
                                                                            .ToList()
                                                                            .FirstOrDefault(g => g.Key.Equals(currency, StringComparison.OrdinalIgnoreCase));

                        if (currencyGroup == null)
                        {
                            context.Logger.LogError("Price row " + currency + " was not found in snapshot " + snapshotId + " for card " + card.FriendlyId + ".", Array.Empty <object>());
                        }
                        else
                        {
                            view.Properties.Add(new ViewProperty
                            {
                                Name       = "Currency",
                                RawValue   = currencyGroup.Key,
                                IsReadOnly = true
                            });

                            if (isEditAction)
                            {
                                view.UiHint = "Grid";
                                currencyGroup.ForEach(tier =>
                                {
                                    EntityView entityView = new EntityView()
                                    {
                                        Name     = context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomCell,
                                        EntityId = card.Id,
                                        ItemId   = itemId
                                    };

                                    var membershipLevels = context.GetPolicy <MembershipLevelPolicy>().MembershipLevels;

                                    ViewProperty item1 = new ViewProperty()
                                    {
                                        Name         = "MembershipLevel",
                                        RawValue     = tier.MembershipLevel,
                                        OriginalType = typeof(string).FullName,
                                        IsReadOnly   = true,
                                        Policies     = new List <Policy>()
                                        {
                                            new AvailableSelectionsPolicy(membershipLevels.Select(c =>
                                            {
                                                return(new Selection()
                                                {
                                                    DisplayName = c.MemerbshipLevelName,
                                                    Name = c.MemerbshipLevelName
                                                });
                                            }).ToList(), false)
                                        }
                                    };
                                    entityView.Properties.Add(item1);

                                    entityView.Properties.Add(new ViewProperty()
                                    {
                                        Name       = "Quantity",
                                        RawValue   = tier.Quantity,
                                        IsReadOnly = true
                                    });

                                    entityView.Properties.Add(new ViewProperty()
                                    {
                                        Name       = "Price",
                                        RawValue   = tier.Price,
                                        IsRequired = false
                                    });

                                    view.ChildViews.Add(entityView);
                                });
                            }
                            else
                            {
                                view.Properties.Add(new ViewProperty
                                {
                                    Name       = "ItemId",
                                    RawValue   = itemId,
                                    IsReadOnly = true,
                                    IsHidden   = true
                                });

                                list.Select(t => t.MembershipLevel).Distinct().OrderBy(q => q).ToList().ForEach(availableMembershipLevel =>
                                {
                                    CustomPriceTier priceTier      = currencyGroup.FirstOrDefault(ct => ct.MembershipLevel == availableMembershipLevel);
                                    List <ViewProperty> properties = view.Properties;
                                    properties.Add(new ViewProperty()
                                    {
                                        Name       = availableMembershipLevel.ToString(CultureInfo.InvariantCulture),
                                        RawValue   = priceTier?.Price,
                                        IsReadOnly = true
                                    });
                                });
                            }
                        }
                    }
                }
            }
        }
Пример #17
0
        public override Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(this.Name + ": The argument cannot be null");
            EntityViewArgument request = context.CommerceContext.GetObjects <EntityViewArgument>().FirstOrDefault();

            if (request == null)
            {
                return(Task.FromResult(arg));
            }

            bool isAddAction  = request.ForAction.Equals(context.GetPolicy <KnownPricingActionsPolicy>().AddPriceSnapshot, StringComparison.OrdinalIgnoreCase);
            bool isEditAction = request.ForAction.Equals(context.GetPolicy <KnownPricingActionsPolicy>().EditPriceSnapshot, StringComparison.OrdinalIgnoreCase);

            if (string.IsNullOrEmpty(request?.ViewName) ||
                !(request.Entity is PriceCard) ||
                !request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().Master, StringComparison.OrdinalIgnoreCase) &&
                !request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceCardSnapshots, StringComparison.OrdinalIgnoreCase) &&
                !request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, StringComparison.OrdinalIgnoreCase) ||
                request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, StringComparison.OrdinalIgnoreCase) &&
                string.IsNullOrEmpty(request.ItemId) && !isAddAction)
            {
                return(Task.FromResult(arg));
            }

            PriceCard card = (PriceCard)request.Entity;

            if (request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().Master, StringComparison.OrdinalIgnoreCase) ||
                request.ViewName.Equals(context.GetPolicy <KnownPricingViewsPolicy>().PriceCardSnapshots, StringComparison.OrdinalIgnoreCase))
            {
                List <EntityView> views = new List <EntityView>();
                this.FindViews(views, arg, context.GetPolicy <KnownPricingViewsPolicy>().PriceSnapshotDetails, context.CommerceContext);
                views.ForEach(snapshotDetailsView =>
                {
                    EntityView view                 = snapshotDetailsView;
                    PriceCard priceCard             = card;
                    PriceSnapshotComponent snapshot = priceCard?.Snapshots.FirstOrDefault(s => s.Id.Equals(snapshotDetailsView.ItemId, StringComparison.OrdinalIgnoreCase));
                    int num1 = isAddAction ? 1 : 0;
                    int num2 = isEditAction ? 1 : 0;
                    this.PopulateSnapshotDetails(view, snapshot, num1 != 0, num2 != 0);
                });
                return(Task.FromResult(arg));
            }
            PriceSnapshotComponent snapshotComponent;

            if (isAddAction)
            {
                snapshotComponent = null;
            }
            else
            {
                PriceCard priceCard = card;
                snapshotComponent = priceCard?.Snapshots.FirstOrDefault(s => s.Id.Equals(request.ItemId, StringComparison.OrdinalIgnoreCase));
            }
            PriceSnapshotComponent snapshot1 = snapshotComponent;

            this.PopulateSnapshotDetails(arg, snapshot1, isAddAction, isEditAction);
            var          rawValue      = arg.Properties.FirstOrDefault((p => p.Name.Equals("BeginDate", StringComparison.OrdinalIgnoreCase))).RawValue;
            CultureInfo  cultureInfo   = CultureInfo.GetCultureInfo(context.CommerceContext.CurrentLanguage());
            string       str           = (string.IsNullOrEmpty(card.DisplayName) ? card.Name : card.DisplayName) + " (" + rawValue + ")";
            ViewProperty viewProperty1 = arg.Properties.FirstOrDefault(p => p.Name.Equals("DisplayName", StringComparison.OrdinalIgnoreCase));

            if (viewProperty1 != null)
            {
                viewProperty1.RawValue = str;
            }

            else if (!isAddAction && !isEditAction)
            {
                List <ViewProperty> properties    = arg.Properties;
                ViewProperty        viewProperty2 = new ViewProperty
                {
                    Name       = "DisplayName",
                    RawValue   = str,
                    IsReadOnly = true
                };
                properties.Add(viewProperty2);
            }
            return(Task.FromResult(arg));
        }
        public override async Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Action) ||
                !arg.Action.Equals(context.GetPolicy <KnownCustomPricingActionsPolicy>().EditMembershipCurrency, StringComparison.OrdinalIgnoreCase) ||
                !arg.Name.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow, StringComparison.OrdinalIgnoreCase))
            {
                return(arg);
            }

            PriceCard card = context.CommerceContext.GetObjects <PriceCard>().FirstOrDefault(p => p.Id.Equals(arg.EntityId, StringComparison.OrdinalIgnoreCase));

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

            KnownResultCodes errorsCodes = context.GetPolicy <KnownResultCodes>();

            if (string.IsNullOrEmpty(arg.ItemId))
            {
                await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "InvalidOrMissingPropertyValue", new object[] { "ItemId" }, "Invalid or missing value for property 'ItemId'.")
                .ConfigureAwait(false);

                return(arg);
            }

            string snapshotId = arg.ItemId.Split('|')[0];
            PriceSnapshotComponent snapshot = card.Snapshots.FirstOrDefault(s => s.Id.Equals(snapshotId, StringComparison.OrdinalIgnoreCase));

            if (snapshot == null)
            {
                await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "PriceSnapshotNotFound", new object[] { snapshotId, card.FriendlyId }, "Price snapshot " + snapshotId + " on price card " + card.FriendlyId + " was not found.")
                .ConfigureAwait(false);

                return(arg);
            }

            ViewProperty currency = arg.Properties.FirstOrDefault(p => p.Name.Equals("Currency", StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrEmpty(currency?.Value))
            {
                await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "InvalidOrMissingPropertyValue", new object[] { currency == null ? "Currency" : currency.DisplayName }, "Invalid or missing value for property 'Currency'.")
                .ConfigureAwait(false);

                return(arg);
            }

            List <Model> list = arg.ChildViews.Where(v => v.Name.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomCell, StringComparison.OrdinalIgnoreCase))
                                .ToList();

            if (!list.Any())
            {
                await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "InvalidOrMissingPropertyValue", new object[] { "Tiers" }, "Invalid or missing value for property 'Tiers'.")
                .ConfigureAwait(false);

                return(arg);
            }

            List <CustomPriceTier> tiersToAdd    = new List <CustomPriceTier>();
            List <CustomPriceTier> tiersToEdit   = new List <CustomPriceTier>();
            List <CustomPriceTier> tiersToDelete = new List <CustomPriceTier>();
            bool hasError = false;

            foreach (EntityView entityView in list.Cast <EntityView>())
            {
                ViewProperty quantityViewProperty = entityView.Properties.FirstOrDefault(p => p.Name.Equals("Quantity", StringComparison.OrdinalIgnoreCase));
                decimal      quantity;

                if (!decimal.TryParse(quantityViewProperty?.Value, out quantity))
                {
                    await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "InvalidOrMissingPropertyValue", new object[] { quantityViewProperty == null ? "Quantity" : quantityViewProperty.DisplayName }, "Invalid or missing value for property 'Quantity'.")
                    .ConfigureAwait(false);

                    hasError = true;
                }
                else
                {
                    ViewProperty membershipLevel = entityView.Properties.FirstOrDefault(p => p.Name.Equals("MembershipLevel", StringComparison.OrdinalIgnoreCase));

                    if (string.IsNullOrEmpty(currency?.Value))
                    {
                        await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "InvalidOrMissingPropertyValue", new object[] { currency == null ? "MembershipLevel" : currency.DisplayName }, "Invalid or missing value for property 'MembershipLevel'.")
                        .ConfigureAwait(false);

                        hasError = true;
                    }
                    else
                    {
                        ViewProperty priceViewProperty = entityView.Properties.FirstOrDefault(p => p.Name.Equals("Price", StringComparison.OrdinalIgnoreCase));
                        decimal      result;
                        bool         isPriceParsed            = decimal.TryParse(priceViewProperty?.Value, out result);
                        var          membershipTiersComponent = snapshot.GetComponent <MembershipTiersComponent>();

                        CustomPriceTier priceTier = membershipTiersComponent.Tiers.FirstOrDefault(t => t.Currency == currency.Value && t.Quantity == quantity && t.MembershipLevel == membershipLevel.Value);

                        if (priceTier == null)
                        {
                            if (!isPriceParsed)
                            {
                                await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "InvalidOrMissingPropertyValue", new object[] { priceViewProperty == null ? "Price" : priceViewProperty.DisplayName }, "Invalid or missing value for property 'Price'.")
                                .ConfigureAwait(false);

                                hasError = true;
                            }
                            else
                            {
                                tiersToAdd.Add(new CustomPriceTier(currency.Value, quantity, result, membershipLevel.Value));
                            }
                        }
                        else if (!isPriceParsed)
                        {
                            tiersToDelete.Add(priceTier);
                        }
                        else
                        {
                            priceTier.Price           = result;
                            priceTier.Quantity        = quantity;
                            priceTier.MembershipLevel = membershipLevel.Value;
                            tiersToEdit.Add(priceTier);
                        }
                    }
                }
            }

            if (hasError)
            {
                return(arg);
            }

            if (tiersToAdd.Any())
            {
                await _addPriceTierCommand.Process(context.CommerceContext, card, snapshot, tiersToAdd)
                .ConfigureAwait(false);
            }

            if (tiersToDelete.Any() && !context.CommerceContext.HasErrors())
            {
                await _removeCustomPriceTierCommand.Process(context.CommerceContext, card, snapshot, tiersToDelete)
                .ConfigureAwait(false);
            }

            if (tiersToEdit.Any() && !context.CommerceContext.HasErrors())
            {
                await _editPriceTierCommand.Process(context.CommerceContext, card, snapshot, tiersToEdit)
                .ConfigureAwait(false);
            }

            return(arg);
        }
Пример #19
0
        public override async Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Action) ||
                !arg.Action.Equals(context.GetPolicy <KnownCustomPricingActionsPolicy>().AddMembershipCurrency, StringComparison.OrdinalIgnoreCase) ||
                !arg.Name.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow, StringComparison.OrdinalIgnoreCase))
            {
                return(arg);
            }

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

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

            var errorsCodes = context.GetPolicy <KnownResultCodes>();

            if (string.IsNullOrEmpty(arg.ItemId))
            {
                await context.CommerceContext.AddMessage(errorsCodes.ValidationError,
                                                         "InvalidOrMissingPropertyValue",
                                                         new object[] { "ItemId" }, "Invalid or missing value for property 'ItemId'.")
                .ConfigureAwait(false);

                return(arg);
            }

            var snapshot = card.Snapshots.FirstOrDefault(s => s.Id.Equals(arg.ItemId, StringComparison.OrdinalIgnoreCase));

            if (snapshot == null)
            {
                await context.CommerceContext.AddMessage(errorsCodes.ValidationError,
                                                         "PriceSnapshotNotFound",
                                                         new object[] { arg.ItemId, card.FriendlyId }, "Price snapshot " + arg.ItemId + " on price card " + card.FriendlyId + " was not found.")
                .ConfigureAwait(false);

                return(arg);
            }

            var currency = arg.Properties.FirstOrDefault(p => p.Name.Equals("Currency", StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrEmpty(currency?.Value))
            {
                await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "InvalidOrMissingPropertyValue", new object[]
                {
                    currency == null ? "Currency" : currency.DisplayName
                }, "Invalid or missing value for property 'Currency'.")
                .ConfigureAwait(false);

                return(arg);
            }

            var list = arg.ChildViews.Where(v => v.Name.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomCell, StringComparison.OrdinalIgnoreCase)).ToList();

            if (!list.Any())
            {
                await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "InvalidOrMissingPropertyValue",
                                                         new object[] { "Tiers" }, "Invalid or missing value for property 'Tiers'.")
                .ConfigureAwait(false);

                return(arg);
            }

            var tiers = new List <CustomPriceTier>();
            var flag  = false;

            foreach (EntityView entityView in list.Cast <EntityView>())
            {
                ViewProperty priceProperty = entityView.Properties.FirstOrDefault(p => p.Name.Equals("Price", StringComparison.OrdinalIgnoreCase));
                decimal      price;

                if (!decimal.TryParse(priceProperty?.Value, out price))
                {
                    await context.CommerceContext.AddMessage(errorsCodes.ValidationError, "InvalidOrMissingPropertyValue",
                                                             new object[] { priceProperty == null ? "Price" : priceProperty.DisplayName }, "Invalid or missing value for property 'Price'.")
                    .ConfigureAwait(false);

                    flag = true;
                }
                else
                {
                    ViewProperty membershipLevelProperty = entityView.Properties.FirstOrDefault(p => p.Name.Equals("MembershipLevel", StringComparison.OrdinalIgnoreCase));
                    tiers.Add(new CustomPriceTier(currency.Value, 1, price, membershipLevelProperty?.Value));
                }
            }
            if (!tiers.Any() | flag)
            {
                return(arg);
            }

            PriceCard priceCard = await _addCustomPriceTierCommand.Process(context.CommerceContext, card, snapshot, tiers)
                                  .ConfigureAwait(false);

            return(arg);
        }
Пример #20
0
        public override async Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Action) ||
                !arg.Action.Equals(context.GetPolicy <KnownCustomPricingActionsPolicy>().EditCustomPriceTier, StringComparison.OrdinalIgnoreCase) ||
                context.CommerceContext.GetObjects <PriceCard>().FirstOrDefault(p => p.Id.Equals(arg.EntityId, StringComparison.OrdinalIgnoreCase)) == null)
            {
                return(arg);
            }

            if (string.IsNullOrEmpty(arg.ItemId))
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[1] {
                    "ItemId"
                }, "Invalid or missing value for property 'ItemId'.")
                .ConfigureAwait(false);

                return(arg);
            }

            string[] strArray = arg.ItemId.Split('|');

            if (strArray.Length != 2)
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[] { "ItemId (Correct format is snapshotId|[tierId])" }, "Invalid or missing value for property 'ItemId (Correct format is snapshotId|[tierId])'.")
                .ConfigureAwait(false);

                return(arg);
            }
            string snapshotId  = strArray[0];
            string priceTierId = strArray[1];

            if (string.IsNullOrEmpty(snapshotId) || string.IsNullOrEmpty(priceTierId))
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[] { "ItemId (Correct format is snapshotId|[tierId])" }, "Invalid or missing value for property 'ItemId (Correct format is snapshotId|[tierId])'.")
                .ConfigureAwait(false);

                return(arg);
            }

            ViewProperty viewProperty = arg.Properties.FirstOrDefault(p => p.Name.Equals("Price", StringComparison.OrdinalIgnoreCase));
            decimal      result;

            if (!decimal.TryParse(viewProperty?.Value, out result))
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[] { viewProperty == null ? "Price" : viewProperty.DisplayName }, "Invalid or missing value for property 'Price'.")
                .ConfigureAwait(false);

                return(arg);
            }

            ViewProperty membershipLevel = arg.Properties.FirstOrDefault(p => p.Name.Equals("MembershipLevel", StringComparison.OrdinalIgnoreCase));

            if (string.IsNullOrEmpty(membershipLevel?.Value))
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[] { viewProperty == null ? "MembershipLevel" : viewProperty.DisplayName }, "Invalid or missing value for property 'MembershipLevel'.")
                .ConfigureAwait(false);

                return(arg);
            }

            PriceCard priceCard = await _editPriceTierCommand.Process(context.CommerceContext, arg.EntityId, snapshotId, priceTierId, result, membershipLevel?.Value)
                                  .ConfigureAwait(false);

            return(arg);
        }
Пример #21
0
 public PriceCardSnapshotCustomTierArgument(PriceCard priceCard, PriceSnapshotComponent priceSnapshot, CustomPriceTier priceTier)
     : base(priceCard, priceSnapshot)
 {
     Condition.Requires(priceTier).IsNotNull("The price tier can not be null");
     PriceTier = priceTier;
 }
        protected virtual async Task <CustomPriceTier> GetCustomPriceTier(CommerceContext context, PriceCard priceCard, PriceSnapshotComponent priceSnapshot, string priceTierId)
        {
            if (priceCard == null ||
                priceSnapshot == null ||
                string.IsNullOrEmpty(priceTierId))
            {
                return(null);
            }

            var membershipTiersComponent = priceSnapshot.GetComponent <MembershipTiersComponent>();
            var existingPriceTier        = membershipTiersComponent.Tiers.FirstOrDefault(t => t.Id.Equals(priceTierId, StringComparison.OrdinalIgnoreCase));

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

            await context.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "PriceTierNotFound",
                                     new object[] { priceTierId, priceSnapshot.Id, priceCard.FriendlyId }, "Price tier " + priceTierId + " was not found in snapshot " + priceSnapshot.Id + " for card " + priceCard.FriendlyId + ".")
            .ConfigureAwait(false);

            return(existingPriceTier);
        }
        /// <summary>
        ///     Creates the tags card.
        /// </summary>
        /// <param name="book">The book.</param>
        /// <param name="context">The context.</param>
        private async Task CreateTagsCard(PriceBook book, CommercePipelineExecutionContext context)
        {
            // TAGS CARD
            PriceCard card = await _addPriceCardPipeline
                             .Run(new AddPriceCardArgument(book, "Habitat_TagsPriceCard"), context).ConfigureAwait(false);

            // TAGS CARD FIRST SNAPSHOT
            card = await _addPriceSnapshotPipeline
                   .Run(new PriceCardSnapshotArgument(card, new PriceSnapshotComponent(DateTimeOffset.UtcNow)), context)
                   .ConfigureAwait(false);

            PriceSnapshotComponent firstSnapshot = card.Snapshots.FirstOrDefault();

            // TAGS CARD FIRST SNAPSHOT  TIERS
            card = await _addPriceTierPipeline
                   .Run(new PriceCardSnapshotTierArgument(card, firstSnapshot, new PriceTier("USD", 1, 250M)), context)
                   .ConfigureAwait(false);

            card = await _addPriceTierPipeline
                   .Run(new PriceCardSnapshotTierArgument(card, firstSnapshot, new PriceTier("USD", 5, 200M)), context)
                   .ConfigureAwait(false);

            card = await _addPriceTierPipeline
                   .Run(new PriceCardSnapshotTierArgument(card, firstSnapshot, new PriceTier("CAD", 1, 251M)), context)
                   .ConfigureAwait(false);

            card = await _addPriceTierPipeline
                   .Run(new PriceCardSnapshotTierArgument(card, firstSnapshot, new PriceTier("CAD", 5, 201M)), context)
                   .ConfigureAwait(false);

            // TAGS CARD FIRST SNAPSHOT TAGS
            card = await _addPriceSnapshotTagPipeline
                   .Run(new PriceCardSnapshotTagArgument(card, firstSnapshot, new Tag("Habitat")), context)
                   .ConfigureAwait(false);

            card = await _addPriceSnapshotTagPipeline
                   .Run(new PriceCardSnapshotTagArgument(card, firstSnapshot, new Tag("Habitat 2")), context)
                   .ConfigureAwait(false);

            card = await _addPriceSnapshotTagPipeline
                   .Run(new PriceCardSnapshotTagArgument(card, firstSnapshot, new Tag("common")), context)
                   .ConfigureAwait(false);

            // TAGS CARD SECOND SNAPSHOT
            card = await _addPriceSnapshotPipeline
                   .Run(new PriceCardSnapshotArgument(card, new PriceSnapshotComponent(DateTimeOffset.UtcNow.AddSeconds(1))),
                        context).ConfigureAwait(false);

            PriceSnapshotComponent secondSnapshot =
                card.Snapshots.FirstOrDefault(s => !s.Id.Equals(firstSnapshot?.Id, StringComparison.OrdinalIgnoreCase));

            // TAGS CARD SECOND SNAPSHOT TIERS
            card = await _addPriceTierPipeline
                   .Run(new PriceCardSnapshotTierArgument(card, secondSnapshot, new PriceTier("USD", 1, 150M)), context)
                   .ConfigureAwait(false);

            card = await _addPriceTierPipeline
                   .Run(new PriceCardSnapshotTierArgument(card, secondSnapshot, new PriceTier("USD", 5, 100M)), context)
                   .ConfigureAwait(false);

            card = await _addPriceTierPipeline
                   .Run(new PriceCardSnapshotTierArgument(card, secondSnapshot, new PriceTier("CAD", 1, 101M)), context)
                   .ConfigureAwait(false);

            card = await _addPriceTierPipeline
                   .Run(new PriceCardSnapshotTierArgument(card, secondSnapshot, new PriceTier("CAD", 5, 151M)), context)
                   .ConfigureAwait(false);

            // TAGS CARD SECOND SNAPSHOT TAGS
            card = await _addPriceSnapshotTagPipeline
                   .Run(new PriceCardSnapshotTagArgument(card, secondSnapshot, new Tag("Habitat variants")), context)
                   .ConfigureAwait(false);

            card = await _addPriceSnapshotTagPipeline
                   .Run(new PriceCardSnapshotTagArgument(card, secondSnapshot, new Tag("Habitat variants 2")), context)
                   .ConfigureAwait(false);

            card = await _addPriceSnapshotTagPipeline
                   .Run(new PriceCardSnapshotTagArgument(card, secondSnapshot, new Tag("common")), context)
                   .ConfigureAwait(false);

            // TAGS CARD APPROVAl COMPONENT
            card.Snapshots.ForEach(s =>
            {
                s.SetComponent(new ApprovalComponent(context.GetPolicy <ApprovalStatusPolicy>().Approved));
            });
            await _persistEntityPipeline.Run(new PersistEntityArgument(card), context).ConfigureAwait(false);
        }
Пример #24
0
        public override async Task <bool> Run(bool arg, CommercePipelineExecutionContext context)
        {
            SetApprovalStatusArgument argument = context.CommerceContext.GetObject <SetApprovalStatusArgument>();

            if (!(argument?.Entity is PriceCard) || string.IsNullOrEmpty(argument.Status) || string.IsNullOrEmpty(argument.ItemId))
            {
                return(arg);
            }

            PriceCard entity = (PriceCard)argument.Entity;
            PriceSnapshotComponent           snapshot = entity.Snapshots.FirstOrDefault(s => s.Id.Equals(argument.ItemId, StringComparison.OrdinalIgnoreCase));
            CommercePipelineExecutionContext executionContext;

            if (snapshot == null)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          commerceTermKey = "PriceSnapshotNotFound";
                object[]        args            = new object[2]
                {
                    argument.ItemId,
                    entity.FriendlyId
                };
                string defaultMessage = "Price snapshot '" + argument.ItemId + "' on price card '" + entity.FriendlyId + "' was not found.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage), context);
                executionContext = null;

                return(false);
            }

            var membershipTiersComponent = snapshot.GetComponent <MembershipTiersComponent>();

            if (!snapshot.Tiers.Any() && !membershipTiersComponent.Tiers.Any())
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          commerceTermKey = "InvalidPriceSnapshot";
                object[]        args            = new object[2]
                {
                    argument.ItemId,
                    entity.FriendlyId
                };
                string defaultMessage = "Price snapshot '" + argument.ItemId + "' on price card '" + entity.FriendlyId + "' has not pricing.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage), context);
                executionContext = null;
                return(false);
            }

            string currentStatus         = snapshot.GetComponent <ApprovalComponent>().Status;
            IEnumerable <string> strings = await _getPossibleStatusesPipeline.Run(new GetPossibleApprovalStatusesArgument(snapshot), context);

            if (strings == null || !strings.Any())
            {
                return(false);
            }

            if (!strings.Any(s => s.Equals(argument.Status, StringComparison.OrdinalIgnoreCase)))
            {
                string str = string.Join(",", strings);
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          commerceTermKey = "SetStatusFailed";
                object[]        args            = new object[4]
                {
                    snapshot.Id,
                    argument.Status,
                    str,
                    currentStatus
                };
                string defaultMessage = "Attempted to change status for '" + snapshot.Id + "' to '" + argument.Status + "'. Allowed status are '" + str + "' when current status is '" + currentStatus + "'.";
                executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, args, defaultMessage), context);
                executionContext = null;
                return(false);
            }

            snapshot.GetComponent <ApprovalComponent>().ModifyStatus(argument.Status, argument.Comment);
            await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Information, null, null, "Price snapshot '" + snapshot.Id + "' approval status has been updated.");

            return(true);
        }
        public override async Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Action) || !arg.Action.Equals(context.GetPolicy <KnownCustomPricingActionsPolicy>().RemoveMembershipCurrency, StringComparison.OrdinalIgnoreCase))
            {
                return(arg);
            }

            PriceCard card = context.CommerceContext.GetObjects <PriceCard>().FirstOrDefault(p => p.Id.Equals(arg.EntityId, StringComparison.OrdinalIgnoreCase));

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

            if (string.IsNullOrEmpty(arg.ItemId))
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[] { "ItemId" }, "Invalid or missing value for property 'ItemId'.")
                .ConfigureAwait(false);

                return(arg);
            }

            string[] strArray = arg.ItemId.Split('|');

            if (strArray.Length != 2 || string.IsNullOrEmpty(strArray[0]) || string.IsNullOrEmpty(strArray[1]))
            {
                string str = await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "InvalidOrMissingPropertyValue", new object[] { "ItemId (Correct format is snapshotId|currency)" }, "Invalid or missing value for property 'ItemId (Correct format is snapshotId|currency)'.")
                             .ConfigureAwait(false);

                return(arg);
            }
            string snapshotId = strArray[0];
            string currency   = strArray[1];
            PriceSnapshotComponent snapshotComponent = card.Snapshots.FirstOrDefault(s => s.Id.Equals(snapshotId, StringComparison.OrdinalIgnoreCase));

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

                return(arg);
            }

            var membershipTiersComponent = snapshotComponent.GetComponent <MembershipTiersComponent>();

            List <CustomPriceTier> list = membershipTiersComponent.Tiers.Where(t => t.Currency.Equals(currency, StringComparison.OrdinalIgnoreCase)).ToList();

            if (!list.Any())
            {
                await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "CurrencyNotFound", new object[] { currency, snapshotId, card.FriendlyId }, "Currency '" + currency + "' for price snapshot '" + snapshotId + "' on price card '" + card.FriendlyId + "' was not found.")
                .ConfigureAwait(false);

                return(arg);
            }

            foreach (CustomPriceTier priceTier in list)
            {
                PriceCard priceCard = await _removeCustomPriceTierCommand.Process(context.CommerceContext, card.FriendlyId, snapshotId, priceTier.Id).ConfigureAwait(false);
            }


            return(arg);
        }
        /// <summary>
        ///     Creates the variants card.
        /// </summary>
        /// <param name="book">The book.</param>
        /// <param name="context">The context.</param>
        private async Task CreateVariantsCard(PriceBook book, CommercePipelineExecutionContext context)
        {
            context.CommerceContext.RemoveModels(m => m is PriceSnapshotAdded || m is PriceTierAdded);

            DateTimeOffset date = DateTimeOffset.UtcNow;

            // VARIANTS CARD
            PriceCard adventureVariantsCard = await _addPriceCardPipeline
                                              .Run(new AddPriceCardArgument(book, "Habitat_VariantsPriceCard"), context)
                                              .ConfigureAwait(false);

            // READY FOR APPROVAL SNAPSHOT
            adventureVariantsCard = await _addPriceSnapshotPipeline
                                    .Run(
                new PriceCardSnapshotArgument(adventureVariantsCard,
                                              new PriceSnapshotComponent(date.AddMinutes(-10))), context)
                                    .ConfigureAwait(false);

            PriceSnapshotComponent readyForApprovalSnapshot =
                adventureVariantsCard.Snapshots.FirstOrDefault(s =>
                                                               s.Id.Equals(context.CommerceContext.GetModel <PriceSnapshotAdded>()?.PriceSnapshotId,
                                                                           StringComparison.OrdinalIgnoreCase));

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, readyForApprovalSnapshot,
                                                  new PriceTier("USD", 1, 2000M)), context).ConfigureAwait(false);

            context.CommerceContext.RemoveModels(m => m is PriceSnapshotAdded || m is PriceTierAdded);

            // FIRST APPROVED SNAPSHOT
            adventureVariantsCard = await _addPriceSnapshotPipeline
                                    .Run(
                new PriceCardSnapshotArgument(adventureVariantsCard,
                                              new PriceSnapshotComponent(date.AddHours(-1))), context).ConfigureAwait(false);

            PriceSnapshotComponent firstSnapshot = adventureVariantsCard.Snapshots.FirstOrDefault(s =>
                                                                                                  s.Id.Equals(
                                                                                                      context.CommerceContext
                                                                                                      .GetModel <PriceSnapshotAdded>()
                                                                                                      ?.PriceSnapshotId,
                                                                                                      StringComparison.OrdinalIgnoreCase));

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, firstSnapshot,
                                                  new PriceTier("USD", 1, 9M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, firstSnapshot,
                                                  new PriceTier("USD", 5, 6M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, firstSnapshot,
                                                  new PriceTier("USD", 10, 3M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, firstSnapshot,
                                                  new PriceTier("CAD", 1, 7M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, firstSnapshot,
                                                  new PriceTier("CAD", 5, 4M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, firstSnapshot,
                                                  new PriceTier("CAD", 10, 2M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, firstSnapshot,
                                                  new PriceTier("EUR", 1, 2M)), context).ConfigureAwait(false);

            context.CommerceContext.RemoveModels(m => m is PriceSnapshotAdded || m is PriceTierAdded);

            // DRAFT SNAPSHOT
            adventureVariantsCard = await _addPriceSnapshotPipeline
                                    .Run(
                new PriceCardSnapshotArgument(adventureVariantsCard,
                                              new PriceSnapshotComponent(date)), context).ConfigureAwait(false);

            PriceSnapshotComponent draftSnapshot = adventureVariantsCard.Snapshots.FirstOrDefault(s =>
                                                                                                  s.Id.Equals(
                                                                                                      context.CommerceContext
                                                                                                      .GetModel <PriceSnapshotAdded>()
                                                                                                      ?.PriceSnapshotId,
                                                                                                      StringComparison.OrdinalIgnoreCase));

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, draftSnapshot,
                                                  new PriceTier("USD", 1, 1000M)), context).ConfigureAwait(false);

            context.CommerceContext.RemoveModels(m => m is PriceSnapshotAdded || m is PriceTierAdded);

            // SECOND APPROVED SNAPSHOT
            adventureVariantsCard = await _addPriceSnapshotPipeline
                                    .Run(
                new PriceCardSnapshotArgument(adventureVariantsCard,
                                              new PriceSnapshotComponent(date.AddDays(30))), context).ConfigureAwait(false);

            PriceSnapshotComponent secondSnapshot = adventureVariantsCard.Snapshots.FirstOrDefault(s =>
                                                                                                   s.Id.Equals(
                                                                                                       context.CommerceContext
                                                                                                       .GetModel <PriceSnapshotAdded>()
                                                                                                       ?.PriceSnapshotId,
                                                                                                       StringComparison.OrdinalIgnoreCase));

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, secondSnapshot,
                                                  new PriceTier("USD", 1, 8M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, secondSnapshot,
                                                  new PriceTier("USD", 5, 4M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, secondSnapshot,
                                                  new PriceTier("USD", 10, 2M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, secondSnapshot,
                                                  new PriceTier("CAD", 1, 7M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, secondSnapshot,
                                                  new PriceTier("CAD", 5, 3M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, secondSnapshot,
                                                  new PriceTier("CAD", 10, 1M)), context).ConfigureAwait(false);

            adventureVariantsCard = await _addPriceTierPipeline
                                    .Run(
                new PriceCardSnapshotTierArgument(adventureVariantsCard, secondSnapshot,
                                                  new PriceTier("EUR", 1, 2M)), context).ConfigureAwait(false);

            context.CommerceContext.RemoveModels(m => m is PriceSnapshotAdded || m is PriceTierAdded);

            readyForApprovalSnapshot?.SetComponent(
                new ApprovalComponent(context.GetPolicy <ApprovalStatusPolicy>().ReadyForApproval));
            firstSnapshot?.SetComponent(new ApprovalComponent(context.GetPolicy <ApprovalStatusPolicy>().Approved));
            secondSnapshot?.SetComponent(new ApprovalComponent(context.GetPolicy <ApprovalStatusPolicy>().Approved));
            await _persistEntityPipeline.Run(new PersistEntityArgument(adventureVariantsCard), context).ConfigureAwait(false);
        }