Try our conversational search powered by Generative AI!

K Khan
Jul 17, 2016
  3935
(3 votes)

developing a custom promotion walk through

I got a chance to share my views on custom promotion at Manchester Meetup and learn from other technology masters. It was really a cool gathering. There was at least one representative was present from each EPiServer partner in that region. It was also exciting to see what other Tech gurus were doing to help out businesses with EPiServer products. I am sure EPiServer will have a road plan to discuss this feature with businesses, so they could understand what are the benefits and how they can increase the revenue from their commerce website by engaing their customer with introducing Personalised and purpose fit promotions.

With new promotion system, as a developer, it is very easy to develop the custom promotions now. It is depending on two Objects

1. Promotion Data - Define metadata of Criteria and Reward

2. Promotion Process - A class that will evaluate the Promotion data and will pass the Reward description to Promotion Engine.

(I will cover custom promotion glossary in a separate blog)

If you are not happy the way Promotion Engine is processing your promotions, No Problem. Develop your custom Promotion Engine and use that.

Promotion Data

[ContentType(GUID = "A5EAED44-82F7-4549-A430-83E0848DE2A2"
    , DisplayName = "Promotion on a Brand"
    , Description = "Item belongs to a particular brand will be elligible for a percentage discount")]
    public class BrandPromotionsData : EntryPromotion
    {
        //PromotionRegion attribute is used to attach Condition with a color propert in Editor Area
        //You also can use the PromotionRegion attribute on a block property.
        [PromotionRegion(PromotionRegionName.Condition)]
        public virtual BrandCriteriaBlock Condition { get; set; }

        [PromotionRegion(PromotionRegionName.Reward)]
        public virtual MonetaryReward Discount { get; set; }
    }

    /// <summary>
    /// Promotion Condition Block - create to manage condition properties
    /// </summary>
    [ContentType(GUID = "97E53739-583F-4565-9868-334168879991", AvailableInEditMode = false)]
    public class BrandCriteriaBlock : BlockData
    {
        [SelectOne(SelectionFactoryType = typeof(BrandSelectionFactory))]
        public virtual string BrandName { get; set; }

        [Range(1, 99)]
        public virtual int Quantity { get; set; }
    }

Promotion Processor

The processor evaluates if a promotion should apply a reward to an order. You can implement the IPromotionProcessor interface directly, but the recommended way is to inherit from the abstract EntryPromotionProcessorBase<TEntryPromotion>,  OrderPromotionProcessorBase<TOrderPromotion>, or  ShippingPromotionProcessorBase<TShippingPromotion> depending on the type of promotion being created.

