protected virtual bool GetEnabledStatus(SellableItem sellableItem, string variantId)
        {
            if (sellableItem.IsBundle)
            {
                // TODO: Implement support for bundles
                return(true);
            }

            if (string.IsNullOrWhiteSpace(variantId))
            {
                if (!sellableItem.HasComponent <ItemVariationsComponent>())
                {
                    return(true);
                }

                var variants = sellableItem.GetComponent <ItemVariationsComponent>().GetComponents <ItemVariationComponent>();
                foreach (var variant in variants)
                {
                    if (!variant.Disabled)
                    {
                        return(true);
                    }
                }
            }
            else
            {
                var variant = sellableItem.GetVariation(variantId);
                return(!variant.Disabled);
            }

            return(false);
        }
Ejemplo n.º 2
0
        private async Task <bool?> CalculateCartLinePrice(
            CartLineComponent arg,
            CommercePipelineExecutionContext context)
        {
            ProductArgument productArgument = ProductArgument.FromItemId(arg.ItemId);
            SellableItem    sellableItem    = null;

            if (productArgument.IsValid())
            {
                sellableItem = context.CommerceContext.GetEntity((Func <SellableItem, bool>)(s => s.ProductId.Equals(productArgument.ProductId, StringComparison.OrdinalIgnoreCase)));

                if (sellableItem == null)
                {
                    string simpleName = productArgument.ProductId.SimplifyEntityName();
                    sellableItem = context.CommerceContext.GetEntity((Func <SellableItem, bool>)(s => s.ProductId.Equals(simpleName, StringComparison.OrdinalIgnoreCase)));

                    if (sellableItem != null)
                    {
                        sellableItem.ProductId = simpleName;
                    }
                }
            }
            if (sellableItem == null)
            {
                CommercePipelineExecutionContext executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                object[]        args            = new object[] { arg.ItemId };
                string          defaultMessage  = "Item '" + arg.ItemId + "' is not purchasable.";
                executionContext.Abort(await commerceContext.AddMessage(error, "LineIsNotPurchasable", args, defaultMessage), context);
                executionContext = null;
                return(new bool?());
            }

            MessagesComponent messagesComponent = arg.GetComponent <MessagesComponent>();

            messagesComponent.Clear(context.GetPolicy <KnownMessageCodePolicy>().Pricing);

            if (sellableItem.HasComponent <MessagesComponent>())
            {
                List <MessageModel> messages = sellableItem.GetComponent <MessagesComponent>().GetMessages(context.GetPolicy <KnownMessageCodePolicy>().Pricing);
                messagesComponent.AddMessages(messages);
            }
            arg.UnitListPrice = sellableItem.ListPrice;
            string listPriceMessage = "CartItem.ListPrice<=SellableItem.ListPrice: Price=" + arg.UnitListPrice.AsCurrency(false, null);
            string sellPriceMessage = string.Empty;
            PurchaseOptionMoneyPolicy optionMoneyPolicy = new PurchaseOptionMoneyPolicy();

            if (sellableItem.HasPolicy <PurchaseOptionMoneyPolicy>())
            {
                optionMoneyPolicy.SellPrice = sellableItem.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice;
                sellPriceMessage            = "CartItem.SellPrice<=SellableItem.SellPrice: Price=" + optionMoneyPolicy.SellPrice.AsCurrency(false, null);
            }

            PriceSnapshotComponent snapshotComponent;

            if (sellableItem.HasComponent <ItemVariationsComponent>())
            {
                ItemVariationSelectedComponent lineVariant             = arg.ChildComponents.OfType <ItemVariationSelectedComponent>().FirstOrDefault();
                ItemVariationsComponent        itemVariationsComponent = sellableItem.GetComponent <ItemVariationsComponent>();
                ItemVariationComponent         itemVariationComponent;

                if (itemVariationsComponent == null)
                {
                    itemVariationComponent = null;
                }
                else
                {
                    IList <Component> childComponents = itemVariationsComponent.ChildComponents;
                    itemVariationComponent = childComponents?.OfType <ItemVariationComponent>().FirstOrDefault(v =>
                    {
                        return(!string.IsNullOrEmpty(v.Id) ? v.Id.Equals(lineVariant?.VariationId, StringComparison.OrdinalIgnoreCase) : false);
                    });
                }

                if (itemVariationComponent != null)
                {
                    if (itemVariationComponent.HasComponent <MessagesComponent>())
                    {
                        List <MessageModel> messages = itemVariationComponent.GetComponent <MessagesComponent>().GetMessages(context.GetPolicy <KnownMessageCodePolicy>().Pricing);
                        messagesComponent.AddMessages(messages);
                    }

                    arg.UnitListPrice = itemVariationComponent.ListPrice;
                    listPriceMessage  = "CartItem.ListPrice<=SellableItem.Variation.ListPrice: Price=" + arg.UnitListPrice.AsCurrency(false, null);

                    if (itemVariationComponent.HasPolicy <PurchaseOptionMoneyPolicy>())
                    {
                        optionMoneyPolicy.SellPrice = itemVariationComponent.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice;
                        sellPriceMessage            = "CartItem.SellPrice<=SellableItem.Variation.SellPrice: Price=" + optionMoneyPolicy.SellPrice.AsCurrency(false, null);
                    }
                }
                snapshotComponent = itemVariationComponent != null?itemVariationComponent.ChildComponents.OfType <PriceSnapshotComponent>().FirstOrDefault() : null;
            }
            else
            {
                snapshotComponent = sellableItem.Components.OfType <PriceSnapshotComponent>().FirstOrDefault();
            }

            string currentCurrency = context.CommerceContext.CurrentCurrency();

            PriceTier priceTier = snapshotComponent?.Tiers.OrderByDescending(t => t.Quantity).FirstOrDefault(t =>
            {
                return(t.Currency.Equals(currentCurrency, StringComparison.OrdinalIgnoreCase) ? t.Quantity <= arg.Quantity : false);
            });

            Customer customer = await _findEntityPipeline.Run(new FindEntityArgument(typeof(Customer), context.CommerceContext.CurrentCustomerId(), false), context) as Customer;

            bool isMembershipLevelPrice = false;

            if (customer != null && customer.HasComponent <MembershipSubscriptionComponent>())
            {
                var membershipSubscriptionComponent = customer.GetComponent <MembershipSubscriptionComponent>();
                var membershipLevel = membershipSubscriptionComponent.MemerbshipLevelName;

                if (snapshotComponent != null && snapshotComponent.HasComponent <MembershipTiersComponent>())
                {
                    var membershipTiersComponent = snapshotComponent.GetComponent <MembershipTiersComponent>();
                    var membershipPriceTier      = membershipTiersComponent.Tiers.FirstOrDefault(x => x.MembershipLevel == membershipLevel);

                    if (membershipPriceTier != null)
                    {
                        optionMoneyPolicy.SellPrice = new Money(membershipPriceTier.Currency, membershipPriceTier.Price);
                        isMembershipLevelPrice      = true;

                        sellPriceMessage = string.Format("CartItem.SellPrice<=PriceCard.ActiveSnapshot: MembershipLevel={0}|Price={1}|Qty={2}", membershipSubscriptionComponent.MemerbshipLevelName, optionMoneyPolicy.SellPrice.AsCurrency(false, null), membershipPriceTier.Quantity);
                    }
                }
            }

            if (!isMembershipLevelPrice && priceTier != null)
            {
                optionMoneyPolicy.SellPrice = new Money(priceTier.Currency, priceTier.Price);
                sellPriceMessage            = string.Format("CartItem.SellPrice<=PriceCard.ActiveSnapshot: Price={0}|Qty={1}", optionMoneyPolicy.SellPrice.AsCurrency(false, null), priceTier.Quantity);
            }

            arg.Policies.Remove(arg.Policies.OfType <PurchaseOptionMoneyPolicy>().FirstOrDefault());

            if (optionMoneyPolicy.SellPrice == null)
            {
                return(false);
            }

            arg.SetPolicy(optionMoneyPolicy);

            if (!string.IsNullOrEmpty(sellPriceMessage))
            {
                messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, sellPriceMessage);
            }

            if (!string.IsNullOrEmpty(listPriceMessage))
            {
                messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, listPriceMessage);
            }

            return(true);
        }
        private async Task UpsertSellableItem(SellableItem item, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(item.ProductId))
            {
                item.ProductId = item.Id.SimplifyEntityName().ProposeValidId();
            }

            if (string.IsNullOrEmpty(item.FriendlyId))
            {
                item.FriendlyId = item.Id.SimplifyEntityName();
            }

            if (string.IsNullOrEmpty(item.SitecoreId))
            {
                item.SitecoreId = GuidUtility.GetDeterministicGuidString(item.Id);
            }

            CommerceEntity entity = await _findEntityPipeline
                                    .Run(new FindEntityArgument(typeof(SellableItem), item.Id), context)
                                    .ConfigureAwait(false);

            if (entity == null)
            {
                await _persistEntityPipeline.Run(new PersistEntityArgument(item), context).ConfigureAwait(false);

                return;
            }

            if (!(entity is SellableItem))
            {
                return;
            }

            var existingSellableItem = entity as SellableItem;

            // Try to merge the items.
            existingSellableItem.Name = item.Name;

            foreach (Policy policy in item.EntityPolicies)
            {
                if (existingSellableItem.HasPolicy(policy.GetType()))
                {
                    existingSellableItem.RemovePolicy(policy.GetType());
                }

                existingSellableItem.SetPolicy(policy);
            }

            if (item.HasComponent <ItemVariationsComponent>())
            {
                var variations = existingSellableItem.GetComponent <ItemVariationsComponent>();

                foreach (ItemVariationComponent variation in item
                         .GetComponent <ItemVariationsComponent>().ChildComponents
                         .OfType <ItemVariationComponent>())
                {
                    ItemVariationComponent existingVariation = existingSellableItem.GetVariation(variation.Id);
                    if (existingVariation != null)
                    {
                        existingVariation.Name = variation.Name;

                        foreach (Policy policy in variation.Policies)
                        {
                            if (existingVariation.Policies.Any(x => x.GetType() == policy.GetType()))
                            {
                                existingVariation.RemovePolicy(policy.GetType());
                            }

                            existingVariation.SetPolicy(policy);
                        }
                    }
                    else
                    {
                        variations.ChildComponents.Add(variation);
                    }
                }
            }

            await _persistEntityPipeline.Run(new PersistEntityArgument(existingSellableItem), context).ConfigureAwait(false);
        }
        public async Task <ItemType> RelistItem(CommerceContext commerceContext, SellableItem sellableItem)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                //Instantiate the call wrapper class
                var apiCall = new RelistItemCall(await GetEbayContext(commerceContext).ConfigureAwait(false));

                if (sellableItem.HasComponent <EbayItemComponent>())
                {
                    var ebayItemComponent = sellableItem.GetComponent <EbayItemComponent>();

                    try
                    {
                        var item = await PrepareItem(commerceContext, sellableItem);

                        item.ItemID = ebayItemComponent.EbayId;

                        //item.ListingDuration = "Days_" + 10;

                        //Send the call to eBay and get the results
                        var feeResult = apiCall.RelistItem(item, new StringCollection());

                        ebayItemComponent.EbayId = item.ItemID;

                        ebayItemComponent.Status = "Listed";
                        sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Listed");

                        foreach (var feeItem in feeResult)
                        {
                            var fee = feeItem as FeeType;
                            ebayItemComponent.Fees.Add(new AwardedAdjustment {
                                Adjustment = new Money(fee.Fee.currencyID.ToString(), System.Convert.ToDecimal(fee.Fee.Value)), AdjustmentType = "Fee", Name = fee.Name
                            });
                        }

                        ebayItemComponent.History.Add(new HistoryEntryModel {
                            EventMessage = "Listing Relisted", EventUser = commerceContext.CurrentCsrId()
                        });

                        return(item);
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Contains("It looks like this listing is for an item you already have on eBay"))
                        {
                            var existingId = ex.Message.Substring(ex.Message.IndexOf("(") + 1);
                            existingId = existingId.Substring(0, existingId.IndexOf(")"));
                            await commerceContext.AddMessage("Warn", "Ebay.RelistItem", new Object[] { }, $"ExistingId:{existingId}-ComponentId:{ebayItemComponent.EbayId}").ConfigureAwait(false);

                            ebayItemComponent.EbayId = existingId;
                            ebayItemComponent.Status = "Listed";
                            sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Listed");
                        }
                        else
                        {
                            commerceContext.Logger.LogError($"Ebay.RelistItem.Exception: Message={ex.Message}");
                            await commerceContext.AddMessage("Error", "Ebay.RelistItem.Exception", new Object[] { ex }, ex.Message).ConfigureAwait(false);
                        }
                    }
                }
                else
                {
                    commerceContext.Logger.LogError($"EbayCommand.RelistItem.Exception: Message=ebayCommand.RelistItem.NoEbayItemComponent");
                    await commerceContext.AddMessage("Error", "Ebay.RelistItem.Exception", new Object[] { }, "ebayCommand.RelistItem.NoEbayItemComponent").ConfigureAwait(false);
                }

                return(new ItemType());
            }
        }
        public async Task <bool> EndItemListing(CommerceContext commerceContext, SellableItem sellableItem, string reason)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                //Instantiate the call wrapper class

                try
                {
                    var apiCall = new EndItemCall(await GetEbayContext(commerceContext));

                    if (sellableItem.HasComponent <EbayItemComponent>())
                    {
                        var ebayItemComponent = sellableItem.GetComponent <EbayItemComponent>();

                        var reasonCodeType = EndReasonCodeType.NotAvailable;

                        switch (reason)
                        {
                        case "NotAvailable":
                            reasonCodeType = EndReasonCodeType.NotAvailable;
                            break;

                        case "CustomCode":
                            reasonCodeType = EndReasonCodeType.CustomCode;
                            break;

                        case "Incorrect":
                            reasonCodeType = EndReasonCodeType.Incorrect;
                            break;

                        case "LostOrBroken":
                            reasonCodeType = EndReasonCodeType.LostOrBroken;
                            break;

                        case "OtherListingError":
                            reasonCodeType = EndReasonCodeType.OtherListingError;
                            break;

                        case "SellToHighBidder":
                            reasonCodeType = EndReasonCodeType.SellToHighBidder;
                            break;

                        case "Sold":
                            reasonCodeType = EndReasonCodeType.Sold;
                            break;

                        default:
                            reasonCodeType = EndReasonCodeType.CustomCode;
                            break;
                        }

                        if (string.IsNullOrEmpty(ebayItemComponent.EbayId))
                        {
                            ebayItemComponent.Status = "LostSync";
                        }
                        else
                        {
                            if (ebayItemComponent.Status != "Ended")
                            {
                                //Call Ebay and End the Item Listing
                                try
                                {
                                    apiCall.EndItem(ebayItemComponent.EbayId, reasonCodeType);
                                    ebayItemComponent.Status = "Ended";
                                }
                                catch (Exception ex)
                                {
                                    if (ex.Message == "The auction has already been closed.")
                                    {
                                        //Capture a case where the listing has expired naturally and it can now no longer be ended.
                                        reason = "Expired";
                                        ebayItemComponent.Status = "Ended";
                                    }
                                    else
                                    {
                                        commerceContext.Logger.LogError(ex, $"EbayCommand.EndItemListing.Exception: Message={ex.Message}");
                                        await commerceContext.AddMessage("Error", "EbayCommand.EndItemListing", new [] { ex }, ex.Message).ConfigureAwait(false);
                                    }
                                }
                            }
                        }

                        ebayItemComponent.ReasonEnded = reason;

                        ebayItemComponent.History.Add(new HistoryEntryModel {
                            EventMessage = "Listing Ended", EventUser = commerceContext.CurrentCsrId()
                        });

                        sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Ended");

                        var persistResult = await this._commerceCommander.PersistEntity(commerceContext, sellableItem).ConfigureAwait(false);

                        var listRemoveResult = await this._commerceCommander.Command <ListCommander>()
                                               .RemoveItemsFromList(commerceContext, "Ebay_Listed", new List <String>()
                        {
                            sellableItem.Id
                        }).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    commerceContext.Logger.LogError($"Ebay.EndItemListing.Exception: Message={ex.Message}");
                    await commerceContext.AddMessage("Error", "Ebay.EndItemListing.Exception", new Object[] { ex }, ex.Message).ConfigureAwait(false);
                }

                return(true);
            }
        }
