public override async Task <Order> Run(Order arg, CommercePipelineExecutionContext context) { if (arg == null) { return(null); } var messageEntity = new MessageEntity { Id = CommerceEntity.IdPrefix <MessageEntity>() + Guid.NewGuid().ToString("N"), Name = "tryry" }; messageEntity.GetComponent <ListMembershipsComponent>().Memberships.Add(CommerceEntity.ListName <MessageEntity>()); messageEntity.History.Add(new HistoryEntryModel { Name = messageEntity.Name, EventMessage = $"An Order was completed" }); var contactComponent = arg.GetComponent <ContactComponent>(); messageEntity.Components.Add(contactComponent); messageEntity.Models.Add(arg.Totals); messageEntity.Models.Add(new OrderSummaryModel { ConfirmationId = arg.OrderConfirmationId, OrderId = arg.Id, Status = arg.Status }); await this._commerceCommander.PersistEntity(context.CommerceContext, messageEntity); return(arg); }
public override async Task <SynchronizeCatalogArgument> Run(SynchronizeCatalogArgument arg, CommercePipelineExecutionContext context) { Sitecore.Commerce.Plugin.Catalog.Catalog catalog = null; var catalogId = arg.Proposition.Name.ProposeValidId() .EnsurePrefix(CommerceEntity.IdPrefix <Sitecore.Commerce.Plugin.Catalog.Catalog>()); if (await _doesEntityExistPipeline.Run( new FindEntityArgument(typeof(Sitecore.Commerce.Plugin.Catalog.Catalog), catalogId), context.CommerceContext.PipelineContextOptions)) { catalog = await _getCatalogPipeline.Run(new GetCatalogArgument(arg.Proposition.Name.ProposeValidId()), context.CommerceContext.PipelineContextOptions); } else { var createResult = await _createCatalogPipeline.Run(new CreateCatalogArgument(arg.Proposition.Name.ProposeValidId(), arg.Proposition.Name), context.CommerceContext.PipelineContextOptions); catalog = createResult?.Catalog; } Condition.Requires <Sitecore.Commerce.Plugin.Catalog.Catalog>(catalog).IsNotNull($"{this.Name}: The Catalog could not be created."); arg.CatalogId = catalog?.Id; arg.Catalog = catalog; return(arg); }
public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context) { if (entityView == null || !entityView.Action.Equals("VatTaxDashboard-AddDashboardEntity", StringComparison.OrdinalIgnoreCase)) { return(entityView); } try { var taxTag = entityView.Properties.First(p => p.Name == "TaxTag").Value ?? ""; var countryCode = entityView.Properties.First(p => p.Name == "CountryCode").Value ?? ""; var taxPct = System.Convert.ToDecimal(entityView.Properties.First(p => p.Name == "TaxPct").Value ?? "0"); var sampleDashboardEntity = new VatTaxTableEntity { Id = CommerceEntity.IdPrefix <VatTaxTableEntity>() + Guid.NewGuid().ToString("N"), Name = string.Empty, TaxTag = taxTag, CountryCode = countryCode, TaxPct = taxPct }; sampleDashboardEntity.GetComponent <ListMembershipsComponent>().Memberships.Add(CommerceEntity.ListName <VatTaxTableEntity>()); await this._commerceCommander.PersistEntity(context.CommerceContext, sampleDashboardEntity); } catch (Exception ex) { context.Logger.LogError($"Catalog.DoActionAddDashboardEntity.Exception: Message={ex.Message}"); } return(entityView); }
private async Task <PriceCard> UpdateOrCreatePriceCard(CommercePipelineExecutionContext context, PriceBook priceBook, string priceCardName, string displayName = "", string description = "") { var cardId = string.Format("{0}{1}-{2}", CommerceEntity.IdPrefix <PriceCard>(), priceBook.Name, priceCardName); var priceCard = await _findEntityPipeline.Run(new FindEntityArgument(typeof(PriceCard), cardId), context).ConfigureAwait(false) as PriceCard; if (priceCard != null) { return(priceCard); } var priceCardArgument = new AddPriceCardArgument(priceBook, priceCardName) { Description = description, DisplayName = displayName }; var createdPriceCard = await _addPriceCardPipeline.Run(priceCardArgument, context) .ConfigureAwait(false); if (createdPriceCard != null) { priceCard = createdPriceCard; } return(priceCard); }
public override async Task <SynchronizeProductArgument> Run(SynchronizeProductArgument arg, CommercePipelineExecutionContext context) { Sitecore.Commerce.Plugin.Catalog.SellableItem product = null; var productId = arg.ImportProduct.ProductId.ProposeValidId() .EnsurePrefix(CommerceEntity.IdPrefix <Sitecore.Commerce.Plugin.Catalog.SellableItem>()); if (await _doesEntityExistPipeline.Run( new FindEntityArgument(typeof(Sitecore.Commerce.Plugin.Catalog.SellableItem), productId), context.CommerceContext.GetPipelineContextOptions())) { product = await _getSellableItemPipeline.Run(new ProductArgument(arg.Catalog.Id, productId), context.CommerceContext.GetPipelineContextOptions()); } else { var productName = arg.ImportProduct.ProductName.FirstOrDefault()?.Name; var createResult = await _createSellableItemPipeline.Run( new CreateSellableItemArgument(arg.ImportProduct.ProductId.ProposeValidId(), arg.ImportProduct.ProductId, productName, ""), context.CommerceContext.GetPipelineContextOptions()); product = createResult?.SellableItems?.FirstOrDefault(s => s.Id.Equals(productId)); } Condition.Requires <Sitecore.Commerce.Plugin.Catalog.SellableItem>(product) .IsNotNull($"{this.Name}: The Product could not be created."); product.IsPersisted = true; arg.SellableItem = product; return(arg); }
public virtual async Task <IList <string> > GetEntityIds(IList <string> ids) { var entityIds = new List <string>(); var missingReferences = new List <string>(); if (ids != null && ids.Any()) { foreach (var id in ids) { var entityId = id.EnsurePrefix(CommerceEntity.IdPrefix <T>()); if (await DoesEntityExists(entityId)) { entityIds.Add(entityId); } else { missingReferences.Add(id); } } } if (missingReferences.Any()) { Context.CommerceContext.AddModel(new MissingReferencesModel() { Name = $"Missing-{Name}", MissingReferences = missingReferences }); } return(entityIds); }
public override async Task <SynchronizeCategoryArgument> Run(SynchronizeCategoryArgument arg, CommercePipelineExecutionContext context) { Sitecore.Commerce.Plugin.Catalog.Category category = null; var categoryId = $"{CommerceEntity.IdPrefix<Category>()}{arg.Catalog.Name}-{arg.ImportCategory.CategoryId.ProposeValidId()}"; if (await _doesEntityExistPipeline.Run( new FindEntityArgument(typeof(Sitecore.Commerce.Plugin.Catalog.Category), categoryId), context.CommerceContext.GetPipelineContextOptions())) { category = await _getCategoryPipeline.Run(new GetCategoryArgument(categoryId), context.CommerceContext.GetPipelineContextOptions()); } else { var createResult = await _createCategoryPipeline.Run( new CreateCategoryArgument(arg.Catalog.Id, arg.ImportCategory.CategoryId.ProposeValidId(), arg.ImportCategory.CategoryName, ""), context.CommerceContext.GetPipelineContextOptions()); category = createResult?.Categories?.FirstOrDefault(c => c.Id.Equals(categoryId)); } Condition.Requires <Sitecore.Commerce.Plugin.Catalog.Category>(category) .IsNotNull($"{this.Name}: The Category could not be created."); arg.Category = category; return(arg); }
/// <summary> /// The execute. /// </summary> /// <param name="arg">The SampleArgument argument.</param> /// <param name="context">The context.</param> /// <returns>The <see cref="SampleEntity"/>.</returns> public override async Task <SampleEntity> Run(TransactionArgument arg, CommercePipelineExecutionContext context) { Condition.Requires(arg).IsNotNull($"{Name}: The argument can not be null"); var result = new SampleEntity() { Id = $"{CommerceEntity.IdPrefix<SampleEntity>()}Inner-{Guid.NewGuid().ToString()}" }; await Commander.PersistEntity(context.CommerceContext, result).ConfigureAwait(false); if (arg.ErrorOnInnerScope) { context.Abort( await context.CommerceContext.AddMessage( context.GetPolicy <KnownResultCodes>().ValidationError, "ForcedError", new object[] { nameof(arg.ErrorOnInnerScope) }, $"Error in {nameof(arg.ErrorOnInnerScope)}.").ConfigureAwait(false), context); return(null); } return(result); }
private void TransformCore(CommerceContext commerceContext, string[] rawFields, InventoryInformation item) { var inventorySetName = rawFields[InventoryIdIndex]; var productId = rawFields[ProductIdIndex]; int.TryParse(rawFields[QuantityIndex], out int quantity); string str = inventorySetName + "-" + productId; //if (!string.IsNullOrEmpty(arg.VariationId)) str = str + "-" + arg.VariationId; item.Id = CommerceEntity.IdPrefix <InventoryInformation>() + str; item.FriendlyId = str; item.InventorySet = new EntityReference(inventorySetName.ToEntityId <InventorySet>(), ""); item.SellableItem = new EntityReference(productId.ToEntityId <SellableItem>(), ""); //item.VariationId = arg.VariationId; item.Quantity = quantity; var component = item.GetComponent <ListMembershipsComponent>(); component.Memberships.Add(CommerceEntity.ListName <InventoryInformation>()); var component1 = item.GetComponent <PreorderableComponent>(); //component1.Preorderable = result1; //component1.PreorderAvailabilityDate = new DateTimeOffset?(); //component1.PreorderLimit = new int?(0); var component2 = item.GetComponent <BackorderableComponent>(); //component2.Backorderable = result3; //component2.BackorderAvailabilityDate = new DateTimeOffset?(); //component2.BackorderLimit = new int?(0); }
public async Task DisassociateParentCategories(string catalogName, Category category, CommerceContext context) { var catalogCommerceId = $"{CommerceEntity.IdPrefix<Catalog>()}{catalogName}"; await _deleteRelationshipCommand.Process(context, catalogCommerceId, category.Id, "CategoryToCategory"); var parentCategorySitecoreIds = category?.ParentCategoryList?.Split('|'); if (parentCategorySitecoreIds == null || parentCategorySitecoreIds.Length == 0) { return; } var categoryList = await _getManagedListCommand.Process(context, CommerceEntity.ListName <Category>()).ConfigureAwait(false); var allCategories = categoryList?.Items?.Cast <Category>(); if (allCategories != null) { foreach (var parentCategorySitecoreId in parentCategorySitecoreIds) { var parentCategory = allCategories.FirstOrDefault(c => c.SitecoreId == parentCategorySitecoreId); if (parentCategory != null) { await _deleteRelationshipCommand.Process(context, parentCategory.Id, category.Id, "CategoryToCategory"); } } } }
/// <summary> /// The execute. /// </summary> /// <param name="arg"> /// The pipeline argument. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// The <see cref="PipelineArgument"/>. /// </returns> public override async Task <Counter> Run(CreateCounterArgument arg, CommercePipelineExecutionContext context) { Condition.Requires(arg).IsNotNull($"{this.Name}: The argument can not be null"); Condition.Requires(arg.CounterName).IsNotEmpty($"The CounterName can not be empty"); var entityId = $"{CommerceEntity.IdPrefix<Counter>()}{arg.CounterName}"; var counterExists = await Commander.Pipeline <IDoesEntityExistPipeline>().Run(new FindEntityArgument(typeof(Counter), entityId), context); if (counterExists) { context.Abort( await context.CommerceContext.AddMessage( context.GetPolicy <KnownResultCodes>().ValidationError, "CounterNameAlreadyInUse", new object[] { arg.CounterName }, $"Counter name {arg.CounterName} is already in use.").ConfigureAwait(false), context); return(null); } var counter = new Counter(entityId, arg.StartValue, arg.Increment); counter.Name = arg.CounterName; counter.DisplayName = arg.CounterName; return(counter); }
public override async Task <SynchronizeProductArgument> Run(SynchronizeProductArgument arg, CommercePipelineExecutionContext context) { if (arg.SellableItem == null || arg.ImportProduct.Categories == null || !arg.ImportProduct.Categories.Any()) { return(arg); } foreach (var category in arg.ImportProduct.Categories) { var categoryId = $"{CommerceEntity.IdPrefix<Category>()}{arg.Catalog.Name}-{category.ProposeValidId()}"; if (await _doesEntityExistPipeline.Run( new FindEntityArgument(typeof(Sitecore.Commerce.Plugin.Catalog.Category), categoryId), context.CommerceContext.GetPipelineContextOptions())) { var associateResult = await _associateSellableItemToParentPipeline.Run( new CatalogReferenceArgument(arg.Catalog.Id, categoryId, arg.SellableItem.Id), context.CommerceContext.GetPipelineContextOptions()); arg.SellableItem = await _findEntityPipeline.Run( new FindEntityArgument(typeof(Sitecore.Commerce.Plugin.Catalog.SellableItem), arg.SellableItem.Id), context.CommerceContext.GetPipelineContextOptions()) as SellableItem ?? arg.SellableItem; } } return(arg); }
/// <summary> /// Bootstraps the cameras. /// </summary> /// <param name="context">The context.</param> /// <returns>a <see cref="Task"/></returns> private async Task BootstrapCameras(CommercePipelineExecutionContext context) { var item = new SellableItem(new List <Component> { new ItemVariationsComponent { ChildComponents = new List <Component> { new ItemVariationComponent(new List <Policy> { new ListPricingPolicy( new List <Money> { new Money("USD", 189.99M), new Money("CAD", 190.99M) }) }) { Id = "57042124", Name = "Optix HD Mini Action Camcorder with Remote (White)", ChildComponents = new List <Component> { //new PhysicalItemComponent() } }, new ItemVariationComponent(new List <Policy> { new ListPricingPolicy( new List <Money> { new Money("USD", 189.99M), new Money("CAD", 190.99M) }) }) { Id = "57042125", Name = "Optix HD Mini Action Camcorder with Remote (Orange)", ChildComponents = new List <Component> { //new PhysicalItemComponent() } } } } }, new List <Policy> { new ListPricingPolicy(new List <Money> { new Money("USD", 117.79M), new Money("CAD", 118.79M) }) }) { Id = $"{CommerceEntity.IdPrefix<SellableItem>()}7042124", Name = "Optix HD Mini Action Camcorder with Remote" }; await UpsertSellableItem(item, context).ConfigureAwait(false); }
public override async Task <Customer> Run(SOMEOBJECTWITHCUSTOMERDATA arg, CommercePipelineExecutionContext context) { var propertiesPolicy = context.GetPolicy <CustomerPropertiesPolicy>(); var customer = new Customer(); string friendlyId = Guid.NewGuid().ToString("N"); customer.AccountNumber = friendlyId; customer.FriendlyId = friendlyId; customer.Id = $"{CommerceEntity.IdPrefix<Customer>()}{friendlyId}"; customer.Email = arg.EmailAddress; //add customer to the entity index so that we can search later await this._persistEntityPipeline.Run( new PersistEntityArgument( new EntityIndex { Id = $"{EntityIndex.IndexPrefix<Customer>("Id")}{customer.Id}", IndexKey = customer.Id, EntityId = customer.Id }), context); return(customer); }
public virtual async Task<InventoryInformation> Process(CommerceContext commerceContext, InventoryModel inventory) { var inventorySetId = $"{CommerceEntity.IdPrefix<InventorySet>()}{inventory.InventorySet}"; string inventorySetIdPrefix = CommerceEntity.IdPrefix<InventorySet>(); var productArgument = ProductArgument.FromItemId(inventory.SellableItemId); string inventoryIdPrefix = CommerceEntity.IdPrefix<InventoryInformation>(); string inventorySetName = inventorySetId.Replace(inventorySetIdPrefix, string.Empty, StringComparison.OrdinalIgnoreCase); string friendlyId = string.IsNullOrWhiteSpace(productArgument.VariantId) ? $"{inventorySetName}-{productArgument.ProductId}" : $"{inventorySetName}-{productArgument.ProductId}-{productArgument.VariantId}"; string inventoryId = $"{inventoryIdPrefix}{friendlyId}"; string sellableItemId = $"{CommerceEntity.IdPrefix<SellableItem>()}{productArgument.ProductId}"; string variationId = productArgument.VariantId; var inventoryInformation = CreateInventoryInformation(inventory, inventoryId, friendlyId, inventorySetId); await AssociateInventoryInformationToSellableItem(commerceContext, inventorySetId, inventoryInformation); await UpdateSellableItem(commerceContext, sellableItemId, variationId, inventoryInformation, inventorySetId); await _inventoryCommander.PersistEntity(commerceContext, inventoryInformation); return inventoryInformation; }
public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context) { if (entityView == null || !entityView.Action.Equals("MyDashboard-AddDashboardEntity", StringComparison.OrdinalIgnoreCase)) { return(entityView); } try { var name = entityView.Properties.First(p => p.Name == "Name").Value ?? ""; var displayName = entityView.Properties.First(p => p.Name == "DisplayName").Value ?? ""; var sampleDashboardEntity = new MessageEntity { Id = CommerceEntity.IdPrefix <MessageEntity>() + Guid.NewGuid().ToString("N"), Name = name, DisplayName = displayName }; sampleDashboardEntity.GetComponent <ListMembershipsComponent>().Memberships.Add(CommerceEntity.ListName <MessageEntity>()); await this._commerceCommander.PersistEntity(context.CommerceContext, sampleDashboardEntity); } catch (Exception ex) { context.Logger.LogError($"Catalog.DoActionAddDashboardEntity.Exception: Message={ex.Message}"); } return(entityView); }
/// <summary> /// The run. /// </summary> /// <param name="arg"> /// The argument. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> public override async Task <string> Run(string arg, CommercePipelineExecutionContext context) { var artifactSet = "Environment.Shops-1.0"; //// Check if this environment has subscribed to this Artifact Set if (!context.GetPolicy <EnvironmentInitializationPolicy>() .InitialArtifactSets.Contains(artifactSet)) { return(arg); } context.Logger.LogInformation($"{Name}.InitializingArtifactSet: ArtifactSet={artifactSet}"); // Default Shop Entity var persistEntitiesArgument = new List <PersistEntityArgument> { new PersistEntityArgument(CreateShop($"{CommerceEntity.IdPrefix<Shop>()}Storefront", "Storefront", "Storefront", "Storefront")), new PersistEntityArgument(CreateShop($"{CommerceEntity.IdPrefix<Shop>()}AwShopCanada", "AwShopCanada", "Adventure Works Canada", "AwShopCanada")), new PersistEntityArgument(CreateShop($"{CommerceEntity.IdPrefix<Shop>()}AwShopUsa", "AwShopUsa", "Adventure Works USA", "AwShopUsa")), new PersistEntityArgument(CreateShop($"{CommerceEntity.IdPrefix<Shop>()}AwShopGermany", "AwShopGermany", "Adventure Works Germany")) }; await _addEntitiesPipeline.Run(new PersistEntitiesArgument(persistEntitiesArgument), context).ConfigureAwait(false); return(arg); }
/// <summary> /// Bootstraps the cameras. /// </summary> /// <param name="context">The context.</param> /// <returns>a <see cref="Task"/></returns> private async Task BootstrapCameras(CommercePipelineExecutionContext context) { var item = new SellableItem { Components = new List <Component> { //new CatalogComponent { Name = "Habitat_Mater" }, //new ListMembershipsComponent //{ // Memberships = new List<string> { CommerceEntity.ListName<SellableItem>() } //}, new ItemVariationsComponent { ChildComponents = new List <Component> { new ItemVariationComponent { Id = "57042124", Name = "Optix HD Mini Action Camcorder with Remote (White)", Policies = new List <Policy> { new ListPricingPolicy(new List <Money> { new Money("USD", 189.99M), new Money("CAD", 190.99M) }) }, ChildComponents = new List <Component> { //new PhysicalItemComponent() } }, new ItemVariationComponent { Id = "57042125", Name = "Optix HD Mini Action Camcorder with Remote (Orange)", Policies = new List <Policy> { new ListPricingPolicy(new List <Money> { new Money("USD", 189.99M), new Money("CAD", 190.99M) }) }, ChildComponents = new List <Component> { //new PhysicalItemComponent() } } } } }, Policies = new List <Policy> { new ListPricingPolicy(new List <Money> { new Money("USD", 117.79M), new Money("CAD", 118.79M) }) }, Id = $"{CommerceEntity.IdPrefix<SellableItem>()}7042124", Name = "Optix HD Mini Action Camcorder with Remote" }; await UpsertSellableItem(item, context); }
private string ExtractCatalogId(string id) { string[] strArray = id.Split(new string[1] { "-" }, StringSplitOptions.RemoveEmptyEntries); return(strArray.Length < 3 ? string.Empty : CommerceEntity.IdPrefix <Catalog>() + strArray[2]); }
public override async Task <Order> Run(ConvertGuestOrderToMemberOrderArgument arg, CommercePipelineExecutionContext context) { Condition.Requires(arg).IsNotNull("The arg can not be null"); Condition.Requires(arg.OrderId).IsNotNull("The order id can not be null"); Condition.Requires(arg.CustomerId).IsNotNull("The customer id can not be null"); Condition.Requires(arg.CustomerEmail).IsNotNull("The customer email can not be null"); var order = await this._commerceCommander.Command <GetOrderCommand>().Process(context.CommerceContext, arg.OrderId); if (order == null) { return(null); } if (!order.HasComponent <ContactComponent>()) { order.Components.Add(new ContactComponent()); } var contactComponent = order.GetComponent <ContactComponent>(); if (contactComponent.IsRegistered == false) { contactComponent.CustomerId = arg.CustomerId; contactComponent.ShopperId = arg.CustomerId; contactComponent.Email = arg.CustomerEmail; contactComponent.IsRegistered = true; } order.SetComponent(contactComponent); var policy = context.GetPolicy <KnownOrderListsPolicy>(); var membershipsComponent = order.GetComponent <ListMembershipsComponent>(); membershipsComponent.Memberships.Remove(policy.AnonymousOrders); membershipsComponent.Memberships.Add(policy.AuthenticatedOrders); membershipsComponent.Memberships.Add(string.Format(policy.CustomerOrders, $"{CommerceEntity.IdPrefix<Customer>()}{arg.CustomerId}")); order.SetComponent(membershipsComponent); await this._commerceCommander.Pipeline <IRemoveListEntitiesPipeline>().Run(new ListEntitiesArgument(new List <string>() { order.Id }, policy.AnonymousOrders), context); await this._commerceCommander.Pipeline <IAddListEntitiesPipeline>().Run(new ListEntitiesArgument(new List <string>() { order.Id }, policy.AuthenticatedOrders), context); await this._commerceCommander.Pipeline <IAddListEntitiesPipeline>().Run(new ListEntitiesArgument(new List <string>() { order.Id }, string.Format(policy.CustomerOrders, $"{CommerceEntity.IdPrefix<Customer>()}{arg.CustomerId}")), context); await this._commerceCommander.Pipeline <IPersistEntityPipeline>().Run(new PersistEntityArgument(order), context); return(order); }
private async Task <string> GetPricingListName(CommercePipelineExecutionContext context, PriceCard entity) { var priceBookName = await Commander.Pipeline <IFindEntityPipeline>().Run( new FindEntityArgument(typeof(PriceBook), entity.Book.EntityTarget.EnsurePrefix(CommerceEntity.IdPrefix <PriceBook>())), context); return(string.Format(context.GetPolicy <KnownPricingListsPolicy>().PriceBookCards, priceBookName?.Name ?? entity.Book.EntityTarget)); }
/// <summary> /// The execute. /// </summary> /// <param name="arg"> /// The AddReviewArgument argument. /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// The <see cref="Review"/>. /// </returns> public override async Task <Review> Run(AddReviewArgument arg, CommercePipelineExecutionContext context) { AddReviewBlock addReviewBlock = this; Condition.Requires(arg).IsNotNull($"{addReviewBlock.Name}: The block argument cannot be null."); string reviewId = Guid.NewGuid().ToString(); Review review = new Review { Id = $"{CommerceEntity.IdPrefix<Review>()}{reviewId}", Text = arg.ReviewsText, Author = arg.Author, Score = arg.Score }; DateTimeOffset?dateCreated = DateTimeOffset.UtcNow; review.DateCreated = dateCreated; DateTimeOffset?dateUpdated = DateTimeOffset.UtcNow; review.DateUpdated = dateUpdated; CommerceContext commerceContextRef = context.CommerceContext; string name = review.Name; review.ProductReference = new EntityReference() { EntityTarget = arg.Product.Id, Name = arg.Product.Name }; Review reviewRef = review; reviewRef.SetComponent(new ListMembershipsComponent() { Memberships = new List <string>() { CommerceEntity.ListName <Review>() } }); ReviewAddedModel reviewAdded = new ReviewAddedModel(review.FriendlyId) { Name = name }; commerceContextRef.AddModel(reviewAdded); context.CommerceContext.AddUniqueObjectByType(arg); await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Information, null, null, "Generated unallocated review"); return(review); }
/// <summary> /// Check if Catalog entity exists in Commerce DB and thorw exception if not /// </summary> /// <param name="context"></param> /// <param name="catalogName"></param> public void AssertCatalogExists(CommercePipelineExecutionContext context, string catalogName) { var commerceCatalogId = $"{CommerceEntity.IdPrefix<Catalog>()}{catalogName}"; Catalog catalog = Task.Run <CommerceEntity>(async() => await _commerceCommander.Command <FindEntityCommand>().Process(context.CommerceContext, typeof(Catalog), commerceCatalogId)).Result as Catalog; if (catalog == null) { throw new ArgumentException($"Catalog '{catalogName}' not found"); } }
protected virtual string ExtractCatalogId(string id) { var strArray = id.Split(new string[] { "-" }, StringSplitOptions.RemoveEmptyEntries); if (strArray.Length < 3) { return(string.Empty); } return(GuidUtils.GetDeterministicGuidString(CommerceEntity.IdPrefix <Catalog>() + strArray[2])); }
public override async Task <CartEmailArgument> Run(CartEmailArgument arg, CommercePipelineExecutionContext context) { if (arg == null) { return(null); } foreach (var cartLine in arg.Cart.Lines) { if (cartLine.HasComponent <ItemAvailabilityComponent>()) { var itemAvailabilityComponent = cartLine.GetComponent <ItemAvailabilityComponent>(); if (!itemAvailabilityComponent.IsAvailable) { if (cartLine.HasComponent <CartProductComponent>()) { var cartProductComponent = cartLine.GetComponent <CartProductComponent>(); if (!cartProductComponent.HasPolicy <AvailabilityAlwaysPolicy>()) { var messageEntity = new MessageEntity { Id = CommerceEntity.IdPrefix <MessageEntity>() + Guid.NewGuid().ToString("N"), Name = "Order.UnavailableItem" }; messageEntity.GetComponent <ListMembershipsComponent>().Memberships.Add(CommerceEntity.ListName <MessageEntity>()); messageEntity.History.Add(new HistoryEntryModel { Name = "Order.UnavailableItem", EventMessage = $"An Order was attempted with an unavailable item" }); var contactComponent = arg.Cart.GetComponent <ContactComponent>(); messageEntity.Components.Add(contactComponent); messageEntity.Components.Add(itemAvailabilityComponent); await this._commerceCommander.PersistEntity(context.CommerceContext, messageEntity); } } } } } if (context.CommerceContext.GetMessages().Any(p => p.Code == "Error")) { try { } catch (Exception ex) { context.CommerceContext.LogException("DevOps.CheckDeserializedEntityBlock", ex); } } return(arg); }
public async Task <IActionResult> Get(string id) { if (!ModelState.IsValid || string.IsNullOrEmpty(id)) { return(NotFound()); } string entityId = $"{ CommerceEntity.IdPrefix<JobConnection>()}{id}"; CommerceEntity commerceEntity = await Command <FindEntityCommand>().Process(CurrentContext, typeof(JobConnection), entityId, false); return(commerceEntity != null ? new ObjectResult(commerceEntity) : (IActionResult)NotFound()); }
/// <summary> /// Main execution point /// </summary> /// <param name="arg"></param> /// <param name="context"></param> /// <returns></returns> public override async Task <ImportCatalogEntityArgument> Run(ImportCatalogEntityArgument arg, CommercePipelineExecutionContext context) { var mappingPolicy = arg.MappingPolicy; var jsonData = arg.Request as JObject; Condition.Requires(jsonData, "Commerce Entity JSON parameter is required").IsNotNull(); context.AddModel(new JsonDataModel(jsonData)); var entityDataModel = context.GetModel <CatalogEntityDataModel>(); var entityData = new CatalogEntityDataModel { EntityId = jsonData.SelectValue <string>(mappingPolicy.EntityId), EntityName = jsonData.SelectValue <string>(mappingPolicy.EntityName), ParentCatalogName = jsonData.SelectValue <string>(mappingPolicy.ParentCatalogName), ParentCategoryName = jsonData.SelectValue <string>(mappingPolicy.ParentCategoryName), EntityFields = jsonData.SelectMappedValues(mappingPolicy.EntityFieldsPaths), ComposerFields = jsonData.SelectMappedValues(mappingPolicy.ComposerFieldsPaths), CustomFields = jsonData.SelectMappedValues(mappingPolicy.CustomFieldsPaths), }; entityData.EntityFields.AddRange(jsonData.QueryMappedValuesFromRoot(mappingPolicy.EntityFieldsRootPaths)); entityData.ComposerFields.AddRange(jsonData.QueryMappedValuesFromRoot(mappingPolicy.ComposerFieldsRootPaths)); entityData.CustomFields.AddRange(jsonData.QueryMappedValuesFromRoot(mappingPolicy.CustomFieldsRootPaths)); if (string.IsNullOrEmpty(entityData.ParentCatalogName)) { entityData.ParentCatalogName = mappingPolicy.DefaultCatalogName; } if (string.IsNullOrEmpty(entityData.ParentCategoryName)) { entityData.ParentCategoryName = mappingPolicy.DefaultCategoryName; } if (arg.CommerceEntityType != null && !string.IsNullOrEmpty(entityData.EntityName)) { if (arg.CommerceEntityType == typeof(Category) && !string.IsNullOrEmpty(entityData.ParentCatalogName)) { entityData.CommerceEntityId = $"{CommerceEntity.IdPrefix<Category>()}{entityData.ParentCatalogName}-{entityData.EntityName}"; } else if (arg.CommerceEntityType == typeof(SellableItem)) { entityData.CommerceEntityId = $"{CommerceEntity.IdPrefix<SellableItem>()}{entityData.EntityId}"; } } context.AddModel(entityData); await Task.CompletedTask; return(arg); }
public override async Task <ImportEntityArgument> Run(ImportEntityArgument arg, CommercePipelineExecutionContext context) { var commerceEntity = arg.ImportHandler.GetCommerceEntity(); if (arg.ImportHandler.ParentEntityIds == null || !arg.ImportHandler.ParentEntityIds.Any() || (!(commerceEntity is Category) && !(commerceEntity is SellableItem))) { return(await Task.FromResult(arg)); } if (commerceEntity.HasComponent <ParentEntitiesComponent>()) { var component = commerceEntity.GetComponent <ParentEntitiesComponent>(); var allIds = arg.ImportHandler.ParentEntityIds.SelectMany(x => x.Value).Distinct().ToList(); var relationshipNamePostfix = "To" + commerceEntity.GetType().Name; foreach (var componentEntityId in component.EntityIds) { if (!allIds.Contains(componentEntityId)) { var relationshipName = string.Empty; if (componentEntityId.StartsWith(CommerceEntity .IdPrefix <Sitecore.Commerce.Plugin.Catalog.Catalog>())) { relationshipName = typeof(Sitecore.Commerce.Plugin.Catalog.Catalog).Name + relationshipNamePostfix; } else if (componentEntityId.StartsWith(CommerceEntity .IdPrefix <Category>())) { relationshipName = typeof(Category).Name + relationshipNamePostfix; } if (!string.IsNullOrEmpty(relationshipName)) { await _deleteRelationshipCommand.Process(context.CommerceContext, componentEntityId, commerceEntity.Id, relationshipName) .ConfigureAwait(false); } } } } return(await Task.FromResult(arg)); }
/// <summary> /// Generates the sales activity. /// </summary> /// <param name="order">The order.</param> /// <param name="existingPayment">The existingPayment.</param> /// <param name="paymentToRefund">The payment to refund</param> /// <param name="refundTransactionId">The refund transaction identifier.</param> /// <param name="context">The context.</param> /// <returns> /// A <see cref="Task" /> /// </returns> protected virtual async Task GenerateSalesActivity(Order order, PaymentComponent existingPayment, PaymentComponent paymentToRefund, string refundTransactionId, CommercePipelineExecutionContext context) { var salesActivity = new SalesActivity { Id = $"{CommerceEntity.IdPrefix<SalesActivity>()}{Guid.NewGuid():N}", ActivityAmount = new Money(existingPayment.Amount.CurrencyCode, paymentToRefund.Amount.Amount * -1), Customer = new EntityReference { EntityTarget = order.EntityComponents.OfType <ContactComponent>().FirstOrDefault()?.CustomerId }, Order = new EntityReference { EntityTarget = order.Id, EntityTargetUniqueId = order.UniqueId }, Name = "Refund the Federated Payment", PaymentStatus = context.GetPolicy <KnownSalesActivityStatusesPolicy>().Completed }; salesActivity.SetComponent(new ListMembershipsComponent { Memberships = new List <string> { CommerceEntity.ListName <SalesActivity>(), context.GetPolicy <KnownOrderListsPolicy>().SalesCredits, string.Format(CultureInfo.InvariantCulture, context.GetPolicy <KnownOrderListsPolicy>().OrderSalesActivities, order.FriendlyId) } }); if (existingPayment.Amount.Amount != paymentToRefund.Amount.Amount) { salesActivity.SetComponent(existingPayment); } if (!string.IsNullOrEmpty(refundTransactionId)) { salesActivity.SetComponent(new TransactionInformationComponent(refundTransactionId)); } var salesActivities = order.SalesActivity.ToList(); salesActivities.Add(new EntityReference { EntityTarget = salesActivity.Id, EntityTargetUniqueId = salesActivity.UniqueId }); order.SalesActivity = salesActivities; await _persistPipeline.Run(new PersistEntityArgument(salesActivity), context).ConfigureAwait(false); }
/// <summary> /// /// </summary> /// <param name="customer"></param> /// <param name="context"></param> /// <returns></returns> public override Task <Customer> Run(Customer customer, CommercePipelineExecutionContext context) { // Ensure customer is not null and has a name Condition.Requires <Customer>(customer).IsNotNull <Customer>("The customer can not be null"); Condition.Requires <string>(customer.UserName).IsNotNullOrEmpty("The customer user name can not be null"); // This is where we proseed to generating the new custom customer number either directly or by calling an external service. customer.AccountNumber = GenerateNewCustomerNumber(context, _findEntitiesInListCommand); customer.Id = $"{(object) CommerceEntity.IdPrefix<Customer>()}{(object) customer.AccountNumber}"; customer.FriendlyId = customer.AccountNumber; return(Task.FromResult <Customer>(customer)); }