public async Task <bool> Process(CommerceContext commerceContext)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var customerTotals = new Dictionary <string, OrdersTotals>();

                try
                {
                    var orderTotals = await this._commerceCommander.GetEntity <OrdersTotals>(commerceContext, "Orders_Totals", true);

                    if (!orderTotals.IsPersisted)
                    {
                        orderTotals.Id = "Orders_Totals";
                    }
                    orderTotals.LastRunStarted = DateTimeOffset.UtcNow;
                    orderTotals.LastRunEnded   = DateTimeOffset.MinValue;
                    orderTotals.MonitorCycle++;

                    var batchSize = 300;

                    var arg         = new FindEntitiesInListArgument(typeof(CommerceEntity), "Orders", System.Convert.ToInt32(orderTotals.LastSkip), batchSize);
                    var ordersBatch = await this._commerceCommander.Pipeline <FindEntitiesInListPipeline>().Run(arg, commerceContext.GetPipelineContextOptions());

                    while (ordersBatch.List.Items.Count > 0)
                    {
                        var returnedOrders = ordersBatch.List.Items.OfType <Order>();

                        foreach (var order in returnedOrders)
                        {
                            orderTotals.Totals.GrandTotal.Amount       = orderTotals.Totals.GrandTotal.Amount + order.Totals.GrandTotal.Amount;
                            orderTotals.Totals.SubTotal.Amount         = orderTotals.Totals.SubTotal.Amount + order.Totals.SubTotal.Amount;
                            orderTotals.Totals.PaymentsTotal.Amount    = orderTotals.Totals.PaymentsTotal.Amount + order.Totals.PaymentsTotal.Amount;
                            orderTotals.Totals.AdjustmentsTotal.Amount = orderTotals.Totals.AdjustmentsTotal.Amount + order.Totals.AdjustmentsTotal.Amount;

                            foreach (var adjustment in order.Adjustments)
                            {
                                var adjustmentType = orderTotals.Adjustments.FirstOrDefault(p => p.Name == adjustment.AdjustmentType);
                                if (adjustmentType == null)
                                {
                                    adjustmentType = new TotalsAdjustmentsModel {
                                        Name = adjustment.AdjustmentType
                                    };
                                    orderTotals.Adjustments.Add(adjustmentType);
                                }
                                adjustmentType.Adjustment.Amount = adjustmentType.Adjustment.Amount + adjustment.Adjustment.Amount;
                            }

                            if (order.HasComponent <ContactComponent>())
                            {
                                OrdersTotals orderTotalsByCust = null;

                                var orderContactComponent = order.GetComponent <ContactComponent>();
                                var customerTotalsId      = $"Order_Totals_ByCust_{orderContactComponent.CustomerId.Replace("Entity-Customer-", "")}";

                                if (customerTotals.ContainsKey(customerTotalsId))
                                {
                                    orderTotalsByCust = customerTotals[customerTotalsId];
                                }
                                else
                                {
                                    orderTotalsByCust = await this._commerceCommander
                                                        .GetEntity <OrdersTotals>(commerceContext, customerTotalsId, true);
                                }

                                if (!orderTotalsByCust.IsPersisted)
                                {
                                    orderTotalsByCust.Id = customerTotalsId;
                                }
                                else
                                {
                                    if (orderTotalsByCust.OrderCount == 0 || orderTotalsByCust.MonitorCycle != orderTotals.MonitorCycle)
                                    {
                                        orderTotalsByCust.Totals.GrandTotal.Amount       = 0;
                                        orderTotalsByCust.Totals.SubTotal.Amount         = 0;
                                        orderTotalsByCust.Totals.PaymentsTotal.Amount    = 0;
                                        orderTotalsByCust.Totals.AdjustmentsTotal.Amount = 0;
                                        orderTotalsByCust.MonitorCycle = orderTotals.MonitorCycle;
                                        orderTotalsByCust.Adjustments.Clear();
                                    }
                                }
                                orderTotalsByCust.OrderCount++;

                                orderTotalsByCust.LastSkip = orderTotalsByCust.LastSkip + batchSize;

                                orderTotalsByCust.Totals.GrandTotal.Amount       = orderTotalsByCust.Totals.GrandTotal.Amount + order.Totals.GrandTotal.Amount;
                                orderTotalsByCust.Totals.SubTotal.Amount         = orderTotalsByCust.Totals.SubTotal.Amount + order.Totals.SubTotal.Amount;
                                orderTotalsByCust.Totals.PaymentsTotal.Amount    = orderTotalsByCust.Totals.PaymentsTotal.Amount + order.Totals.PaymentsTotal.Amount;
                                orderTotalsByCust.Totals.AdjustmentsTotal.Amount = orderTotalsByCust.Totals.AdjustmentsTotal.Amount + order.Totals.AdjustmentsTotal.Amount;

                                foreach (var adjustment in order.Adjustments)
                                {
                                    var adjustmentType = orderTotalsByCust.Adjustments.FirstOrDefault(p => p.Name == adjustment.AdjustmentType);
                                    if (adjustmentType == null)
                                    {
                                        adjustmentType = new TotalsAdjustmentsModel
                                        {
                                            Name = adjustment.AdjustmentType
                                        };
                                        orderTotalsByCust.Adjustments.Add(adjustmentType);
                                    }
                                    adjustmentType.Adjustment.Amount = adjustmentType.Adjustment.Amount + adjustment.Adjustment.Amount;
                                }
                            }

                            orderTotals.OrderCount++;
                        }

                        orderTotals.LastSkip = orderTotals.LastSkip + batchSize;

                        orderTotals.History.Add(new HistoryEntryModel {
                            Name = "MonitorTotals.BatchCompleted", EventMessage = $"Completed batch: {orderTotals.LastSkip}"
                        });

                        orderTotals.LastRunEnded = DateTimeOffset.UtcNow;

                        orderTotals.LastSkip = (orderTotals.LastSkip - batchSize) + returnedOrders.Count();

                        await this._commerceCommander.PersistEntity(commerceContext, orderTotals);

                        foreach (var orderCustomerTotal in customerTotals)
                        {
                            await this._commerceCommander.PersistEntity(commerceContext, orderCustomerTotal.Value);
                        }

                        customerTotals.Clear();

                        await Task.Delay(100);

                        arg         = new FindEntitiesInListArgument(typeof(CommerceEntity), "Orders", System.Convert.ToInt32(orderTotals.LastSkip), batchSize);
                        ordersBatch = await this._commerceCommander.Pipeline <FindEntitiesInListPipeline>().Run(arg, commerceContext.GetPipelineContextOptions());
                    }
                }
                catch (Exception ex)
                {
                    commerceContext.Logger.LogError($"ChildViewEnvironments.Exception: Message={ex.Message}");
                }
                return(true);
            }
        }