Ejemplo n.º 6
0
        public async Task AddEntityProperties(CommercePipelineExecutionContext context, EntityView entityView, EntityView detailsView, SellableItem entity, bool isAddAction, bool isEditAction, string viewName)
        {
            var policy = context.GetPolicy <KnownCatalogViewsPolicy>();
            var itemId = entityView.ItemId;

            if (!string.IsNullOrEmpty(itemId))
            {
                detailsView.ItemId = itemId;
            }
            var variation     = entity.GetVariation(itemId);
            var flag1         = variation != null;
            var properties1   = detailsView.Properties;
            var viewProperty1 = new ViewProperty
            {
                Name       = flag1 ? "VariantId" : "ProductId",
                RawValue   = flag1 ? variation.Id : entity?.ProductId ?? string.Empty,
                IsReadOnly = !isAddAction,
                IsRequired = isAddAction | isEditAction,
                IsHidden   = false
            };

            properties1.Add(viewProperty1);
            var properties2   = detailsView.Properties;
            var viewProperty2 = new ViewProperty
            {
                Name       = "Name",
                RawValue   = variation != null ? variation.Name : entity?.Name ?? string.Empty,
                IsReadOnly = !isAddAction,
                IsRequired = isAddAction,
                IsHidden   = !isAddAction
            };

            properties2.Add(viewProperty2);
            var properties3   = detailsView.Properties;
            var viewProperty3 = new ViewProperty
            {
                Name       = "DisplayName",
                RawValue   = variation != null ? variation.DisplayName : entity?.DisplayName ?? string.Empty,
                IsReadOnly = !isAddAction && !isEditAction,
                IsRequired = isAddAction | isEditAction,
                IsHidden   = false
            };

            properties3.Add(viewProperty3);
            if (!isAddAction && !isEditAction)
            {
                var definitions = new List <string>();
                if (entity != null && entity.HasComponent <CatalogsComponent>())
                {
                    entity.GetComponent <CatalogsComponent>().Catalogs.Where(c => !string.IsNullOrEmpty(c.ItemDefinition)).ForEach(c => definitions.Add(
                                                                                                                                       $"{c.Name} - {c.ItemDefinition}"));
                }
                var properties4   = detailsView.Properties;
                var viewProperty4 = new ViewProperty
                {
                    Name         = "ItemDefinitions",
                    RawValue     = definitions,
                    IsReadOnly   = true,
                    IsRequired   = false,
                    UiType       = "List",
                    OriginalType = "List"
                };
                properties4.Add(viewProperty4);
            }
            var properties5   = detailsView.Properties;
            var viewProperty5 = new ViewProperty
            {
                Name       = "Description",
                RawValue   = variation != null ? variation.Description : entity?.Description ?? string.Empty,
                IsReadOnly = !isAddAction && !isEditAction,
                IsRequired = false,
                IsHidden   = false
            };

            properties5.Add(viewProperty5);
            var properties6   = detailsView.Properties;
            var viewProperty6 = new ViewProperty
            {
                Name       = "Brand",
                RawValue   = entity?.Brand ?? string.Empty,
                IsReadOnly = ((isAddAction ? 0 : (!isEditAction ? 1 : 0)) | (flag1 ? 1 : 0)) != 0,
                IsRequired = false,
                IsHidden   = false
            };

            properties6.Add(viewProperty6);
            var properties7   = detailsView.Properties;
            var viewProperty7 = new ViewProperty
            {
                Name       = "Manufacturer",
                RawValue   = entity?.Manufacturer ?? string.Empty,
                IsReadOnly = ((isAddAction ? 0 : (!isEditAction ? 1 : 0)) | (flag1 ? 1 : 0)) != 0,
                IsRequired = false,
                IsHidden   = false
            };

            properties7.Add(viewProperty7);
            var properties8   = detailsView.Properties;
            var viewProperty8 = new ViewProperty
            {
                Name       = "TypeOfGood",
                RawValue   = entity?.TypeOfGood ?? string.Empty,
                IsReadOnly = ((isAddAction ? 0 : (!isEditAction ? 1 : 0)) | (flag1 ? 1 : 0)) != 0,
                IsRequired = false,
                IsHidden   = false
            };

            properties8.Add(viewProperty8);
            var source        = ((variation?.Tags ?? entity?.Tags) ?? new List <Tag>()).Select(x => x.Name);
            var properties9   = detailsView.Properties;
            var viewProperty9 = new ViewProperty
            {
                Name         = "Tags",
                RawValue     = source.ToArray(),
                IsReadOnly   = !isAddAction && !isEditAction,
                IsRequired   = false,
                IsHidden     = false,
                UiType       = isEditAction | isAddAction ? "Tags" : "List",
                OriginalType = "List"
            };

            properties9.Add(viewProperty9);
            var flag2 = entityView.Name.Equals(policy.ConnectSellableItem, StringComparison.OrdinalIgnoreCase);

            if (flag2)
            {
                var properties4   = detailsView.Properties;
                var viewProperty4 = new ViewProperty
                {
                    Name       = "VariationProperties",
                    RawValue   = string.Empty,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = false
                };
                properties4.Add(viewProperty4);
                var properties10   = detailsView.Properties;
                var viewProperty10 = new ViewProperty
                {
                    Name       = "SitecoreId",
                    RawValue   = entity?.SitecoreId ?? string.Empty,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = true
                };
                properties10.Add(viewProperty10);
                var properties11   = detailsView.Properties;
                var viewProperty11 = new ViewProperty
                {
                    Name       = "ParentCatalogList",
                    RawValue   = entity?.ParentCatalogList ?? string.Empty,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = true
                };
                properties11.Add(viewProperty11);
                var properties12   = detailsView.Properties;
                var viewProperty12 = new ViewProperty
                {
                    Name       = "ParentCategoryList",
                    RawValue   = entity?.ParentCategoryList ?? string.Empty,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = true
                };
                properties12.Add(viewProperty12);
            }
            if (isAddAction || isEditAction)
            {
                return;
            }
            var dictionary  = new Dictionary <string, object>();
            var entityView1 = new EntityView
            {
                DisplayName   = "Identifiers",
                Name          = "Identifiers",
                UiHint        = "Flat",
                EntityId      = entityView.EntityId,
                EntityVersion = entityView.EntityVersion,
                ItemId        = itemId
            };
            var entityView2 = entityView1;

            if (entity != null && entity.HasComponent <IdentifiersComponent>(itemId) | flag2)
            {
                var component = entity.GetComponent <IdentifiersComponent>(itemId);
                dictionary.Add("ISBN", component.ISBN);
                dictionary.Add("LEICode", component.LEICode);
                dictionary.Add("SKU", component.SKU);
                dictionary.Add("TaxID", component.TaxID);
                dictionary.Add("gtin8", component.gtin8);
                dictionary.Add("gtin12", component.gtin12);
                dictionary.Add("gtin13", component.gtin13);
                dictionary.Add("mbm", component.mbm);
                dictionary.Add("ISSN", component.ISSN);
                foreach (var keyValuePair in dictionary)
                {
                    var properties4   = entityView2.Properties;
                    var viewProperty4 = new ViewProperty
                    {
                        Name       = keyValuePair.Key,
                        RawValue   = keyValuePair.Value ?? string.Empty,
                        IsReadOnly = true,
                        IsRequired = false,
                        IsHidden   = false
                    };
                    properties4.Add(viewProperty4);
                }
            }
            var entityView3 = new EntityView
            {
                DisplayName   = "Display Properties",
                Name          = "DisplayProperties",
                UiHint        = "Flat",
                EntityId      = entityView.EntityId,
                EntityVersion = entityView.EntityVersion,
                ItemId        = itemId
            };
            var entityView4 = entityView3;

            dictionary.Clear();
            if (entity != null && entity.HasComponent <DisplayPropertiesComponent>(itemId) | flag2)
            {
                var component     = entity.GetComponent <DisplayPropertiesComponent>(itemId);
                var properties4   = entityView4.Properties;
                var viewProperty4 = new ViewProperty
                {
                    Name       = "Color",
                    RawValue   = component.Color ?? string.Empty,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = false
                };
                properties4.Add(viewProperty4);
                var properties10   = entityView4.Properties;
                var viewProperty10 = new ViewProperty
                {
                    Name       = "Size",
                    RawValue   = component.Size ?? string.Empty,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = false
                };
                properties10.Add(viewProperty10);
                var properties11   = entityView4.Properties;
                var viewProperty11 = new ViewProperty
                {
                    Name       = "DisambiguatingDescription",
                    RawValue   = component.DisambiguatingDescription ?? string.Empty,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = false
                };
                properties11.Add(viewProperty11);
                var properties12   = entityView4.Properties;
                var viewProperty12 = new ViewProperty
                {
                    Name       = "DisplayOnSite",
                    RawValue   = component.DisplayOnSite,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = false
                };
                properties12.Add(viewProperty12);
                var properties13   = entityView4.Properties;
                var viewProperty13 = new ViewProperty
                {
                    Name       = "DisplayInProductList",
                    RawValue   = component.DisplayInProductList,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = false
                };
                properties13.Add(viewProperty13);
                var properties14   = entityView4.Properties;
                var viewProperty14 = new ViewProperty
                {
                    Name       = "Style",
                    RawValue   = component.Style,
                    IsReadOnly = true,
                    IsRequired = false,
                    IsHidden   = false
                };
                properties14.Add(viewProperty14);
            }
            var entityView5 = new EntityView
            {
                DisplayName   = "Images",
                Name          = "Images",
                UiHint        = "Table",
                EntityId      = entityView.EntityId,
                EntityVersion = entityView.EntityVersion,
                ItemId        = itemId
            };
            var entityView6 = entityView5;
            var entityView7 = new EntityView
            {
                DisplayName   = "Item Specifications",
                Name          = "ItemSpecifications",
                UiHint        = "Flat",
                EntityId      = entityView.EntityId,
                EntityVersion = entityView.EntityVersion,
                ItemId        = itemId
            };
            var entityView8 = entityView7;

            dictionary.Clear();
            if (entity != null && entity.HasComponent <ItemSpecificationsComponent>(itemId) | flag2)
            {
                var component = entity.GetComponent <ItemSpecificationsComponent>(itemId);
                if (component.AreaServed == null)
                {
                    component.AreaServed = new GeoLocation();
                }
                var city       = component.AreaServed.City;
                var region     = component.AreaServed.Region;
                var postalCode = component.AreaServed.PostalCode;
                var str1       = string.IsNullOrWhiteSpace(region) ? "" : ", " + region;
                var str2       = string.IsNullOrWhiteSpace(postalCode) ? "" : ", " + postalCode;
                var str3       = $"{city}{str1}{str2}".TrimStart(',');
                dictionary.Add("AreaServed", str3);
                if (flag2)
                {
                    dictionary.Add("Weight", component.Weight);
                    dictionary.Add("WeightUnitOfMeasure", component.WeightUnitOfMeasure);
                    dictionary.Add("Length", component.Length);
                    dictionary.Add("Width", component.Width);
                    dictionary.Add("Height", component.Height);
                    dictionary.Add("DimensionsUnitOfMeasure", component.DimensionsUnitOfMeasure);
                    dictionary.Add("SizeOnDisk", component.Weight);
                    dictionary.Add("SizeOnDiskUnitOfMeasure", component.WeightUnitOfMeasure);
                }
                else
                {
                    dictionary.Add("Weight", $"{component.Weight} {component.WeightUnitOfMeasure}");
                    var str4 = string.Format("{0}{3}x{1}{3}x{2}{3}", component.Width, component.Height, component.Length, component.DimensionsUnitOfMeasure);
                    dictionary.Add("Dimensions", str4);
                    dictionary.Add("DigitalProperties", $"{component.SizeOnDisk} {component.SizeOnDiskUnitOfMeasure}");
                }
                foreach (var keyValuePair in dictionary)
                {
                    var properties4   = entityView8.Properties;
                    var viewProperty4 = new ViewProperty
                    {
                        Name       = keyValuePair.Key,
                        RawValue   = keyValuePair.Value,
                        IsReadOnly = true,
                        IsRequired = false,
                        IsHidden   = false
                    };
                    properties4.Add(viewProperty4);
                }
            }
            this.AddSellableItemPricing(entityView, entity, variation, context);
            AddSellableItemVariations(entityView, entity, context);
            await AddSellableItemParentCategories(entityView, entity, context);

            entityView.ChildViews.Add(entityView2);
            entityView.ChildViews.Add(entityView4);
            entityView.ChildViews.Add(entityView6);
            entityView.ChildViews.Add(entityView8);
            if (!entityView.Name.Equals("Variant", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }
            var properties15   = entityView.Properties;
            var viewProperty15 = new ViewProperty
            {
                DisplayName = "DisplayName",
                Name        = "DisplayName",
                RawValue    = variation?.DisplayName
            };

            properties15.Add(viewProperty15);
        }
Ejemplo n.º 7
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);
        }