public class BrandPromotionProcessor : EntryPromotionProcessorBase<BrandPromotionsData>
    {
        private readonly LocalizationService localizationService;
        private readonly IContentLoader contentLoader;
        private readonly ReferenceConverter referenceConverter;
        private readonly IProductService productService;

        public BrandPromotionProcessor(IContentLoader contentLoader, ReferenceConverter referenceConverter, LocalizationService localizationService, IProductService productService)
        {
            this.contentLoader = contentLoader;
            this.referenceConverter = referenceConverter;
            this.localizationService = localizationService;
            this.productService = productService;
        }

        protected override RewardDescription Evaluate(BrandPromotionsData promotionData, PromotionProcessorContext context)
        {
            var applicableCodes = this.ApplicableCodes(promotionData, context);
            IEnumerable<ILineItem> lineItems = GetLineItems(context.OrderForm);

            //A status flag. Indicates if a promotion is not, partially, or fully fulfilled.
            var status = GetFulfilmentStatus(lineItems, applicableCodes);

            //if (!status.HasFlag(FulfillmentStatus.Fulfilled))
            //{
            //    implement NotFulfilledRewardDescription and retun it before further processing
            //}

            //A list of redemption descriptions, 
            //one for each of the maximum amount of redemptions that could be applied to the 
            //current order. This does not have to take redemption limits into consideration, 
            //that is handled by the promotion engine.
            //Note @EPiServer: EPiServer.Commerce.Marketing.RedemptionDescription is not testable, @dveloper better to make a custom RedemptionDescription

            IEnumerable<RedemptionDescription> redemptions = GetRedemptions(promotionData, lineItems, context, applicableCodes);

            //A reward type.Depending on the type, the discount value is read from the properties 
            //UnitDiscount, Percentage or Quantity.
            MonetaryReward discount = promotionData.Discount;

            var desc = RewardDescription.CreateMoneyOrPercentageRewardDescription(status, redemptions, promotionData, discount, context.OrderGroup.Currency, this.localizationService);
            return desc;
        }

        /// <summary>
        /// Can this promotion can be applied
        /// </summary>
        /// <param name="promotionData">Promotion Data</param>
        /// <param name="context">Promotion Context</param>
        /// <returns>returns true if promotion can be applied</returns>
        protected override bool CanBeFulfilled(BrandPromotionsData promotionData, PromotionProcessorContext context)
        {
            //Add business logic can this promotion be fulfilled
            return true;
        }

        protected override PromotionItems GetPromotionItems(BrandPromotionsData promotionData)
        {
            var ids = this.productService.GetProductsByBrand(promotionData.Condition.BrandName);
            var items = new PromotionItems(promotionData, new CatalogItemSelection(ids, CatalogItemSelectionType.Specific, false), new CatalogItemSelection(ids, CatalogItemSelectionType.Specific, false));
            return items;
        }

        private IEnumerable<string> ApplicableCodes(BrandPromotionsData promotionData, PromotionProcessorContext context)
        {
            List<string> codes = new List<string>();
            List<ILineItem> lineItems = this.GetLineItems(context.OrderForm).ToList();

            return this.productService.GetProductCodes(lineItems);
        }

        private FulfillmentStatus GetFulfilmentStatus(IEnumerable<ILineItem> lineItems, IEnumerable<string> applicableCodes)
        {
            // Add you business logic to return back fulfillment status
            return FulfillmentStatus.Fulfilled;
        }

        private IEnumerable<RedemptionDescription> GetRedemptions(BrandPromotionsData promotionData, IEnumerable<ILineItem> lineItems, PromotionProcessorContext context, IEnumerable<string> applicableCodes)
        {
            IEnumerable<ILineItem> targetItems = from li in lineItems
                                                 where applicableCodes.Contains(li.Code)
                                                 select li;
            decimal q = this.productService.GetQuantity(targetItems);

            AffectedEntries affectedEntries = context.EntryPrices.ExtractEntries(applicableCodes, q);
            if (affectedEntries == null)
            {
                return Enumerable.Empty<RedemptionDescription>();
            }

            return new RedemptionDescription[]
            {
                this.CreateRedemptionDescription(affectedEntries)
            };
        }
    }

And Tada!

Jul 17, 2016

Comments

Please login to comment.
Latest blogs
Optimizely and the never-ending story of the missing globe!

I've worked with Optimizely CMS for 14 years, and there are two things I'm obsessed with: Link validation and the globe that keeps disappearing on...

Tomas Hensrud Gulla | Apr 18, 2024 | Syndicated blog

Visitor Groups Usage Report For Optimizely CMS 12

This add-on offers detailed information on how visitor groups are used and how effective they are within Optimizely CMS. Editors can monitor and...

Adnan Zameer | Apr 18, 2024 | Syndicated blog

Azure AI Language – Abstractive Summarisation in Optimizely CMS

In this article, I show how the abstraction summarisation feature provided by the Azure AI Language platform, can be used within Optimizely CMS to...

Anil Patel | Apr 18, 2024 | Syndicated blog

Fix your Search & Navigation (Find) indexing job, please

Once upon a time, a colleague asked me to look into a customer database with weird spikes in database log usage. (You might start to wonder why I a...

Quan Mai | Apr 17, 2024 | Syndicated blog

The A/A Test: What You Need to Know

Sure, we all know what an A/B test can do. But what is an A/A test? How is it different? With an A/B test, we know that we can take a webpage (our...

Lindsey Rogers | Apr 15, 2024

.Net Core Timezone ID's Windows vs Linux

Hey all, First post here and I would like to talk about Timezone ID's and How Windows and Linux systems use different IDs. We currently run a .NET...

sheider | Apr 15, 2024