Exemplo n.º 1
0
        public virtual async Task <WishList> Process(CommerceContext commerceContext, string wishListId, WishListLineComponent line)
        {
            WishList result = null;

            using (CommandActivity.Start(commerceContext, this))
            {
                var context            = commerceContext.GetPipelineContextOptions();
                var findEntityArgument = new FindEntityArgument(typeof(WishList), wishListId);
                var wishList           = await _getPipeline.Run(findEntityArgument, context) as WishList;

                if (wishList == null)
                {
                    await context.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().ValidationError, "EntityNotFound", new object[] { wishListId }, string.Format("Entity {0} was not found.", wishListId));

                    return(null);
                }
                if (wishList.Lines.FirstOrDefault <WishListLineComponent>(c => c.Id == line.Id) == null)
                {
                    await context.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().ValidationError, "WishListLineNotFound", new object[] { line.Id }, string.Format("WishList line {0} was not found", line.Id));

                    return(wishList);
                }
                result = await _pipeline.Run(new WishListLineArgument(wishList, line), context);

                return(result);
            }
        }
Exemplo n.º 2
0
            public void Execute_ShouldRoundPriceCalc_True(
                BaseCartItemSubtotalAmountOffAction action,
                IRuleValue <decimal> subtotal,
                IRuleValue <decimal> amountOff,
                Cart cart,
                CommerceContext commerceContext,
                IRuleExecutionContext context)
            {
                /**********************************************
                * Arrange
                **********************************************/
                cart.Adjustments.Clear();
                cart.Lines.ForEach(l => l.Adjustments.Clear());

                var globalPricingPolicy = commerceContext.GetPolicy <GlobalPricingPolicy>();

                globalPricingPolicy.ShouldRoundPriceCalc         = true;
                globalPricingPolicy.RoundDigits                  = 3;
                globalPricingPolicy.MidPointRoundUp              = true;
                cart.Lines.ForEach(l => l.Totals.SubTotal.Amount = 100);
                var cartline = cart.Lines[1];

                cartline.Totals.SubTotal.Amount = 175;
                var cartTotals = new CartTotals(cart);

                subtotal.Yield(context).ReturnsForAnyArgs(150);
                amountOff.Yield(context).ReturnsForAnyArgs(25.555555M);

                context.Fact <CommerceContext>().ReturnsForAnyArgs(commerceContext);
                commerceContext.AddObject(cartTotals);
                commerceContext.AddObject(cart);
                action.MatchingLines(context).ReturnsForAnyArgs(cart.Lines);
                action.SubtotalOperator = new DecimalGreaterThanEqualToOperator();
                action.Subtotal         = subtotal;
                action.AmountOff        = amountOff;

                /**********************************************
                * Act
                **********************************************/
                Action executeAction = () => action.Execute(context);

                /**********************************************
                * Assert
                **********************************************/
                executeAction.Should().NotThrow <Exception>();
                cart.Lines.SelectMany(l => l.Adjustments).Should().HaveCount(1);
                cart.Adjustments.Should().BeEmpty();
                cartTotals.Lines[cartline.Id].SubTotal.Amount.Should().Be(149.444M);
                cartline.Adjustments.Should().NotBeEmpty();
                cartline.Adjustments.FirstOrDefault().Should().NotBeNull();
                cartline.Adjustments.FirstOrDefault().Should().BeOfType <CartLineLevelAwardedAdjustment>();
                cartline.Adjustments.FirstOrDefault()?.Name.Should().Be(commerceContext.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount);
                cartline.Adjustments.FirstOrDefault()?.DisplayName.Should().Be(commerceContext.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount);
                cartline.Adjustments.FirstOrDefault()?.AdjustmentType.Should().Be(commerceContext.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount);
                cartline.Adjustments.FirstOrDefault()?.AwardingBlock.Should().Contain(nameof(BaseCartItemSubtotalAmountOffAction));
                cartline.Adjustments.FirstOrDefault()?.IsTaxable.Should().BeFalse();
                cartline.Adjustments.FirstOrDefault()?.Adjustment.CurrencyCode.Should().Be(commerceContext.CurrentCurrency());
                cartline.Adjustments.FirstOrDefault()?.Adjustment.Amount.Should().Be(-25.556M);
                cartline.HasComponent <MessagesComponent>().Should().BeTrue();
            }
