Example #1
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);
            }
        }
        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);
        }
Example #3
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);
        }
Example #4
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;
 }
Example #5
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);
            }
        }
        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
                                    });
                                });
                            }
                        }
                    }
                }
            }
        }