Example #2
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The argument cannot be null");

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

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

            entityView.UiHint      = "Table";
            entityView.Icon        = pluginPolicy.Icon;
            entityView.DisplayName = "List Master";

            var arg          = new FindEntitiesInListArgument(typeof(CommerceEntity), "ManagedLists", 0, 100);
            var managedLists = await this._commerceCommander.Pipeline <FindEntitiesInListPipeline>().Run(arg, context.CommerceContext.GetPipelineContextOptions());

            if (managedLists.List.TotalItemCount > 0)
            {
                foreach (var managedList in managedLists.List.Items.OfType <ManagedList>())
                {
                    managedList.TotalItemCount = await this._commerceCommander.Command <GetListCountCommand>().Process(context.CommerceContext, managedList.Name);

                    var publishedListEntities = managedList.GetComponent <ListEntitiesInPublish>();

                    var duration = publishedListEntities.LastPublishEnd - publishedListEntities.LastPublishStart;

                    entityView.ChildViews.Add(
                        new EntityView
                    {
                        ItemId     = managedList.Id,
                        Icon       = pluginPolicy.Icon,
                        Properties = new List <ViewProperty>
                        {
                            new ViewProperty {
                                Name = "ItemId", RawValue = managedList.Id, UiType = "EntityLink", IsHidden = true
                            },
                            new ViewProperty {
                                Name = "Name", RawValue = managedList.Name, UiType = "EntityLink"
                            },
                            new ViewProperty {
                                Name = "DisplayName", RawValue = managedList.DisplayName
                            },
                            new ViewProperty {
                                Name = "Count", RawValue = managedList.TotalItemCount
                            },
                            new ViewProperty {
                                Name = "LastPublishStart", RawValue = publishedListEntities.LastPublishStart.ToString("yyyy-MMM-dd hh:mm zzz")
                            },
                            new ViewProperty {
                                Name = "LastPublishEnd", RawValue = publishedListEntities.LastPublishEnd.ToString("yyyy-MMM-dd hh:mm zzz")
                            },
                            new ViewProperty {
                                Name = "LastPublishCount", RawValue = publishedListEntities.LastPublishCount
                            },
                            new ViewProperty {
                                Name = "Duration", DisplayName = "Duration (s)", RawValue = duration.Seconds
                            },
                            new ViewProperty {
                                Name = "LastRow", RawValue = publishedListEntities.LastRow
                            }
                        }
                    });
                }
            }

            return(entityView);
        }