Exemplo n.º 3
0
        /// <summary>
        /// Processes the specified commerce context.
        /// </summary>
        /// <param name="commerceContext">The commerce context.</param>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public virtual async Task <FulfillmentFeeBook> Process(CommerceContext commerceContext, string name = "")
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                var FulfillmentFeeBookName = commerceContext.GetPolicy <GlobalPolicy>().GetFulfillmentFeeBookName(name, commerceContext);
                var cachePolicy            = commerceContext.GetPolicy <FulfillmentFeeCachePolicy>();
                var cacheKey = string.Format("{0}{1}", commerceContext.CurrentLanguage(), FulfillmentFeeBookName);

                ICache             cache = null;
                FulfillmentFeeBook FulfillmentFeeBook = null;

                if (cachePolicy.AllowCaching)
                {
                    var environmentCacheArgument = new EnvironmentCacheArgument {
                        CacheName = cachePolicy.CacheName
                    };
                    cache = await _cachePipeline.Run(environmentCacheArgument, commerceContext.GetPipelineContextOptions());

                    FulfillmentFeeBook = await cache.Get(cacheKey) as FulfillmentFeeBook;
                }

                if (FulfillmentFeeBook == null)
                {
                    FulfillmentFeeBook = await this.GetFulfillmentFeeBook(commerceContext, FulfillmentFeeBookName);

                    if (cachePolicy.AllowCaching && cache != null)
                    {
                        await cache.Set(cacheKey, new Cachable <FulfillmentFeeBook>(FulfillmentFeeBook, 1L), cachePolicy.GetCacheEntryOptions());
                    }
                }

                return(FulfillmentFeeBook);
            }
        }
        public virtual async Task <Cart> Process(CommerceContext commerceContext, string wishlistId, CartLineComponent line)
        {
            RemoveWishListLineCommand removeCartLineCommand = this;
            Activity activity;


            Cart result = null;

            activity = CommandActivity.Start(commerceContext, removeCartLineCommand);

            try
            {
                CommercePipelineExecutionContextOptions context = commerceContext.PipelineContextOptions;
                FindEntityArgument findEntityArgument           = new FindEntityArgument(typeof(Cart), wishlistId, false);
                Cart cart = await removeCartLineCommand._getPipeline.Run(findEntityArgument, context).ConfigureAwait(false) as Cart;

                if (cart == null)
                {
                    string str = await context.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().ValidationError, "EntityNotFound", new object[1]
                    {
                        wishlistId
                    }, string.Format("Entity {0} was not found.", wishlistId)).ConfigureAwait(false);

                    return(null);
                }
                if (cart.Lines.FirstOrDefault((c => c.Id == line.Id)) == null)
                {
                    string str = await context.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().ValidationError, "CartLineNotFound", new object[1]
                    {
                        line.Id
                    }, string.Format("Wishlist line {0} was not found", line.Id)).ConfigureAwait(false);

                    return(cart);
                }

                await removeCartLineCommand.PerformTransaction(commerceContext, async() =>
                {
                    var cartResult = await this._pipeline.Run(new CartLineArgument(cart, line), (IPipelineExecutionContextOptions)context).ConfigureAwait(false);

                    result = cartResult;
                });

                return(result);
            }
            finally
            {
                if (activity != null)
                {
                    activity.Dispose();
                }
            }
        }
        private async Task TransformD365Category(CommerceContext commerceContext, List <SellableItem> importItems, List <TransientImportSellableItemDataPolicy> transientDataList)
        {
            var d365Response = await commerceContext.GetPolicy <ConnectionPolicy>().GetCategories();

            var d365CategoriesLookup = (d365Response).ToLookup(c => c[CategoryDisplayNameIndex].ToString());
            var d365ProductCategoryAssignmentsLookup = (await commerceContext.GetPolicy <ConnectionPolicy>().GetProductCategoryAssignments()).ToLookup(a => a[ProductNumberIndex].ToString());

            var defaultCatalogName = d365Response.First()[CategoryCatalogName].ToString();

            foreach (var item in importItems)
            {
                var data = item.GetPolicy <TransientImportSellableItemDataPolicy>();

                var assignmentList = d365ProductCategoryAssignmentsLookup[item.ProductId];
                if (assignmentList != null && !assignmentList.Count().Equals(0))
                {
                    foreach (var assignment in assignmentList)
                    {
                        var categoryDisplayName = assignment[ProductCategoryDisplayNameIndex].ToString();
                        var d365CategoryList    = d365CategoriesLookup[categoryDisplayName];
                        if (d365CategoryList == null || d365CategoryList.Count().Equals(0))
                        {
                            throw new Exception($"Error, product with ID '{item.ProductId}' is a assigned to a category '{categoryDisplayName}' that can't be found.");
                        }

                        data.CategoryAssociationList.Add(new CategoryAssociationModel
                        {
                            CatalogName  = assignment[ProductCatalogNameIndex].ToString(),
                            CategoryName = d365CategoryList.First()[CategoryNameIndex].ToString()
                        });

                        Console.WriteLine($"Product Id '{item.ProductId}' associating to '{categoryDisplayName}'.");
                        await commerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().Information, null, null, $"Product Id '{item.ProductId}' associating to '{categoryDisplayName}'.");
                    }

                    foreach (var catalogName in data.CategoryAssociationList.Select(a => a.CatalogName).Distinct())
                    {
                        data.CatalogAssociationList.Add(new CatalogAssociationModel {
                            Name = catalogName
                        });
                    }
                }
                else
                {
                    data.CatalogAssociationList.Add(new CatalogAssociationModel {
                        Name = defaultCatalogName
                    });
                }

                transientDataList.Add(data);
            }
        }
        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);
        }
Exemplo n.º 7
0
        public async Task <IEnumerable <SellableItem> > Process(CommerceContext commerceContext, IEnumerable <string[]> importRawLines)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var importPolicy      = commerceContext.GetPolicy <ImportSellableItemsPolicy>();
                var importItems       = new List <SellableItem>();
                var transientDataList = new List <TransientImportSellableItemDataPolicy>();
                foreach (var rawFields in importRawLines)
                {
                    if (rawFields.Count() != ExpectedIndexLimit)
                    {
                        commerceContext.Logger.LogWarning($"Warning, skipping unexpected line with field count'{rawFields.Count()}' and expected '{ExpectedIndexLimit}'. Line '{string.Join(",", rawFields)}'");
                        continue;
                    }

                    var item = new SellableItem();
                    TransformCore(commerceContext, rawFields, item);
                    TransformListPrice(commerceContext, importPolicy, rawFields, item);
                    TransformProductExtension(rawFields, item);
                    TransformTransientData(importPolicy, rawFields, item, transientDataList);
                    importItems.Add(item);
                }

                await TransformCatalog(commerceContext, importItems);
                await TransformCategory(commerceContext, transientDataList, importItems);
                await TransformImages(commerceContext, transientDataList, importItems);

                return(importItems);
            }
        }
