K Khan
Jul 17, 2016
  3998
(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
Opti ID overview

Opti ID allows you to log in once and switch between Optimizely products using Okta, Entra ID, or a local account. You can also manage all your use...

K Khan | Jul 26, 2024

Getting Started with Optimizely SaaS using Next.js Starter App - Extend a component - Part 3

This is the final part of our Optimizely SaaS CMS proof-of-concept (POC) blog series. In this post, we'll dive into extending a component within th...

Raghavendra Murthy | Jul 23, 2024 | Syndicated blog

Optimizely Graph – Faceting with Geta Categories

Overview As Optimizely Graph (and Content Cloud SaaS) makes its global debut, it is known that there are going to be some bugs and quirks. One of t...

Eric Markson | Jul 22, 2024 | Syndicated blog

Integration Bynder (DAM) with Optimizely

Bynder is a comprehensive digital asset management (DAM) platform that enables businesses to efficiently manage, store, organize, and share their...

Sanjay Kumar | Jul 22, 2024

Frontend Hosting for SaaS CMS Solutions

Introduction Now that CMS SaaS Core has gone into general availability, it is a good time to start discussing where to host the head. SaaS Core is...

Minesh Shah (Netcel) | Jul 20, 2024

Optimizely London Dev Meetup 11th July 2024

On 11th July 2024 in London Niteco and Netcel along with Optimizely ran the London Developer meetup. There was an great agenda of talks that we put...

Scott Reed | Jul 19, 2024