Example #3
0
        public override async Task <bool> Run(SellableItemInventorySetsArgument argument, CommercePipelineExecutionContext context)
        {
            AssociateStoreInventoryToSellablteItemBlock associateStoreInventoryToSellablteItemBlock = this;

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

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

            CommercePipelineExecutionContext executionContext;

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

            SellableItem sellableItem = entity as SellableItem;

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

            ItemVariationComponent sellableItemVariation = null;

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

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

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

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

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

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

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

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

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

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

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

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

                inventoryAssociations.Add(inventoryAssociation);
            }

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

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

            return(true);
        }
Example #4
0
        public override async Task <List <string> > Run(string catalogName, CommercePipelineExecutionContext context)
        {
            List <InventorySet> inventorySets = new List <InventorySet>();

            GetProductsToUpdateInventoryBlock getProductsToUpdateInventoryBlock = this;

            // get the sitecoreid from catalog based on catalogname
            var catalogSitecoreId = "";
            FindEntitiesInListArgument entitiesInListArgumentCatalog = await getProductsToUpdateInventoryBlock._findEntitiesInListPipeline.Run(new FindEntitiesInListArgument(typeof(Catalog), string.Format("{0}", (object)CommerceEntity.ListName <Catalog>()), 0, int.MaxValue), context);

            foreach (CommerceEntity commerceEntity in (await getProductsToUpdateInventoryBlock._findEntitiesInListPipeline.Run(entitiesInListArgumentCatalog, (IPipelineExecutionContextOptions)context.ContextOptions)).List.Items)
            {
                var item = commerceEntity as Catalog;

                if (item.Name == catalogName)
                {
                    catalogSitecoreId = item.SitecoreId;
                    break;
                }
            }


            if (string.IsNullOrEmpty(catalogSitecoreId))
            {
                return(null);
            }

            List <string> productIds = new List <string>();


            string              cacheKey      = string.Format("{0}|{1}|{2}", context.CommerceContext.Environment.Name, context.CommerceContext.CurrentLanguage(), context.CommerceContext.CurrentShopName() ?? "");
            CatalogCachePolicy  cachePolicy   = context.GetPolicy <CatalogCachePolicy>();
            ICache              cache         = null;
            List <SellableItem> sellableItems = null;

            if (cachePolicy.AllowCaching)
            {
                IGetEnvironmentCachePipeline cachePipeline            = getProductsToUpdateInventoryBlock._cachePipeline;
                EnvironmentCacheArgument     environmentCacheArgument = new EnvironmentCacheArgument();
                environmentCacheArgument.CacheName = cachePolicy.CatalogsCacheName;
                CommercePipelineExecutionContext context1 = context;
                cache = await cachePipeline.Run(environmentCacheArgument, context1).ConfigureAwait(false);

                sellableItems = await cache.Get(cacheKey).ConfigureAwait(false) as List <SellableItem>;

                if (sellableItems != null)
                {
                    foreach (var item in sellableItems)
                    {
                        await GetProductId(context, getProductsToUpdateInventoryBlock, catalogSitecoreId, productIds, item);
                    }
                }
            }
            else
            {
                sellableItems = new List <SellableItem>();
                FindEntitiesInListArgument entitiesInListArgument = new FindEntitiesInListArgument(typeof(SellableItem), string.Format("{0}", (object)CommerceEntity.ListName <SellableItem>()), 0, int.MaxValue);
                foreach (CommerceEntity commerceEntity in (await getProductsToUpdateInventoryBlock._findEntitiesInListPipeline.Run(entitiesInListArgument, context.ContextOptions).ConfigureAwait(false)).List.Items)
                {
                    await GetProductId(context, getProductsToUpdateInventoryBlock, catalogSitecoreId, productIds, commerceEntity as SellableItem).ConfigureAwait(false);
                }

                if (cachePolicy.AllowCaching)
                {
                    if (cache != null)
                    {
                        await cache.Set(cacheKey, new Cachable <List <SellableItem> >(sellableItems, 1L), cachePolicy.GetCacheEntryOptions()).ConfigureAwait(false);
                    }
                }
            }

            return(productIds);
        }