Exemplo n.º 8
0
        private async Task <bool> ImportComposerViewsFields(CommerceEntity commerceEntity, Dictionary <string, string> entityFields, CommerceContext context)
        {
            //Get root/master view of the target entity, composer views, if any, will be included in Child views of this master view
            var masterView = await _commerceCommander.Command <GetEntityViewCommand>().Process(
                context,
                commerceEntity.Id,
                commerceEntity.EntityVersion,
                context.GetPolicy <KnownCatalogViewsPolicy>().Master,
                string.Empty,
                string.Empty);

            if (masterView == null)
            {
                Log.Error($"Master view not found on Commerce Entity, Entity ID={commerceEntity.Id}");
                throw new ApplicationException($"Master view not found on Commerce Entity, Entity ID={commerceEntity.Id}");
            }

            if (masterView.ChildViews == null || masterView.ChildViews.Count == 0)
            {
                Log.Error($"No composer-generated views found on Sellable Item entity, Entity ID={commerceEntity.Id}");
                throw new ApplicationException($"No composer-generated views found on Sellable Item entity, Entity ID={commerceEntity.Id}");
            }

            //Now iterate through child views and then their child fields, looking for matching names
            var isUpdated = false;

            foreach (EntityView view in masterView.ChildViews)
            {
                EntityView composerViewForEdit = null;
                foreach (var viewField in view.Properties)
                {
                    //Found matching field that need to be updated
                    if (entityFields.Keys.Contains(viewField.Name))
                    {
                        //Retrieve the composer view to update...
                        if (composerViewForEdit == null)
                        {
                            composerViewForEdit = Task.Run <EntityView>(async() => await commerceEntity.GetComposerView(view.ItemId, _commerceCommander, context)).Result;
                        }
                        //...and update the field value
                        if (composerViewForEdit != null)
                        {
                            var composerProperty = composerViewForEdit.GetProperty(viewField.Name);
                            if (composerViewForEdit != null)
                            {
                                composerProperty.ParseValueAndSetEntityView(entityFields[viewField.Name]);
                                isUpdated = true;
                            }
                        }
                    }
                }
            }

            if (isUpdated)
            {
                return(await _composerCommander.PersistEntity(context, commerceEntity));
            }

            return(false);
        }
Exemplo n.º 9
0
        public bool Evaluate(IRuleExecutionContext context)
        {
            /* STUDENT: Complete the Evaluate method to:
             * Retrieve the current temperature
             * Compare it to the temperature stored in the Policy
             * Return the result of that comparison
             */
            var             minimumTemperature = MinimumTemperature.Yield(context);
            var             city            = City.Yield(context);
            var             country         = Country.Yield(context);
            CommerceContext commerceContext = context.Fact <CommerceContext>((string)null);

            string openWeatherAPIKey  = commerceContext.GetPolicy <WeatherServiceClientPolicy>().OpenWeatherAPIKey;
            var    currentTemperature = GetCurrentTemperature(city, country, openWeatherAPIKey);

            if (currentTemperature > minimumTemperature)
            {
                return(true);
            }
            else
            {
                return(false);
            }

            // STUDENT: Replace this line. It is only provided so the stub
            // project will build cleanly
        }
        public virtual async Task <WishList> Process(CommerceContext commerceContext, string wishListId, WishListLineComponent line)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var context            = commerceContext.GetPipelineContextOptions();
                var findEntityArgument = new FindEntityArgument(typeof(WishList), wishListId, true);
                var wishList           = await _getPipeline.Run(findEntityArgument, context) as WishList;

                if (wishList == null)
                {
                    await context.CommerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().ValidationError, "EntityNotFound", new object[] { wishListId }, string.Format("Entity {0} was not found.", wishListId));

                    return(null);
                }

                if (!wishList.IsPersisted)
                {
                    wishList.Id       = wishListId;
                    wishList.Name     = wishListId;
                    wishList.ShopName = commerceContext.CurrentShopName();
                }

                var result = await _addToWishListPipeline.Run(new WishListLineArgument(wishList, line), context);

                await _persistEntityPipeline.Run(new PersistEntityArgument(result), context);

                return(result);
            }
        }
Exemplo n.º 11
0
        public async Task <JsonResponse> Process(CommerceContext commerceContext, string uri)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var response = new JsonResponse {
                    Uri = uri
                };

                try
                {
                    using (var httpClient = new HttpClient())
                    {
                        response.Json = await httpClient.GetStringAsync(response.Uri);
                    }

                    var reader = new StringReader(response.Json);

                    response.Reader = new JsonTextReader(reader);
                }
                catch (Exception ex)
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        $"JsonCommand.Get.Exception: Message={ex.Message}",
                        new object[] { ex },
                        $"JsonCommand.Get.Exception: Message={ex.Message}|Stack={ex.StackTrace}");

                    response = null;
                }
                return(response);
            }
        }
