public void SellableItemCompare_ByImportData_ProductExtensionComponent_03_ItemBoth_IsNull( SellableItem ItemA) { /********************************************** * Arrange **********************************************/ var comparer = new ImportSellableItemComparer(SellableItemComparerConfiguration.ByImportData); var ItemB = ItemA.Clone(); ItemA.GetComponent <ProductExtensionComponent>().Style = null; ItemB.GetComponent <ProductExtensionComponent>().Style = null; /********************************************** * Act **********************************************/ bool result = false; Action executeAction = () => result = comparer.Equals(ItemA, ItemB); /********************************************** * Assert **********************************************/ executeAction.Should().NotThrow <Exception>(); ItemA.GetComponent <ProductExtensionComponent>().Style.Should().BeNull(); result.Should().BeTrue(); }
public void SellableItemCompare_ByImportData_Images_06_AreEqual( SellableItem ItemA, ImagesComponent ImagesComponentA) { /********************************************** * Arrange **********************************************/ var comparer = new ImportSellableItemComparer(SellableItemComparerConfiguration.ByImportData); ItemA.Components.Add(ImagesComponentA); var ItemB = ItemA.Clone(); /********************************************** * Act **********************************************/ bool result = false; Action executeAction = () => result = comparer.Equals(ItemA, ItemB); /********************************************** * Assert **********************************************/ executeAction.Should().NotThrow <Exception>(); ItemA.GetComponent <ImagesComponent>().Images.Count().Should().BeGreaterThan(0); ItemA.GetComponent <ImagesComponent>().Images.Count().Should().Be(ItemB.GetComponent <ImagesComponent>().Images.Count()); result.Should().BeTrue(); }
public void SellableItemCompare_ByImportData_Images_05_SameCount_EachListWithDifferentDuplicates( SellableItem ItemA, ImagesComponent ImagesComponentA) { /********************************************** * Arrange **********************************************/ var comparer = new ImportSellableItemComparer(SellableItemComparerConfiguration.ByImportData); ItemA.Components.Add(ImagesComponentA); var ItemB = ItemA.Clone(); ItemA.GetComponent <ImagesComponent>().Images.Add(ItemA.GetComponent <ImagesComponent>().Images[0].Clone().ToString()); ItemB.GetComponent <ImagesComponent>().Images.Add(ItemB.GetComponent <ImagesComponent>().Images[2].Clone().ToString()); /********************************************** * Act **********************************************/ bool result = false; Action executeAction = () => result = comparer.Equals(ItemA, ItemB); /********************************************** * Assert **********************************************/ executeAction.Should().NotThrow <Exception>(); ItemA.GetComponent <ImagesComponent>().Images.Count().Should().Be(ItemB.GetComponent <ImagesComponent>().Images.Count()); result.Should().BeFalse(); }
private async Task UpdateSyncforceComposerTemplate(SynchronizeProductArgument arg, CommercePipelineExecutionContext context, SellableItem sellableItem, ComposerTemplate commonComposerTemplate, SyncForceClientPolicy syncForcePolicy) { var sellableEntityViewComponent = sellableItem.GetComponent <EntityViewComponent>(); if (sellableEntityViewComponent != null) { EntityView tempViewHolder = new EntityView(); tempViewHolder.SetPropertyValue("Template", syncForcePolicy.CommonComposerTemplateName); tempViewHolder.GetProperty(it => String.Equals(it.Name, "Template", StringComparison.InvariantCultureIgnoreCase)).Value = syncForcePolicy.CommonComposerTemplateName; EntityView templateView = !string.IsNullOrEmpty(tempViewHolder.ItemId) ? sellableItem.GetComponent <EntityViewComponent>().ChildViewWithItemId(tempViewHolder.ItemId) : sellableItem.GetComponent <EntityViewComponent>().View.ChildViews.OfType <EntityView>().FirstOrDefault <EntityView>(); if (templateView == null || !sellableItem.GetComponent <EntityViewComponent>().HasChildViews((Func <EntityView, bool>)(p => p.Name.Equals(templateView.Name, StringComparison.OrdinalIgnoreCase)))) { await _composerCommander.AddChildViewFromTemplate(context.CommerceContext, tempViewHolder, sellableItem); } var composerView = sellableItem.GetComponent <EntityViewComponent>()?.View.ChildViews?.OfType <EntityView>() ?.FirstOrDefault(v => v.Name == syncForcePolicy.CommonComposerTemplateName); if (composerView != null) { //Add SyncForce timestamp var timestampDateTime = DateTime.SpecifyKind(arg.MasterProduct.TimeStamp, DateTimeKind.Utc); var timestampDateTimeOffset = (DateTimeOffset)timestampDateTime; var timestampRawValue = timestampDateTimeOffset.ToString("yyyy-MM-dd'T'H:mm:ss.fffffffzzz"); //Ensure timestamp field on ComposerTemplate await EnsureComposerTemplateProperty(syncForcePolicy, commonComposerTemplate, context.CommerceContext, composerView, "Timestamp", "System.DateTimeOffset"); if (composerView.ContainsProperty("Timestamp")) { composerView.SetPropertyValue("Timestamp", timestampRawValue); } else { composerView.Properties.Add(new ViewProperty() { DisplayName = "Timestamp", RawValue = timestampRawValue, IsHidden = false, IsReadOnly = false, IsRequired = false, Name = "Timestamp", OriginalType = "System.DateTimeOffset" }); } } } }
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); }
public void SellableItemCompare_ByImportData_ProductExtensionComponent_05_AreDifferent( SellableItem ItemA, ProductExtensionComponent ProductExtensionComponentA) { /********************************************** * Arrange **********************************************/ var comparer = new ImportSellableItemComparer(SellableItemComparerConfiguration.ByImportData); ItemA.Components.Add(ProductExtensionComponentA); var ItemB = ItemA.Clone(); ItemB.GetComponent <ProductExtensionComponent>().Style += "1"; /********************************************** * Act **********************************************/ bool result = false; Action executeAction = () => result = comparer.Equals(ItemA, ItemB); /********************************************** * Assert **********************************************/ executeAction.Should().NotThrow <Exception>(); ItemA.GetComponent <ProductExtensionComponent>().Style.Should().NotBeNullOrWhiteSpace(); result.Should().BeFalse(); }
private SellableItem TransformCore(CommerceContext commerceContext, JToken rawLine, List <SellableItem> importItems) { var productId = rawLine[ProductIdIndex].ToString(); var id = productId.ToEntityId <SellableItem>(); var item = importItems.FirstOrDefault(i => i.Id.Equals(id)); if (item == null) { item = new SellableItem(); item.ProductId = productId; item.Id = id; item.FriendlyId = item.ProductId; item.Name = rawLine[ProductNameIndex].ToString(); item.SitecoreId = GuidUtils.GetDeterministicGuidString(item.Id); item.DisplayName = rawLine[DisplayNameIndex].ToString(); item.TypeOfGood = rawLine[TypeOfGoodIndex].ToString(); var listPricePolicy = item.GetPolicy <ListPricingPolicy>(); listPricePolicy.AddPrice(new Money { CurrencyCode = "USD", Amount = decimal.Parse(rawLine[ListPriceIndex].ToString()) }); var component = item.GetComponent <ListMembershipsComponent>(); component.Memberships.Add(string.Format("{0}", CommerceEntity.ListName <SellableItem>())); component.Memberships.Add(commerceContext.GetPolicy <KnownCatalogListsPolicy>().CatalogItems); importItems.Add(item); } return(item); }
public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context) { Condition.Requires(entityView).IsNotNull(string.Format($"{Name}: The argument cannot be null")); if (string.IsNullOrEmpty(entityView.Action)) { return(entityView); } CommerceEntity commerceEntity = context.CommerceContext.GetObject <CommerceEntity>(p => p.Id.Equals(entityView.EntityId, StringComparison.OrdinalIgnoreCase)); SellableItem sellableItem = commerceEntity as SellableItem; if (entityView.Action.Equals("EditSellableItemSpecifications", StringComparison.OrdinalIgnoreCase)) { if (entityView.ContainsProperty(Constants.LoyaltyPoints)) { string s = entityView.Properties.FirstOrDefault(p => p.Name.Equals(Constants.LoyaltyPoints, StringComparison.OrdinalIgnoreCase))?.Value; if (int.TryParse(s, out var value)) { sellableItem.GetComponent <LoyaltyPointsComponent>().Points = value; await _editSellableItemCommand.Process(context.CommerceContext, sellableItem); } } } return(entityView); }
/// <summary> /// Retrieves all component types applicable for the sellable item /// </summary> /// <param name="context"></param> /// <param name="sellableItem">Sellable item for which to get the applicable components</param> /// <returns></returns> public async Task <List <Type> > GetApplicableComponentTypes(CommerceContext context, SellableItem sellableItem) { // Get the item definition var catalogs = sellableItem.GetComponent <CatalogsComponent>(); // TODO: What happens if a sellableitem is part of multiple catalogs? var catalog = catalogs.GetComponent <CatalogComponent>(); var itemDefinition = catalog.ItemDefinition; var sellableItemComponentsArgument = new SellableItemComponentsArgument(); sellableItemComponentsArgument = await this.Pipeline <IGetSellableItemComponentsPipeline>().Run(sellableItemComponentsArgument, context.GetPipelineContext()); var applicableComponentTypes = new List <Type>(); foreach (var component in sellableItemComponentsArgument.SellableItemComponents) { System.Attribute[] attrs = System.Attribute.GetCustomAttributes(component); if (attrs.Any(attr => attr is AllSellableItemsAttribute)) { applicableComponentTypes.Add(component); } else if (attrs.Any(attr => attr is ItemDefinitionAttribute && ((ItemDefinitionAttribute)attr).ItemDefinition == itemDefinition)) { applicableComponentTypes.Add(component); } } return(applicableComponentTypes); }
private static async Task GetProductId(CommercePipelineExecutionContext context, GetProductsToUpdateInventoryBlock getProductsToUpdateInventoryBlock, string catalogSitecoreId, List <string> productIds, SellableItem item) { if (item.ParentCatalogList == catalogSitecoreId) { CommerceEntity entity = await getProductsToUpdateInventoryBlock._findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), item.Id, false), context); if ((entity is SellableItem)) { SellableItem sellableItem = entity as SellableItem; var variants = sellableItem.GetComponent <ItemVariationsComponent>(); if (variants != null && variants.ChildComponents.Count > 0) { foreach (ItemVariationComponent variant in variants.ChildComponents) { var variantData = variant; productIds.Add($"{item.Id}|{variantData.Id}"); } } else { productIds.Add($"{item.Id}"); } } } }
private static void MapImages(SellableItem sellableItem, CsvImportLine csvImportLine) { var imagesComponent = sellableItem.GetComponent <ImagesComponent>(); foreach (var image in csvImportLine.Images) { if (imagesComponent.Images.All(x => x != image)) { imagesComponent.Images.Add(image); } } }
protected async virtual Task <string> GetInventoryStatus(string inventorySetName, SellableItem sellableItem, string variantId, CommercePipelineExecutionContext context) { if (sellableItem.IsBundle) { // TODO: Implement support for bundle return("Not Supported"); } if (sellableItem.HasPolicy <AvailabilityAlwaysPolicy>()) { return(Engine.CatalogConstants.InventoryStatus.Perpetual); } if (string.IsNullOrWhiteSpace(variantId) && !string.IsNullOrWhiteSpace(inventorySetName)) { var inventoryInformation = await Commander.Command <GetInventoryInformationCommand>().Process(context.CommerceContext, inventorySetName, sellableItem.ProductId).ConfigureAwait(false); if (inventoryInformation != null) { return(this.ToInventoryStatus(inventoryInformation)); } } if (string.IsNullOrWhiteSpace(variantId)) { var variants = sellableItem.GetComponent <ItemVariationsComponent>().GetComponents <ItemVariationComponent>(); var allNotAvailable = true; foreach (var variant in variants) { var status = await GetVariantInventoryStatus(variant, inventorySetName, context).ConfigureAwait(false); allNotAvailable &= status.Equals(Engine.CatalogConstants.InventoryStatus.NotAvailable, StringComparison.InvariantCultureIgnoreCase); if (status.Equals(Engine.CatalogConstants.InventoryStatus.NotAvailable, StringComparison.InvariantCultureIgnoreCase) || status.Equals(Engine.CatalogConstants.InventoryStatus.OutOfStock, StringComparison.InvariantCultureIgnoreCase)) { continue; } return(status); } return(allNotAvailable ? Engine.CatalogConstants.InventoryStatus.NotAvailable : Engine.CatalogConstants.InventoryStatus.OutOfStock); } else { var variant = sellableItem.GetVariation(variantId); return(await GetVariantInventoryStatus(variant, inventorySetName, context).ConfigureAwait(false)); } }
public static ProductExtensionComponent GetProductExtensionComponent(SellableItem instance, string variationId) { ItemVariationComponent variation = instance.GetVariation(variationId); if (variation.HasComponent <ProductExtensionComponent>() == false) { var component = instance.GetComponent <ProductExtensionComponent>().Clone(); variation.SetComponent(component); return(component); } else { return(variation.GetComponent <ProductExtensionComponent>()); } }
void DrawUpgradeScreen(Rect drawRect, GUIStyle style) { GUI.BeginGroup(drawRect); GUI.DrawTexture(new Rect(0, 0, drawRect.width, drawRect.height), backGround); XMLVendorReader vendorReader = GameObject.Find("XMLReader").GetComponent <XMLVendorReader>(); SellableItem sellItem = null; if (curItem.GetComponent <SellableItem>().upgradedItem) { sellItem = curItem.GetComponent <SellableItem>().upgradedItem.GetComponent <SellableItem>(); } if (sellItem != null) { if (sellItem.currentUpgrade <= 2) { sellItem.cost = vendorReader.GetCurrentFortificationCost(sellItem.cost, sellItem.itemName, sellItem.currentUpgrade); } if (GameController.Instance.GetResources() >= sellItem.cost) { if (GUI.Button(new Rect(drawRect.width - 180, drawRect.height - 250, 150, 50), "UPGRADE: " + sellItem.cost, style)) { itemVendor.Upgrade(curItem); } GUI.Label(new Rect(drawRect.width - 200, drawRect.height - 200, 200, 100), sellItem.GetComponent <SellableItem>().description, descriptionStyle); } else { GUI.Label(new Rect(drawRect.width - 180, drawRect.height - 250, 150, 50), "NOT ENOUGH FUNDS", style); } } else { GUI.Label(new Rect(drawRect.width - 180, drawRect.height - 250, 150, 50), "FULLY UPGRADED", style); } if (GUI.Button(new Rect(drawRect.width - 150, drawRect.height - 100, 100, 50), "BACK", style)) { state = State.FORTINFO; } GUI.EndGroup(); }
/// <summary> /// Ensures the SellableItem exists and creates it if it doesn't. /// Adds/updates the product identifiers and Brand. /// </summary> /// <param name="arg">The arg.</param> /// <param name="context">The context.</param> /// <returns>The arg with an updated SellableItem property.</returns> public override async Task <SynchronizeProductArgument> Run(SynchronizeProductArgument arg, CommercePipelineExecutionContext context) { var syncForceClientPolicy = context.GetPolicy <SyncForceClientPolicy>(); var validMasterCode = arg.MasterProduct.MasterCode.ProposeValidId(); var sellableItemId = $"{CommerceEntity.IdPrefix<SellableItem>()}{validMasterCode}"; SellableItem sellableItem = null; if (await _doesEntityExistPipeline.Run(new FindEntityArgument(typeof(SellableItem), sellableItemId), context.CommerceContext.PipelineContextOptions)) { sellableItem = await _getSellableItemPipeline.Run(new ProductArgument { CatalogName = "", ProductId = sellableItemId }, context.CommerceContext.PipelineContextOptions); } else { var createResult = (await _createSellableItemPipeline.Run(new CreateSellableItemArgument(arg.MasterProduct.MasterCode.ProposeValidId(), arg.MasterProduct.MasterCode, arg.MasterProduct.MasterCode, string.Empty), context.CommerceContext.PipelineContextOptions)); sellableItem = createResult?.SellableItems?.FirstOrDefault(s => s.Id == sellableItemId); Condition.Requires <SellableItem>(sellableItem).IsNotNull($"{this.Name}: The SellableItem could not be created."); } //Sitecore should have set this to true, issue created #514238 sellableItem.IsPersisted = true; //Add Base properties sellableItem.Brand = arg.MasterProduct.Brand.Name; //Clear Tags sellableItem.Tags.Clear(); //Add identifiers var identifiersComponent = sellableItem.GetComponent <IdentifiersComponent>(); identifiersComponent.SKU = arg.MasterProduct.MasterCode; if (!identifiersComponent.CustomId.Any(i => i.Key.Equals(syncForceClientPolicy.CustomIdentifierKey))) { identifiersComponent.CustomId.Add(new Models.CustomIdentifier(syncForceClientPolicy.CustomIdentifierKey, arg.MasterProduct.Id.ToString())); } sellableItem.SetComponent(identifiersComponent); sellableItem = (await _persistEntityPipeline.Run(new PersistEntityArgument(sellableItem), context.CommerceContext.PipelineContextOptions))?.Entity as SellableItem ?? sellableItem; arg.SellableItem = sellableItem; arg.SellableItems?.Add(sellableItem); return(arg); }
private void EditProperties(EntityView entityView, SellableItem entity) { if (entity == null) { return; } List <ViewProperty> properties = entityView.Properties; ViewProperty viewProperty = new ViewProperty(); viewProperty.Name = Constants.LoyaltyPoints; viewProperty.RawValue = entity.GetComponent <LoyaltyPointsComponent>().Points; viewProperty.IsReadOnly = false; viewProperty.IsRequired = false; viewProperty.IsHidden = false; properties.Add(viewProperty); }
private void TransformCore(CommerceContext commerceContext, string[] rawFields, SellableItem item) { item.ProductId = rawFields[ProductIdIndex]; item.Id = item.ProductId.ToEntityId <SellableItem>(); item.FriendlyId = item.ProductId; item.Name = rawFields[ProductNameIndex]; /// Be sure not to include SitecoreId in <see cref="ProductExtensionComponentComparer"/> item.SitecoreId = GuidUtils.GetDeterministicGuidString(item.Id); item.DisplayName = rawFields[DisplayNameIndex]; item.Description = rawFields[DescriptionIndex]; item.Brand = rawFields[BrandIndex]; item.Manufacturer = rawFields[ManufacturerIndex]; item.TypeOfGood = rawFields[TypeOfGoodIndex]; var tags = string.IsNullOrEmpty(rawFields[TagsIndex]) ? null : rawFields[TagsIndex].Split('|'); item.Tags = tags == null ? new List <Tag>() : tags.Select(x => new Tag(x)).ToList(); var component = item.GetComponent <ListMembershipsComponent>(); component.Memberships.Add(string.Format("{0}", CommerceEntity.ListName <SellableItem>())); component.Memberships.Add(commerceContext.GetPolicy <KnownCatalogListsPolicy>().CatalogItems); }
/// <summary> /// Updates variants entity view /// </summary> /// <param name="variantsView">The variants view.</param> /// <param name="sellableItem">The sellable item.</param> /// <param name="context">The context.</param> protected virtual void UpdateVariantsView(EntityView variantsView, SellableItem sellableItem, CommercePipelineExecutionContext context) { if (variantsView == null) { return; } var variations = sellableItem.GetComponent <ItemVariationsComponent>().ChildComponents.OfType <ItemVariationComponent>().ToList(); if (variations != null && variations.Count <= 0) { return; } var variationPropertyPolicy = context.CommerceContext.Environment.GetPolicy <VariationPropertyPolicy>(); foreach (var variation in variations) { var variationView = variantsView.ChildViews.FirstOrDefault(c => ((EntityView)c).ItemId == variation.Id) as EntityView; PopulateVariationProperties(variationView, variation, variationPropertyPolicy); } }
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 CreateExampleBundles(CommercePipelineExecutionContext context) { // First bundle SellableItem bundle1 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001001", "SmartWiFiBundle", "Smart WiFi Bundle", string.Empty, string.Empty, string.Empty, string.Empty, new[] { "smart", "wifi", "bundle" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042964|56042964", Quantity = 1 }, new BundleItem { SellableItemId = "Entity-SellableItem-6042971|56042971", Quantity = 1 } }).ConfigureAwait(false); // Set image and list price for bundle bundle1.GetComponent <ImagesComponent>().Images.Add("65703328-1456-48da-a693-bad910d7d1fe"); bundle1.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 200.00M), new Money("CAD", 250.00M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle1), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-Connected home", bundle1.Id).ConfigureAwait(false); // Second bundle SellableItem bundle2 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001002", "ActivityTrackerCameraBundle", "Activity Tracker & Camera Bundle", "Sample bundle containting two activity trackers and two cameras.", "Striva Wearables", string.Empty, string.Empty, new[] { "activitytracker", "camera", "bundle" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042896|56042896", Quantity = 2 }, new BundleItem { SellableItemId = "Entity-SellableItem-7042066|57042066", Quantity = 2 } }).ConfigureAwait(false); // Set image and list price for bundle bundle2.GetComponent <ImagesComponent>().Images.Add("003c9ee5-2d97-4a6c-bb9e-24e110cd7645"); bundle2.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 220.00M), new Money("CAD", 280.00M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle2), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-Fitness Activity Trackers", bundle2.Id).ConfigureAwait(false); // Third bundle SellableItem bundle3 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001003", "RefrigeratorFlipPhoneBundle", "Refrigerator & Flip Phone Bundle", "Sample bundle containting a refrigerator and two flip phones.", "Viva Refrigerators", string.Empty, string.Empty, new[] { "refrigerator", "flipphone", "bundle" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042567|56042568", Quantity = 1 }, new BundleItem { SellableItemId = "Entity-SellableItem-6042331|56042331", Quantity = 2 }, new BundleItem { SellableItemId = "Entity-SellableItem-6042896|56042896", Quantity = 3 }, new BundleItem { SellableItemId = "Entity-SellableItem-7042066|57042066", Quantity = 4 } }).ConfigureAwait(false); // Set image and list price for bundle bundle3.GetComponent <ImagesComponent>().Images.Add("372d8bc6-6888-4375-91c1-f3bee2d31558"); bundle3.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 10.00M), new Money("CAD", 20.00M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle3), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-Appliances", bundle3.Id).ConfigureAwait(false); // Fourth bundle with digital items SellableItem bundle4 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001004", "GiftCardAndSubscriptionBundle", "Gift Card & Subscription Bundle", "Sample bundle containting a gift card and two subscriptions.", string.Empty, string.Empty, string.Empty, new[] { "bundle", "giftcard", "entitlement" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042986|56042987", Quantity = 1 }, new BundleItem { SellableItemId = "Entity-SellableItem-6042453|56042453", Quantity = 2 } }).ConfigureAwait(false); // Set image and list price for bundle bundle4.GetComponent <ImagesComponent>().Images.Add("7b57e6e0-a4ef-417e-809c-572f2e30aef7"); bundle4.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 10.00M), new Money("CAD", 20.00M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle4), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping", bundle4.Id).ConfigureAwait(false); // Preorderable bundle SellableItem bundle5 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001005", "PreorderableBundle", "Preorderable Bundle", "Sample bundle containting a phone and headphones.", string.Empty, string.Empty, string.Empty, new[] { "bundle" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042305|56042305", Quantity = 1 }, new BundleItem { SellableItemId = "Entity-SellableItem-6042059|56042059", Quantity = 1 } }).ConfigureAwait(false); // Set image and list price for bundle bundle5.GetComponent <ImagesComponent>().Images.Add("b0b07d7b-ddaf-4798-8eb9-af7f570af3fe"); bundle5.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 44.99M), new Money("CAD", 59.99M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle5), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-Phones", bundle5.Id).ConfigureAwait(false); // Backorderable bundle SellableItem bundle6 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001006", "BackorderableBundle", "Backorderable Bundle", "Sample bundle containting a phone and headphones.", string.Empty, string.Empty, string.Empty, new[] { "bundle" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042305|56042305", Quantity = 1 }, new BundleItem { SellableItemId = "Entity-SellableItem-6042058|56042058", Quantity = 1 } }).ConfigureAwait(false); // Set image and list price for bundle bundle6.GetComponent <ImagesComponent>().Images.Add("b0b07d7b-ddaf-4798-8eb9-af7f570af3fe"); bundle6.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 44.99M), new Money("CAD", 59.99M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle6), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-Phones", bundle6.Id).ConfigureAwait(false); // Backorderable bundle SellableItem bundle7 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001007", "PreorderableBackorderableBundle", "Preorderable / Backorderable Bundle", "Sample bundle containting headphones.", string.Empty, string.Empty, string.Empty, new[] { "bundle" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042058|56042058", Quantity = 1 }, new BundleItem { SellableItemId = "Entity-SellableItem-6042059|56042059", Quantity = 1 } }).ConfigureAwait(false); // Set image and list price for bundle bundle7.GetComponent <ImagesComponent>().Images.Add("b0b07d7b-ddaf-4798-8eb9-af7f570af3fe"); bundle7.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 44.99M), new Money("CAD", 59.99M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle7), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-Audio", bundle7.Id).ConfigureAwait(false); // Eigth bundle with a gift card only SellableItem bundle8 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001008", "GiftCardBundle", "Gift Card Bundle", "Sample bundle containting a gift card.", string.Empty, string.Empty, string.Empty, new[] { "bundle", "entitlement", "giftcard" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042986|56042987", Quantity = 1 } }).ConfigureAwait(false); // Set image and list price for bundle bundle8.GetComponent <ImagesComponent>().Images.Add("7b57e6e0-a4ef-417e-809c-572f2e30aef7"); bundle8.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 40.00M), new Money("CAD", 50.00M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle8), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping", bundle8.Id).ConfigureAwait(false); // Warranty bundle SellableItem bundle9 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001009", "WarrantyBundle", "Warranty Bundle", "Sample bundle containting a warranty.", string.Empty, string.Empty, string.Empty, new[] { "bundle", "warranty" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-7042259|57042259", Quantity = 1 } }).ConfigureAwait(false); // Set image and list price for bundle bundle9.GetComponent <ImagesComponent>().Images.Add("eebf49f2-74df-4fe6-b77f-f2d1d447827c"); bundle9.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 150.00M), new Money("CAD", 200.00M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle9), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping", bundle9.Id).ConfigureAwait(false); // Service bundle SellableItem bundle10 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001010", "ServiceBundle", "Service Bundle", "Sample bundle containting a service.", string.Empty, string.Empty, string.Empty, new[] { "bundle", "service" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042418|56042418", Quantity = 1 } }).ConfigureAwait(false); // Set image and list price for bundle bundle10.GetComponent <ImagesComponent>().Images.Add("8b59fe2a-c234-4f92-b84b-7515411bf46e"); bundle10.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 150.00M), new Money("CAD", 200.00M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle10), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping", bundle10.Id).ConfigureAwait(false); // Subscription bundle SellableItem bundle11 = await _commerceCommander.Command <CreateBundleCommand>().Process( context.CommerceContext, "Static", "6001011", "SubscriptionBundle", "Subscription Bundle", "Sample bundle containting a subscription.", string.Empty, string.Empty, string.Empty, new[] { "bundle", "subscription" }, new List <BundleItem> { new BundleItem { SellableItemId = "Entity-SellableItem-6042453|56042453", Quantity = 1 } }).ConfigureAwait(false); // Set image and list price for bundle bundle11.GetComponent <ImagesComponent>().Images.Add("22d74215-8e5f-4de3-a9d6-ece3042bd64c"); bundle11.SetPolicy( new ListPricingPolicy( new List <Money> { new Money("USD", 10.00M), new Money("CAD", 15.00M) })); await _commerceCommander.Pipeline <IPersistEntityPipeline>() .Run(new PersistEntityArgument(bundle11), context).ConfigureAwait(false); // Associate bundle to parent category await _commerceCommander.Command <AssociateSellableItemToParentCommand>().Process( context.CommerceContext, "Entity-Catalog-Habitat_Master", "Entity-Category-Habitat_Master-eGift Cards and Gift Wrapping", bundle11.Id).ConfigureAwait(false); }
public async Task <ItemType> RelistItem(CommerceContext commerceContext, SellableItem sellableItem) { using (CommandActivity.Start(commerceContext, this)) { var apiCall = new eBay.Service.Call.RelistItemCall(await this.GetEbayContext(commerceContext)); if (sellableItem.HasComponent <EbayItemComponent>()) { var ebayItemComponent = sellableItem.GetComponent <EbayItemComponent>(); try { var item = await this.PrepareItem(commerceContext, sellableItem); item.ItemID = ebayItemComponent.EbayId; // 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}"); 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); } } } else { commerceContext.Logger.LogError("EbayCommand.RelistItem.Exception: Message=ebayCommand.RelistItem.NoEbayItemComponent"); await commerceContext.AddMessage("Error", "Ebay.RelistItem.Exception", new object[] { }, "ebayCommand.RelistItem.NoEbayItemComponent"); } return(new ItemType()); } }
private void CopyProductExtension(SellableItem itemNewData, SellableItem item) { item.RemoveComponent(typeof(ProductExtensionComponent)); item.Components.Add(itemNewData.GetComponent <ProductExtensionComponent>()); }
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 override async Task <Order> Run(OfflineStoreOrderArgument arg, CommercePipelineExecutionContext context) { CreateOfflineOrderBlock createOrderBlock = this; Condition.Requires(arg).IsNotNull($"{createOrderBlock.Name}: arg can not be null"); CommercePipelineExecutionContext executionContext; if (string.IsNullOrEmpty(arg.Email)) { executionContext = context; executionContext.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, "EmailIsRequired", new object[1], "Can not create order, email address is required.").ConfigureAwait(false), context); executionContext = null; return(null); } if (!arg.Lines.Any()) { executionContext = context; CommerceContext commerceContext = context.CommerceContext; string error = context.GetPolicy <KnownResultCodes>().Error; string commerceTermKey = "OrderHasNoLines"; string defaultMessage = "Can not create order, cart has no lines"; executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, null, defaultMessage).ConfigureAwait(false), context); executionContext = null; return(null); } // Find contact using email string email = arg.Email; ContactComponent contactComponent = new ContactComponent(); EntityIndex entityIndex = await createOrderBlock._findEntityPipeline .Run(new FindEntityArgument(typeof(EntityIndex), string.Format("{0}{1}\\{2}", EntityIndex.IndexPrefix <Customer>("Id"), arg.Domain, arg.Email)), context) .ConfigureAwait(false) as EntityIndex; if (entityIndex != null) { var customerEntityId = entityIndex.EntityId; Customer entityCustomer = await createOrderBlock._findEntityPipeline .Run(new FindEntityArgument(typeof(Customer), customerEntityId), context) .ConfigureAwait(false) as Customer; if (entityCustomer != null) { contactComponent.IsRegistered = true; contactComponent.CustomerId = entityCustomer.Id; contactComponent.ShopperId = entityCustomer.Id; contactComponent.Name = entityCustomer.Name; } } contactComponent.Email = email; KnownOrderListsPolicy policy1 = context.GetPolicy <KnownOrderListsPolicy>(); string orderId = string.Format("{0}{1:N}", CommerceEntity.IdPrefix <Order>(), Guid.NewGuid()); Order storeOrder = new Order(); storeOrder.Components = new List <Component>(); storeOrder.Id = orderId; Totals totals = new Totals() { GrandTotal = new Money(arg.CurrencyCode, arg.GrandTotal), SubTotal = new Money(arg.CurrencyCode, arg.SubTotal), AdjustmentsTotal = new Money(arg.CurrencyCode, arg.Discount), PaymentsTotal = new Money(arg.CurrencyCode, arg.GrandTotal) }; storeOrder.Totals = totals; IList <CartLineComponent> lines = new List <CartLineComponent>(); foreach (var line in arg.Lines) { var items = line.ItemId.Split('|'); CommerceEntity entity = await createOrderBlock._findEntityPipeline .Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-" + (items.Count() > 2 ? items[1] : line.ItemId), false), context) .ConfigureAwait(false); CartLineComponent lineComponent = new CartLineComponent { ItemId = line.ItemId, Quantity = line.Quantity, Totals = new Totals() { SubTotal = new Money(arg.CurrencyCode, line.SubTotal), GrandTotal = new Money(arg.CurrencyCode, line.SubTotal) }, UnitListPrice = new Money() { CurrencyCode = arg.CurrencyCode, Amount = line.UnitListPrice }, Id = Guid.NewGuid().ToString("N"), //Policies = new List<Policy>() //todo: determine if this is required }; lineComponent.Policies.Add(new PurchaseOptionMoneyPolicy() { PolicyId = "c24f0ed4f2f1449b8a488403b6bf368a", SellPrice = new Money() { CurrencyCode = arg.CurrencyCode, Amount = line.SubTotal } }); if (entity is SellableItem) { SellableItem sellableItem = entity as SellableItem; lineComponent.ChildComponents.Add(new CartProductComponent() { DisplayName = line.ProductName, Id = items.Count() > 2 ? items[1] : line.ItemId, Image = new Image() { ImageName = line.ProductName, AltText = line.ProductName, Height = 50, Width = 50, SitecoreId = sellableItem.GetComponent <ImagesComponent>().Images.FirstOrDefault() } }); } // if it has a variant if (items.Count() > 2) { // Set VariantionId lineComponent.ChildComponents.Add(new ItemVariationSelectedComponent() { VariationId = items[2] }); } lines.Add(lineComponent); } storeOrder.Lines = lines; IList <AwardedAdjustment> adjustments = new List <AwardedAdjustment>(); if (arg.Discount > 0) { var discountAdjustment = new CartLevelAwardedAdjustment { AdjustmentType = "Discount", Adjustment = new Money(arg.CurrencyCode, -arg.Discount), IsTaxable = false, IncludeInGrandTotal = true, Name = "Discount", AwardingBlock = "In Store Discount" }; adjustments.Add(discountAdjustment); } if (arg.TaxTotal > 0) { var taxAdjustment = new CartLevelAwardedAdjustment { AdjustmentType = "Tax", Adjustment = new Money(arg.CurrencyCode, arg.TaxTotal), IsTaxable = false, IncludeInGrandTotal = true, Name = "TaxFee", AwardingBlock = "Tax:block:calculatecarttax" }; adjustments.Add(taxAdjustment); } storeOrder.Adjustments = adjustments; // Payment FederatedPaymentComponent paymentComponent = new FederatedPaymentComponent(new Money(arg.CurrencyCode, arg.GrandTotal)) { PaymentInstrumentType = arg.PaymentInstrumentType, CardType = arg.CardType, ExpiresMonth = arg.ExpiresMonth, ExpiresYear = arg.ExpiresYear, TransactionId = arg.TransactionId, TransactionStatus = arg.TransactionStatus, MaskedNumber = arg.MaskedNumber, Amount = new Money(arg.CurrencyCode, arg.GrandTotal), Comments = "Store Payment", PaymentMethod = new EntityReference("Card", new Guid().ToString()), BillingParty = new Party(), Name = "Store Payment" }; storeOrder.Components.Add(paymentComponent); // Fulfillment PhysicalFulfillmentComponent physicalFulfillmentComponent = new PhysicalFulfillmentComponent { //ShippingParty = new Party() { AddressName = arg.StoreDetails.Name, Address1 = arg.StoreDetails.Address, City = arg.StoreDetails.City, State = arg.StoreDetails.State, // StateCode = arg.StoreDetails.State, Country =arg.StoreDetails.Country, CountryCode = arg.StoreDetails.Country, ZipPostalCode = arg.StoreDetails.ZipCode.ToString(), ExternalId = "0" }, FulfillmentMethod = new EntityReference() { Name = "Offline Store Order By Customer", EntityTarget = "b146622d-dc86-48a3-b72a-05ee8ffd187a" } }; var shippingParty = new FakeParty() { AddressName = arg.StoreDetails.Name, Address1 = arg.StoreDetails.Address, City = arg.StoreDetails.City, State = arg.StoreDetails.State, StateCode = arg.StoreDetails.State, Country = arg.StoreDetails.Country, CountryCode = arg.StoreDetails.Country, ZipPostalCode = arg.StoreDetails.ZipCode.ToString(), ExternalId = "0" }; // Have to do the following because we cannot set external id on party directly var tempStorage = JsonConvert.SerializeObject(shippingParty); Party party = JsonConvert.DeserializeObject <Party>(tempStorage); physicalFulfillmentComponent.ShippingParty = party; storeOrder.Components.Add(physicalFulfillmentComponent); storeOrder.Components.Add(contactComponent); storeOrder.Name = "InStoreOrder"; storeOrder.ShopName = arg.ShopName; storeOrder.FriendlyId = orderId; storeOrder.OrderConfirmationId = arg.OrderConfirmationId; storeOrder.OrderPlacedDate = Convert.ToDateTime(arg.OrderPlacedDate); //string createdOrderStatus = policy2.CreatedOrderStatus; storeOrder.Status = arg.Status; Order order = storeOrder; string str3 = contactComponent.IsRegistered ? policy1.AuthenticatedOrders : policy1.AnonymousOrders; ListMembershipsComponent membershipsComponent1 = new ListMembershipsComponent() { Memberships = new List <string>() { CommerceEntity.ListName <Order>(), str3 } }; if (contactComponent.IsRegistered && !string.IsNullOrEmpty(contactComponent.CustomerId)) { membershipsComponent1.Memberships.Add(string.Format(context.GetPolicy <KnownOrderListsPolicy>().CustomerOrders, contactComponent.CustomerId)); } order.SetComponent(membershipsComponent1); Order order2 = order; TransientListMembershipsComponent membershipsComponent2 = new TransientListMembershipsComponent(); membershipsComponent2.Memberships = new List <string>() { policy1.PendingOrders }; context.Logger.LogInformation(string.Format("Offline Orders.ImportOrder: OrderId={0}|GrandTotal={1} {2}", orderId, order.Totals.GrandTotal.CurrencyCode, order.Totals.GrandTotal.Amount), Array.Empty <object>()); context.CommerceContext.AddModel(new CreatedOrder() { OrderId = orderId }); Dictionary <string, double> dictionary = new Dictionary <string, double>() { { "GrandTotal", Convert.ToDouble(order.Totals.GrandTotal.Amount, System.Globalization.CultureInfo.InvariantCulture) } }; createOrderBlock._telemetryClient.TrackEvent("OrderCreated", null, dictionary); int orderTotal = Convert.ToInt32(Math.Round(order.Totals.GrandTotal.Amount, 0), System.Globalization.CultureInfo.InvariantCulture); if (context.GetPolicy <PerformancePolicy>().WriteCounters) { int num1 = await createOrderBlock._performanceCounterCommand.IncrementBy("SitecoreCommerceMetrics", "MetricCount", string.Format("Orders.GrandTotal.{0}", order.Totals.GrandTotal.CurrencyCode), orderTotal, context.CommerceContext).ConfigureAwait(false) ? 1 : 0; int num2 = await createOrderBlock._performanceCounterCommand.Increment("SitecoreCommerceMetrics", "MetricCount", "Orders.Count", context.CommerceContext).ConfigureAwait(false) ? 1 : 0; } return(order); }
private void CopyImages(SellableItem itemNewData, SellableItem item) { item.RemoveComponent(typeof(ImagesComponent)); item.Components.Add(itemNewData.GetComponent <ImagesComponent>()); }
protected async virtual Task <PricingModel> CreatePricingModel(SellableItem sellableItem, string variantId, CommercePipelineExecutionContext context) { PricingModel pricingModel = null; if (string.IsNullOrWhiteSpace(variantId)) { pricingModel = new PricingModel(sellableItem.ListPrice, sellableItem.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice, sellableItem.GetComponent <MessagesComponent>()); } else { var variation = sellableItem.GetVariation(variantId); if (variation == null) { return(await Task.FromResult(pricingModel).ConfigureAwait(false)); } pricingModel = new PricingModel(variation.ListPrice, variation.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice, variation.GetComponent <MessagesComponent>()); } return(await Task.FromResult(pricingModel).ConfigureAwait(false)); }
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); }
public async Task <ItemType> AddItem(CommerceContext commerceContext, SellableItem sellableItem) { using (var activity = CommandActivity.Start(commerceContext, this)) { var ebayItemComponent = sellableItem.GetComponent <EbayItemComponent>(); try { //Instantiate the call wrapper class var apiCall = new AddFixedPriceItemCall(await GetEbayContext(commerceContext).ConfigureAwait(false)); var item = await PrepareItem(commerceContext, sellableItem).ConfigureAwait(false); //Send the call to eBay and get the results FeeTypeCollection feeTypeCollection = apiCall.AddFixedPriceItem(item); foreach (var feeItem in feeTypeCollection) { 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 Added", EventUser = commerceContext.CurrentCsrId() }); ebayItemComponent.EbayId = item.ItemID; ebayItemComponent.Status = "Listed"; sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Listed"); await commerceContext.AddMessage("Info", "EbayCommand.AddItem", new [] { item.ItemID }, $"Item Listed:{item.ItemID}").ConfigureAwait(false); 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", "EbayCommand.AddItem", new [] { existingId }, $"ExistingId:{existingId}-ComponentId:{ebayItemComponent.EbayId}").ConfigureAwait(false); ebayItemComponent.EbayId = existingId; ebayItemComponent.Status = "Listed"; ebayItemComponent.History.Add(new HistoryEntryModel { EventMessage = "Existing Listing Linked", EventUser = commerceContext.CurrentCsrId() }); sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Listed"); } else { commerceContext.Logger.LogError($"Ebay.AddItem.Exception: Message={ex.Message}"); await commerceContext.AddMessage("Error", "Ebay.AddItem.Exception", new [] { ex }, ex.Message).ConfigureAwait(false); ebayItemComponent.History.Add(new HistoryEntryModel { EventMessage = $"Error-{ex.Message}", EventUser = commerceContext.CurrentCsrId() }); } } 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); } }
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); }