Example #5
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            if (entityView == null ||
                !entityView.Action.Equals("ListMaster-ExportList", StringComparison.OrdinalIgnoreCase))
            {
                return(entityView);
            }

            try
            {
                var listName      = entityView.ItemId;
                var directoryPath = @"C:\Users\kha\Documents\ExportedEntities\";

                var asPack      = entityView.Properties.First(p => p.Name == "AsPack").Value ?? "";
                var incremental = entityView.Properties.First(p => p.Name == "Incremental").Value ?? "";

                var listFriendlyName = entityView.ItemId.Replace("Entity-ManagedList-", "");

                var asPackBool      = System.Convert.ToBoolean(asPack);
                var incrementalBool = System.Convert.ToBoolean(incremental);

                var listCount = await this._commerceCommander.Command <GetListCountCommand>().Process(context.CommerceContext, listFriendlyName);

                var listMembers           = new StringBuilder();
                var listMembersSerialized = new StringBuilder();

                var packContainer = new PackContainer();

                var managedList = await this._commerceCommander.Command <GetManagedListCommand>().Process(context.CommerceContext, listFriendlyName);

                if (managedList != null)
                {
                    var publishedListEntities = managedList.GetComponent <ListEntitiesInPublish>();
                    publishedListEntities.LastPublishStart = DateTimeOffset.UtcNow;
                    publishedListEntities.LastPublishCount = 0;
                    if (!incrementalBool)
                    {
                        publishedListEntities.LastRow = 0;
                        publishedListEntities.PublishCycle++;
                        publishedListEntities.PublishIteration = 0;
                    }
                    else
                    {
                        publishedListEntities.PublishIteration++;
                    }
                    var historyComponent = managedList.GetComponent <HistoryComponent>();
                    historyComponent.History.Add(new HistoryEntryModel {
                        Name = "StartPublish", EventMessage = $"Start Publish of List:{listName} ({listCount})"
                    });
                    var managedListPersistResult = await this._commerceCommander.PersistEntity(context.CommerceContext, managedList);

                    JsonSerializerSettings serializerSettings = new JsonSerializerSettings
                    {
                        TypeNameHandling  = TypeNameHandling.All,
                        NullValueHandling = NullValueHandling.Ignore,
                        MaxDepth          = 100,
                        Formatting        = Formatting.Indented
                    };

                    while (publishedListEntities.LastRow < listCount)
                    {
                        var arg    = new FindEntitiesInListArgument(typeof(CommerceEntity), listFriendlyName, publishedListEntities.LastRow, 100);
                        var result = await this._commerceCommander.Pipeline <FindEntitiesInListPipeline>().Run(arg, context.CommerceContext.GetPipelineContextOptions());

                        foreach (var listEntity in result.List.Items)
                        {
                            var serializedEntity = JsonConvert.SerializeObject(listEntity, serializerSettings);

                            listMembersSerialized.Append(serializedEntity + ",");
                            managedList.TotalItemCount++;

                            packContainer.Entities.Add(listEntity);

                            listMembers.AppendLine();

                            publishedListEntities.LastPublishCount++;
                        }

                        publishedListEntities.LastRow = publishedListEntities.LastRow + 100;
                    }

                    if (asPackBool)
                    {
                        packContainer.ManagedLists.Add(managedList);

                        var serializedPackContainer = JsonConvert.SerializeObject(packContainer, serializerSettings);
                        var writePath = directoryPath + $"{context.CommerceContext.Environment.Name}-Pack-" + managedList.Id + $"_{DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm")}.json";
                        if (incrementalBool)
                        {
                            writePath = directoryPath + $"{context.CommerceContext.Environment.Name}.{managedList.Name}-Pack-{publishedListEntities.PublishCycle.ToString("00#")}-{publishedListEntities.PublishIteration.ToString("00#")}-{DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm")}.json";
                        }
                        else
                        {
                            writePath = directoryPath + $"{context.CommerceContext.Environment.Name}.{managedList.Name}-Pack-{publishedListEntities.PublishCycle.ToString("00#")}-000-{DateTime.UtcNow.ToString("yyyy-MM-dd-hh-mm")}.json";
                        }
                        File.WriteAllText(writePath, serializedPackContainer);

                        this._commerceCommander.Command <GzipCommand>().Compress(context.CommerceContext, new DirectoryInfo(directoryPath));
                    }

                    historyComponent.History.Add(new HistoryEntryModel {
                        Name = "ListPublish", EventMessage = $"Published List:{listName} ({listCount})"
                    });

                    publishedListEntities.LastPublishEnd = DateTimeOffset.UtcNow;

                    await this._commerceCommander.PersistEntity(context.CommerceContext, managedList);
                }
            }
            catch (Exception ex)
            {
                context.Logger.LogError($"Catalog.DoActionAddList.Exception: Message={ex.Message}");
            }

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

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

            var forAction = entityViewArgument.ForAction;

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

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

                properties.Add(viewPropertyCode);


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

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

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

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

            Promotion entity = entityViewArgument.Entity as Promotion;

            if (entity != null)
            {
                EntityView publicCouponsView;

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

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

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

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

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

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


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


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

            return(entityView);
        }