Exemplo n.º 12
0
        public async Task <Dictionary <string, string> > Process(CommerceContext commerceContext, IEnumerable <string> listOfImageNames)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var mediaItemList    = new Dictionary <string, string>();
                var connectionString = commerceContext.GetPolicy <SitecoreMasterSqlPolicy>().ReadOnlyConnectionString();

                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    await connection.OpenAsync();

                    string[] paramNames = listOfImageNames.Select((s, i) => "@tag" + i.ToString()).ToArray();

                    using (var cmd = connection.CreateCommand())
                    {
                        cmd.CommandText = $"SELECT DISTINCT TOP (1000) [Name], [ID] FROM [dbo].[Items] WHERE [Name] in ({string.Join(", ", paramNames)})";
                        for (int i = 0; i < paramNames.Length; i++)
                        {
                            cmd.Parameters.AddWithValue(paramNames[i], listOfImageNames.ElementAt(i));
                        }

                        using (var reader = await cmd.ExecuteReaderAsync())
                        {
                            while (reader.Read())
                            {
                                mediaItemList.Add(reader["Name"].ToString(), reader["ID"].ToString());
                            }
                        }
                    }
                }

                return(mediaItemList);
            }
        }
Exemplo n.º 13
0
        public async Task <string> Process(CommerceContext commerceContext)
        {
            var policy = commerceContext.GetPolicy <ShortConfirmationCodePolicy>();
            int count  = 0;

            string result = Guid.NewGuid().ToString("N").ToUpper(); //Fallback value.

            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                await this.PerformTransaction(commerceContext, async() =>
                {
                    do
                    {
                        string value = CreateValue(policy);
                        string id    = $"Entity-ShortConfirmationCode-{value}";
                        if (await NotYetUsed(commerceContext, id))
                        {
                            await ReserveIt(commerceContext, id);
                            result = value;
                            break;
                        }
                        count++;
                    } while (count <= policy.MaximumRetries);
                });

                return(result);
            }
        }
Exemplo n.º 14
0
        public async Task <CommerceCommand> Process(CommerceContext commerceContext, IFormFile importFile, string mode, int errorThreshold, bool publishEntities = true)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                //var pipelineContextOptions = commerceContext.GetPipelineContextOptions();
                var catalogsArgument = new ImportCsvProductsArgument(importFile, mode)
                {
                    ErrorThreshold = errorThreshold
                };

                if (publishEntities)
                {
                    commerceContext.Environment.SetPolicy(new AutoApprovePolicy());
                }

                //var importResult = await _importCsvProductsPipeline.Run(catalogsArgument, pipelineContextOptions);
                var importResult = await _importCsvProductsPipeline.Run(catalogsArgument);

                if (importResult != null)
                {
                    Messages.AddRange(importResult.Errors);
                    ResponseCode = importResult.ResultCode;
                }
                else
                {
                    ResponseCode = commerceContext.GetPolicy <KnownResultCodes>().Error;
                }

                if (publishEntities)
                {
                    commerceContext.Environment.RemovePolicy(typeof(AutoApprovePolicy));
                }
            }
            return(this);
        }
Exemplo n.º 15
0
        private Category TransformCore(CommerceContext commerceContext, JToken rawLine, List <Category> importItems)
        {
            var catalogName = rawLine[CatalogNameIndex].ToString();
            var name        = rawLine[CategoryNameIndex].ToString();
            var id          = name.ToCategoryId(catalogName);

            var item = importItems.FirstOrDefault(i => i.Id.Equals(id));

            if (item == null)
            {
                item             = new Category();
                item.Name        = name;
                item.Id          = id;
                item.FriendlyId  = item.Name.ToCategoryFriendlyId(catalogName);
                item.SitecoreId  = GuidUtils.GetDeterministicGuidString(item.Id);
                item.DisplayName = rawLine[CategoryDisplayNameIndex].ToString();

                var component = item.GetComponent <ListMembershipsComponent>();
                component.Memberships.Add(string.Format("{0}", CommerceEntity.ListName <Category>()));
                component.Memberships.Add(commerceContext.GetPolicy <KnownCatalogListsPolicy>().CatalogItems);

                importItems.Add(item);
            }

            return(item);
        }
Exemplo n.º 16
0
        public async Task <PriceCard> Process(CommerceContext commerceContext, string bookId)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                PriceCard createdPriceCard = null;
                var       bookName         = bookId.Replace("Entity-PriceBook-", "");
                var       listName         = string.Format(commerceContext.GetPolicy <KnownPricingListsPolicy>().PriceBookCards, bookName);

                var cardIds = await this._commerceCommander.Command <ListCommander>()
                              .GetListItemIds <PriceCard>(commerceContext, listName, 0, 100);

                while (cardIds.Count > 0)
                {
                    var tasks = new List <Task>();

                    foreach (var card in cardIds)
                    {
                        tasks.Add(Task.Run(() => this._commerceCommander
                                           .DeleteEntity(commerceContext, card)));
                    }

                    await Task.WhenAll(tasks);

                    cardIds = await this._commerceCommander.Command <ListCommander>()
                              .GetListItemIds <PriceCard>(commerceContext, listName, 0, 100);
                }

                return(createdPriceCard);
            }
        }
Exemplo n.º 17
0
        public bool Evaluate(IRuleExecutionContext context)
        {
            /* STUDENT: Complete the Evaluate method to:
             * Retrieve the current temperature
             * Compare it to the temperature stored in the Policy
             * Return the result of that comparison
             */
            var minimumTemperature = MinimumTemperature.Yield(context);
            var city    = City.Yield(context);
            var country = Country.Yield(context);


            // Fetch applicationid from the policy created.
            CommerceContext commerceContext      = context.Fact <CommerceContext>((string)null);
            var             weatherServicePolicy = commerceContext.GetPolicy <WeatherServiceClientPolicy>();

            var currentTemperature = GetCurrentTemperature(city, country, weatherServicePolicy.ApplicationId);

            if (currentTemperature > minimumTemperature)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public bool Evaluate(IRuleExecutionContext context)
        {
            //itemId = ID to check in purchase order history
            //itemInCartItemId = Item in cart to check in order history to give discount
            //If customer has purchased itemId and has not purchased itemInCartItemId this rule returns true
            string itemId           = this.TargetItemId.Yield(context);
            string itemInCartItemId = this.CurrentItemInCartId.Yield(context);
            bool   valid            = false;

            CommerceContext commerceContext = context.Fact <CommerceContext>((string)null);

            if (commerceContext == null || !commerceContext.CurrentUserIsRegistered() || string.IsNullOrEmpty(itemId))
            {
                return(false);
            }
            //UPDATED TO USE CURRENTSHOPPERID VS EMPTY CURRENTCUSTOMERID
            string listName             = string.Format(commerceContext.GetPolicy <KnownOrderListsPolicy>().CustomerOrders, (object)commerceContext.CurrentShopperId());
            CommerceList <Order> result = Task.Run <CommerceList <Order> >((Func <Task <CommerceList <Order> > >)(() => this._getEntitFindEntitiesInListCommand.Process <Order>(commerceContext, listName, 0, int.MaxValue))).Result;
            List <Order>         source = result != null?result.Items.ToList <Order>() : (List <Order>)null;

            if (source == null || !source.Any <Order>())
            {
                return(false);
            }
            if (!this.MatchesAnItem(context))
            {
                if (
                    source.Any <Order>(
                        (Func <Order, bool>)(
                            o => o.Lines.Any <CartLineComponent>(
                                (Func <CartLineComponent, bool>)(
                                    l => l.ItemId.StartsWith(itemId, StringComparison.OrdinalIgnoreCase)
                                    )))))
                {
                    valid = source.Where <Order>(
                        (Func <Order, bool>)(
                            o => o.Lines.Where <CartLineComponent>(
                                (Func <CartLineComponent, bool>)(
                                    l => l.ItemId.Contains(itemInCartItemId)
                                    )).FirstOrDefault() != null)).FirstOrDefault() == null;
                    return(valid);
                }
            }
            if (source.Any <Order>(
                    (Func <Order, bool>)(
                        o => o.Lines.Any <CartLineComponent>(
                            (Func <CartLineComponent, bool>)(
                                l => l.ItemId.Equals(itemId)
                                )))))
            {
                valid = source.Where <Order>(
                    (Func <Order, bool>)(
                        o => o.Lines.Where <CartLineComponent>(
                            (Func <CartLineComponent, bool>)(
                                l => !l.ItemId.Equals(itemInCartItemId, StringComparison.OrdinalIgnoreCase)
                                )).FirstOrDefault() == null)).FirstOrDefault() == null;
                return(valid);
            }
            return(valid);
        }
        /// <summary>
        /// Processes the specified commerce context.
        /// </summary>
        /// <param name="commerceContext">The commerce context.</param>
        /// <returns>User site terms</returns>
        public virtual async Task <IEnumerable <Customer> > Process(CommerceContext commerceContext)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var sqlContext = ConnectionHelper.GetProfilesSqlContext(commerceContext);
                var rows       = await sqlContext.GetAllProfiles();

                var migratedCustomers = new List <Customer>();

                foreach (DataRow row in rows)
                {
                    try
                    {
                        var contextOptions = commerceContext.GetPipelineContextOptions();

                        var csCustomer = await this._migrateCustomerPipeline.Run(row, contextOptions);

                        if (csCustomer != null)
                        {
                            migratedCustomers.Add(csCustomer);
                        }
                    }
                    catch (Exception ex)
                    {
                        await commerceContext.AddMessage(
                            commerceContext.GetPolicy <KnownResultCodes>().Error,
                            "EntityNotFound",
                            new object[] { row["u_user_id"] as string, ex },
                            $"Customer {row["u_user_id"] as string} was not migrated.");
                    }
                }

                return(migratedCustomers);
            }
        }
Exemplo n.º 20
0
            public void Execute_PercentOff(
                CartItemQuantityRangePercentOffAction action,
                IRuleValue <string> targetItemId,
                IRuleValue <decimal> minQuantity,
                IRuleValue <decimal> maxQuantity,
                IRuleValue <decimal> percentOff,
                Cart cart,
                CommerceContext commerceContext,
                IRuleExecutionContext context)
            {
                /**********************************************
                * Arrange
                **********************************************/
                cart.Adjustments.Clear();
                cart.Lines.ForEach(l => l.Adjustments.Clear());

                var globalPricingPolicy = commerceContext.GetPolicy <GlobalPricingPolicy>();

                globalPricingPolicy.ShouldRoundPriceCalc         = true;
                cart.Lines.ForEach(l => l.Totals.SubTotal.Amount = 100);
                targetItemId.Yield(context).Returns("Habitat_Master|12345|");
                var index = 12345;

                cart.Lines.ForEach(line =>
                {
                    line.ItemId   = $"Habitat_Master|{index++}|";
                    line.Quantity = 2;
                    line.Totals.SubTotal.Amount = 150;
                    line.SetPolicy(new PurchaseOptionMoneyPolicy());
                });
                var cartTotals = new CartTotals(cart);

                minQuantity.Yield(context).ReturnsForAnyArgs(2);
                maxQuantity.Yield(context).ReturnsForAnyArgs(3);
                percentOff.Yield(context).ReturnsForAnyArgs(10);

                context.Fact <CommerceContext>().ReturnsForAnyArgs(commerceContext);
                commerceContext.AddObject(cartTotals);
                commerceContext.AddObject(cart);
                action.TargetItemId = targetItemId;
                action.MinQuantity  = minQuantity;
                action.MaxQuantity  = maxQuantity;
                action.PercentOff   = percentOff;

                /**********************************************
                * Act
                **********************************************/
                Action executeAction = () => action.Execute(context);

                /**********************************************
                * Assert
                **********************************************/
                executeAction.Should().NotThrow <Exception>();
                cart.Lines.SelectMany(l => l.Adjustments).Should().HaveCount(1);
                cart.Adjustments.Should().BeEmpty();
                cartTotals.Lines[cart.Lines[0].Id].SubTotal.Amount.Should().Be(135);
            }
        public static void AddPromotionApplied(this MessagesComponent messageComponent, CommerceContext commerceContext,
                                               string awardingBlock)
        {
            var    propertiesModel = commerceContext.GetObject <PropertiesModel>();
            object promotionName   = propertiesModel?.GetPropertyValue("PromotionId") ?? awardingBlock;

            messageComponent.AddMessage(commerceContext.GetPolicy <KnownMessageCodePolicy>().Promotions,
                                        $"PromotionApplied: {promotionName}");
        }
Exemplo n.º 22
0
        public static SyncForceClientPolicy GetSyncForceClientPolicy(CommerceContext context)
        {
            if (!context.HasPolicy <SyncForceClientPolicy>())
            {
                throw new Exception("GetSyncForceClientPolicy could not find a SyncForceClientPolicy to be returned for API Connection");
            }

            return(context.GetPolicy <SyncForceClientPolicy>());
        }
        /// <summary>
        /// Import fields defined in Item's composer views
        /// </summary>
        /// <param name="commerceEntity"></param>
        /// <param name="jsonData"></param>
        /// <param name="mappingPolicy"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <SellableItem> ImportComposerViewsFields(SellableItem commerceEntity, Dictionary <string, string> composerFields, CommerceContext context)
        {
            var masterView = await _commerceCommander.Command <GetEntityViewCommand>().Process(
                context, commerceEntity.Id,
                commerceEntity.EntityVersion,
                context.GetPolicy <KnownCatalogViewsPolicy>().Master,
                string.Empty,
                string.Empty);

            if (masterView == null)
            {
                Log.Error($"Master view not found on Commerce Entity, Entity ID={commerceEntity.Id}");
                throw new ApplicationException($"Master view not found on Commerce Entity, Entity ID={commerceEntity.Id}");
            }

            if (masterView.ChildViews == null || masterView.ChildViews.Count == 0)
            {
                Log.Error($"No composer-generated views found on Sellable Item entity, Entity ID={commerceEntity.Id}");
                throw new ApplicationException($"No composer-generated views found on Sellable Item entity, Entity ID={commerceEntity.Id}");
            }

            var isUpdated = false;

            foreach (EntityView view in masterView.ChildViews)
            {
                EntityView composerViewForEdit = null;
                foreach (var viewField in view.Properties)
                {
                    if (composerFields.Keys.Contains(viewField.Name))
                    {
                        if (composerViewForEdit == null)
                        {
                            composerViewForEdit = Task.Run <EntityView>(async() => await commerceEntity.GetComposerView(view.ItemId, _commerceCommander, context)).Result;
                        }
                        if (composerViewForEdit != null)
                        {
                            var composerProperty = composerViewForEdit.GetProperty(viewField.Name);
                            if (composerViewForEdit != null)
                            {
                                composerProperty.ParseValueAndSetEntityView(composerFields[viewField.Name]);
                                isUpdated = true;
                            }
                        }
                    }
                }
            }

            if (isUpdated)
            {
                await _composerCommander.PersistEntity(context, commerceEntity);

                //var persistResult = await _commerceCommander.Pipeline<IPersistEntityPipeline>().Run(new PersistEntityArgument(commerceEntity), context.PipelineContextOptions);
                return(await _commerceCommander.Command <FindEntityCommand>().Process(context, typeof(SellableItem), commerceEntity.Id) as SellableItem);
            }

            return(commerceEntity);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Gets the profiles SQL connection policy.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns>
        /// A <see cref="ProfilesSqlPolicy" />
        /// </returns>
        public static ProfilesSqlPolicy GetProfilesSqlConnectionPolicy(CommerceContext context)
        {
            if (!context.HasPolicy <ProfilesSqlPolicy>())
            {
                throw new Sitecore.Commerce.Core.CommerceException("GetProfilesSqlConnectionPolicy a ProfilesSqlPolicy to be returned for SQL Connection");
            }

            return(context.GetPolicy <ProfilesSqlPolicy>());
        }
Exemplo n.º 25
0
            public void Execute_TimesQualified_Two_MaximumApplications_One(
                CartAnyItemQuantityXForQuantityYAction action,
                IRuleValue <int> quantityX,
                IRuleValue <int> quantityY,
                IRuleValue <int> maximumApplications,
                Cart cart,
                CommerceContext commerceContext,
                IRuleExecutionContext context)
            {
                /**********************************************
                * Arrange
                **********************************************/
                cart.Adjustments.Clear();
                cart.Lines.ForEach(l => l.Adjustments.Clear());

                var globalPricingPolicy = commerceContext.GetPolicy <GlobalPricingPolicy>();

                globalPricingPolicy.ShouldRoundPriceCalc         = false;
                cart.Lines.ForEach(l => l.Totals.SubTotal.Amount = 100);
                while (cart.Lines.Count > 1)
                {
                    cart.Lines.RemoveAt(0);
                }
                var cartline = cart.Lines[0];

                cartline.Quantity = 8;
                cartline.Totals.SubTotal.Amount = 200;
                cartline.SetPolicy(new PurchaseOptionMoneyPolicy
                {
                    SellPrice = new Money(25)
                });
                var cartTotals = new CartTotals(cart);

                quantityX.Yield(context).ReturnsForAnyArgs(4);
                quantityY.Yield(context).ReturnsForAnyArgs(3);
                maximumApplications.Yield(context).ReturnsForAnyArgs(1);

                context.Fact <CommerceContext>().ReturnsForAnyArgs(commerceContext);
                commerceContext.AddObject(cartTotals);
                commerceContext.AddObject(cart);
                action.QuantityX           = quantityX;
                action.QuantityY           = quantityY;
                action.MaximumApplications = maximumApplications;

                /**********************************************
                * Act
                **********************************************/
                Action executeAction = () => action.Execute(context);

                /**********************************************
                * Assert
                **********************************************/
                executeAction.Should().NotThrow <Exception>();
                cart.Lines.SelectMany(l => l.Adjustments).Should().HaveCount(1);
                cart.Adjustments.Should().BeEmpty();
                cartTotals.Lines[cartline.Id].SubTotal.Amount.Should().Be(175);
            }
            public void Execute_12_NoPurchaseOptionMoneyPolicy(
                CartItemQuantityXForQuantityYAction action,
                IRuleValue <string> targetItemId,
                IRuleValue <int> quantityX,
                IRuleValue <int> quantityY,
                IRuleValue <int> maximumApplications,
                Cart cart,
                CommerceContext commerceContext,
                IRuleExecutionContext context)
            {
                /**********************************************
                * Arrange
                **********************************************/
                cart.Adjustments.Clear();
                cart.Lines.ForEach(l => l.Adjustments.Clear());

                var globalPricingPolicy = commerceContext.GetPolicy <GlobalPricingPolicy>();

                globalPricingPolicy.ShouldRoundPriceCalc         = false;
                cart.Lines.ForEach(l => l.Totals.SubTotal.Amount = 100);
                while (cart.Lines.Count > 1)
                {
                    cart.Lines.RemoveAt(0);
                }
                var cartline = cart.Lines[0];

                cartline.Quantity = 4;
                cartline.Totals.SubTotal.Amount = 100;
                cartline.ItemId = "Habitat_Master|12345|";
                var cartTotals = new CartTotals(cart);

                targetItemId.Yield(context).ReturnsForAnyArgs("Habitat_Master|12345|");
                quantityX.Yield(context).ReturnsForAnyArgs(4);
                quantityY.Yield(context).ReturnsForAnyArgs(3);

                context.Fact <CommerceContext>().ReturnsForAnyArgs(commerceContext);
                commerceContext.AddObject(cartTotals);
                commerceContext.AddObject(cart);
                action.TargetItemId        = targetItemId;
                action.QuantityX           = quantityX;
                action.QuantityY           = quantityY;
                action.MaximumApplications = maximumApplications;

                /**********************************************
                * Act
                **********************************************/
                Action executeAction = () => action.Execute(context);

                /**********************************************
                * Assert
                **********************************************/
                executeAction.Should().NotThrow <Exception>();
                cart.Lines.SelectMany(l => l.Adjustments).Should().HaveCount(0);
                cart.Adjustments.Should().BeEmpty();
            }
Exemplo n.º 27
0
        /// <returns>true if succesful</returns>
        public async Task <SellableItem> Process(CommerceContext commerceContext, string productId)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                int percent = commerceContext.GetPolicy <LoyaltyPointsPolicy>().LoyaltyPointPercent;
                var arg     = new AddLoyaltyPointsArgument(productId, percent);
                var result  = await this._pipeline.Run(arg, new CommercePipelineExecutionContextOptions(commerceContext));

                return(result);
            }
        }
        public async Task <CommerceCommand> Process(CommerceContext commerceContext, string itemId, decimal price)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                var ids         = itemId.Split('|');
                var catalogName = ids[0];
                var productId   = ids[1];

                var approvalStatusPolicy = commerceContext.GetPolicy <ApprovalStatusPolicy>();

                var sellableItem = await Commander.GetEntity <SellableItem>(commerceContext, productId.ToEntityId <SellableItem>());

                if (sellableItem != null)
                {
                    var priceCardId = $"HerderPreisbuch-{productId}".ToEntityId <PriceCard>();
                    var priceCard   = await Commander.GetEntity <PriceCard>(commerceContext, priceCardId);

                    if (priceCard != null)
                    {   /// Find the snapshot (we are assuming there is only one snapshot we are updating. If there are more we don't know which one we should update.)
                        if (priceCard.Snapshots.Count == 1)
                        {
                            var snapshot = priceCard.Snapshots[0];
                            if (snapshot.Tiers.Any())
                            {
                                var tier = snapshot.Tiers[0];
                                tier.Price = price;
                            }
                            else
                            {
                                var    snapshotStartDate = DateTimeOffset.Now;
                                int    quantity          = 1;
                                string currency          = "EUR";

                                snapshot = new PriceSnapshotComponent();

                                snapshot.BeginDate = snapshotStartDate;
                                snapshot.Tiers.Add(new PriceTier(currency, quantity, price));
                            }

                            var approvalComponent = snapshot.GetComponent <ApprovalComponent>();
                            approvalComponent.ModifyStatus(approvalStatusPolicy.Approved, "Automatically approved");

                            await Commander.PersistEntity(commerceContext, priceCard);
                        }
                    }

                    // We assume the pricecard is already attached to the sellable item so we don't save it
                }

                return(this);
            }
        }
        public async Task <CommerceCommand> Process(CommerceContext commerceContext, string itemId, decimal price)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                var ids         = itemId.Split('|');
                var catalogName = ids[0];
                var productId   = ids[1];

                var approvalStatusPolicy = commerceContext.GetPolicy <ApprovalStatusPolicy>();

                var sellableItem = await Commander.GetEntity <SellableItem>(commerceContext, productId.ToEntityId <SellableItem>());

                if (sellableItem != null)
                {
                    var priceCardId = $"HerderPreisbuch-{productId}".ToEntityId <PriceCard>();
                    var priceCard   = await Commander.GetEntity <PriceCard>(commerceContext, priceCardId);

                    if (priceCard != null)
                    {   /// Create a new snapshot...
                        var    snapshotStartDate = DateTimeOffset.Now;
                        int    quantity          = 1;
                        string currency          = "EUR";

                        var priceSnapShot = new PriceSnapshotComponent();

                        priceSnapShot.BeginDate = snapshotStartDate;
                        priceSnapShot.Tiers.Add(new PriceTier(currency, quantity, price));

                        // Add the snapshot to the price card
                        priceCard = await Commander.Command <Sitecore.Commerce.Plugin.Pricing.AddPriceSnapshotCommand>().Process(commerceContext, priceCard, priceSnapShot);

                        // Approve the snapshot
                        var approvalComponent = priceSnapShot.GetComponent <ApprovalComponent>();
                        approvalComponent.ModifyStatus(approvalStatusPolicy.Approved, "Automatically approved");

                        // Save the price card
                        await Commander.PersistEntity(commerceContext, priceCard);

                        // Associate price card with sellable item (if this has not been done already)
                        var priceCardPolicy = sellableItem.GetPolicy <PriceCardPolicy>();
                        priceCardPolicy.PriceCardName = priceCard.Name;

                        await Commander.PersistEntity(commerceContext, sellableItem);
                    }

                    // We assume the pricecard is already attached to the sellable item so we don't save it
                }

                return(this);
            }
        }
        /// <summary>
        /// The process of the command
        /// </summary>
        /// <param name="commerceContext">
        /// The commerce context
        /// </param>
        /// <param name="cartLineComponent"></param>
        /// <param name="awardingAction"></param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public virtual void Process(CommerceContext commerceContext, [NotNull] CartLineComponent cartLineComponent, [NotNull] string awardingAction)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var discountAdjustmentType = commerceContext.GetPolicy <KnownCartAdjustmentTypesPolicy>().Discount;
                var propertiesModel        = commerceContext.GetObject <PropertiesModel>();
                var totals         = commerceContext?.GetObject <CartTotals>();
                var discountAmount = cartLineComponent.UnitListPrice.Amount * decimal.MinusOne;

                cartLineComponent.Adjustments.Add(new CartLineLevelAwardedAdjustment
                {
                    Name           = (propertiesModel?.GetPropertyValue("PromotionText") as string ?? discountAdjustmentType),
                    DisplayName    = (propertiesModel?.GetPropertyValue("PromotionCartText") as string ?? discountAdjustmentType),
                    Adjustment     = new Money(commerceContext.CurrentCurrency(), discountAmount),
                    AdjustmentType = discountAdjustmentType,
                    IsTaxable      = false,
                    AwardingBlock  = propertiesModel?.GetPropertyValue("PromotionId") as string
                });

                totals.Lines[cartLineComponent.Id].SubTotal.Amount = totals.Lines[cartLineComponent.Id].SubTotal.Amount + discountAmount;
                cartLineComponent.GetComponent <MessagesComponent>().AddMessage(commerceContext.GetPolicy <KnownMessageCodePolicy>().Promotions, string.Format("PromotionApplied: {0}", propertiesModel?.GetPropertyValue("PromotionId") ?? awardingAction));
            }
        }