protected void uxAddButton_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                if (uxMultiSubGroup.ConvertToSubGroupIDs().Length > 0)
                {
                    PromotionGroup promotionGroup = new PromotionGroup(uxLanguageControl.CurrentCulture);

                    promotionGroup = SetUpPromotionGroup(promotionGroup);
                    promotionGroup = DataAccessContextDeluxe.PromotionGroupRepository.Save(promotionGroup);
                    string newPromotionGroupID = promotionGroup.PromotionGroupID;

                    uxMessage.DisplayMessage(Resources.PromotionGroupMessage.AddSuccess);

                    ClearInputFields();
                }
                else
                {
                    uxMessage.DisplayError(Resources.PromotionGroupMessage.AddErrorPromotionSubGroupEmpty);
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            uxMessage.DisplayException(ex);
        }
    }
Beispiel #2
0
    protected string GetItemImage(object cartItem)
    {
        ICartItem baseCartItem = ( ICartItem )cartItem;

        if (baseCartItem.IsPromotion)
        {
            CartItemPromotion cartItemPromotion = (CartItemPromotion)baseCartItem;
            PromotionGroup    promotion         = cartItemPromotion.PromotionSelected.GetPromotionGroup();

            if (String.IsNullOrEmpty(promotion.ImageFile))
            {
                return("~/Images/Products/Thumbnail/DefaultNoImage.gif");
            }
            else
            {
                return("~/" + promotion.ImageFile);
            }
        }
        else
        {
            ProductImage details = baseCartItem.Product.GetPrimaryProductImage();

            if (String.IsNullOrEmpty(details.ThumbnailImage))
            {
                return("~/Images/Products/Thumbnail/DefaultNoImage.gif");
            }
            else
            {
                return("~/" + details.ThumbnailImage);
            }
        }
    }
Beispiel #3
0
        /// <summary>
        /// Adds the discount to line item.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="itemRecord">The item record.</param>
        /// <param name="entryCode">The entry code.</param>
        /// <param name="itemDiscount">The item discount.</param>
        /// <param name="orderLevelDiscount">The order level discount.</param>
        private void AddDiscountToLineItem(OrderGroup order, PromotionItemRecord itemRecord, PromotionEntry promotionEntry,
                                           decimal itemDiscount, decimal orderLevelDiscount)
        {
            LineItem item = FindLineItemByPromotionEntry(order, promotionEntry);

            if (item != null)
            {
                // Add line item properties
                item.LineItemDiscountAmount   += itemDiscount;
                item.OrderLevelDiscountAmount += orderLevelDiscount;
                item.ExtendedPrice             = item.ListPrice * item.Quantity - item.LineItemDiscountAmount - item.OrderLevelDiscountAmount;

                if (itemRecord.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key, StringComparison.OrdinalIgnoreCase))
                {
                    LineItemDiscount discount = FindLineItemDiscountById(order, itemRecord.PromotionItem.DataRow.PromotionId, item.LineItemId);

                    if (discount == null)
                    {
                        discount = new LineItemDiscount();
                    }

                    discount.DiscountAmount = itemRecord.PromotionItem.DataRow.OfferAmount;
                    discount.DiscountCode   = itemRecord.PromotionItem.DataRow.CouponCode;
                    discount.DiscountName   = itemRecord.PromotionItem.DataRow.Name;
                    discount.DiscountValue  = itemRecord.PromotionItem.DataRow.OfferAmount;
                    discount.DisplayMessage = GetDisplayName(itemRecord.PromotionItem.DataRow, Thread.CurrentThread.CurrentCulture.Name);
                    discount.LineItemId     = item.LineItemId;
                    discount.DiscountId     = itemRecord.PromotionItem.DataRow.PromotionId;
                    item.Discounts.Add(discount);
                }
            }
        }
Beispiel #4
0
    protected void uxTellFriendButton_Command(object sender, CommandEventArgs e)
    {
        group = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(StoreContext.Culture, StoreContext.CurrentStore.StoreID, PromotionGroupID, BoolFilter.ShowTrue);
        string url = UrlManager.GetPromotionTellFriendUrl(group.PromotionGroupID, group.UrlName);

        Response.Redirect(url);
    }
Beispiel #5
0
    public void SetupDropDownList(string groupID, Culture culture, bool restore)
    {
        DataTable table = new DataTable();

        table.Columns.Add(new DataColumn("PromotionGroupID", Type.GetType("System.Int32")));
        table.Columns.Add(new DataColumn("PromotionSubGroupID", Type.GetType("System.Int32")));

        if (restore)
        {
            string[] subGroupIDs = uxSubGroupIDHidden.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < subGroupIDs.Length; i++)
            {
                DataRow row = table.NewRow();
                row["PromotionGroupID"]    = groupID;
                row["PromotionSubGroupID"] = subGroupIDs[i];
                table.Rows.Add(row);
            }
        }
        else
        {
            PromotionGroup promotionGroup = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(culture, groupID);
            for (int i = 0; i < promotionGroup.PromotionGroupSubGroup.Count; i++)
            {
                DataRow row = table.NewRow();
                row["PromotionGroupID"]    = groupID;
                row["PromotionSubGroupID"] = promotionGroup.PromotionGroupSubGroup[i].PromotionSubGroupID;
                table.Rows.Add(row);
            }
        }
        InitDropDownList(culture, table);
    }
    private void Update()
    {
        try
        {
            if (Page.IsValid)
            {
                if (uxMultiSubGroup.ConvertToSubGroupIDs().Length > 0)
                {
                    PromotionGroup promotionGroup = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(uxLanguageControl.CurrentCulture, CurrentID);
                    promotionGroup = SetUpPromotionGroup(promotionGroup);
                    promotionGroup = DataAccessContextDeluxe.PromotionGroupRepository.Save(promotionGroup);

                    PopulateControls();
                    uxMessage.DisplayMessage(Resources.PromotionGroupMessage.UpdateSuccess);
                }
                else
                {
                    uxMessage.DisplayError(Resources.PromotionGroupMessage.AddErrorPromotionSubGroupEmpty);
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            uxMessage.DisplayException(ex);
        }
    }
Beispiel #7
0
 private void PopulateControl()
 {
     group        = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(StoreContext.Culture, StoreContext.CurrentStore.StoreID, PromotionGroupID, BoolFilter.ShowTrue);
     subGroupList = DataAccessContextDeluxe.PromotionGroupRepository.GetPromotionGroupSubGroup(PromotionGroupID);
     SetGroup();
     SetList();
 }
    private void IsPromotionAvailable()
    {
        PromotionGroup group = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(
            StoreContext.Culture, StoreContext.CurrentStore.StoreID, PromotionGroupID, BoolFilter.ShowTrue);

        if (!group.IsEnabled || group.IsNull == true)
        {
            Response.Redirect("~/Error404.aspx");
        }
    }
        public virtual PromotionContext Evaluate(PromotionFilter filter, PromotionEntriesSet sourceEntriesSet, PromotionEntriesSet targetEntriesSet, bool checkEntryLevelLimit)
        {
            var helper = new PromotionHelper();

            helper.PromotionContext.TargetGroup      = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key;
            helper.PromotionContext.SourceEntriesSet = sourceEntriesSet;
            helper.PromotionContext.TargetEntriesSet = targetEntriesSet;
            helper.Eval(filter, checkEntryLevelLimit);
            return(helper.PromotionContext);
        }
        /// <summary>
        /// Creates the filter nodes.
        /// </summary>
        protected override void CreateFilterNodes()
        {
            //First call base implementation
            base.CreateFilterNodes();

            _filterElementsMap = new Dictionary <string, IEnumerable <FilterExpressionNode> >();

            #region Entry
            string promotionGroupKey            = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key;
            List <FilterExpressionNode> tmpColl = new List <FilterExpressionNode>();
            tmpColl.AddRange(ActionsEntryDefs.Select(x => CreateFilterExpressionNode(x)));
            _filterElementsMap.Add(promotionGroupKey, tmpColl);
            #endregion
            #region OrderGroup
            promotionGroupKey = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key;
            tmpColl           = new List <FilterExpressionNode>();
            tmpColl.AddRange(ActionsOrderDefs.Select(x => CreateFilterExpressionNode(x)));
            _filterElementsMap.Add(promotionGroupKey, tmpColl);
            #endregion
            #region Shipment
            //tmpColl = new List<FilterExpressionNode>();
            //promotionGroupKey = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Shipping).Key;
            //tmpColl.AddRange(new FilterExpressionNode[] {
            //        CreateFilterExpressionNode(eAvailableActions.EachShipping.ToString(), "get $ off shipping per item", FilterExpressionNodeType.Element),
            //        CreateFilterExpressionNode(eAvailableActions.EachShippingPercent.ToString(), "get % off shipping per item", FilterExpressionNodeType.Element),
            //        CreateFilterExpressionNode(eAvailableActions.AllShipping.ToString(), "get $ off whole shipping", FilterExpressionNodeType.Element),
            //        CreateFilterExpressionNode(eAvailableActions.AllShippingPercent.ToString(), "get % off whole shipping", FilterExpressionNodeType.Element),
            //        CreateFilterExpressionNode(eAvailableActions.FreeShipping.ToString(), "get free shipping", FilterExpressionNodeType.Element)
            //        });
            //_filterElementsMap.Add(promotionGroupKey, tmpColl);
            #endregion

            #region Register method elemets
            //Each entry
            CreateMethodElement(MethodEachEntryDefs, "~/Apps/Marketing/ExpressionFunctions/actionRewardTwoParam.ascx");
            //All entry
            CreateMethodElement(MethodAllEntryDefs, "~/Apps/Marketing/ExpressionFunctions/actionRewardOneParam.ascx");
            //All entry percent
            CreateMethodElement(MethodAllEntryPercentDefs, "~/Apps/Marketing/ExpressionFunctions/actionRewardOneParamPercent.ascx");
            //Gift
            CreateMethodElement(MethodGiftDefs, "~/Apps/Marketing/ExpressionFunctions/actionRewardOneParam.ascx");
            #endregion


            #region Register conditions elements
            //Decimal
            CreateConditionEement(ConditionDecimalDefs, ConditionElementType.Custom, "~/Apps/Marketing/ExpressionFunctions/DecimalFilter.ascx");
            //Percent
            CreateConditionEement(ConditionPercentDecimalDefs, ConditionElementType.Custom, "~/Apps/Marketing/ExpressionFunctions/DecimalPercentFilter.ascx");
            //SkuSet
            CreateConditionEement(ConditionSkuSelectDefs, ConditionElementType.Custom, "~/Apps/Marketing/ExpressionFunctions/CatalogEntryFilter.ascx");
            #endregion
        }
Beispiel #11
0
    protected void SetUpEmailPromotion(PromotionGroup group)
    {
        string subjectText;
        string bodyText;

        EmailTemplateTextVariable.ReplaceTellFriendPromotionText(
            group,
            out subjectText,
            out bodyText);

        uxSubjectText.Text      = subjectText;
        uxEmailBodyHidden.Value = bodyText;
    }
Beispiel #12
0
    protected void SetUpEmailPromotion(PromotionGroup group, out string subject, out string contentBody)
    {
        string subjectText;
        string bodyText;

        EmailTemplateTextVariable.ReplaceTellFriendPromotionText(
            group,
            out subjectText,
            out bodyText);

        subject     = subjectText;
        contentBody = bodyText + "<br/><br/>";
    }
    private void PromotionDetail_StoreCultureChanged(object sender, CultureEventArgs e)
    {
        PromotionGroup promotionGroup = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(
            StoreContext.Culture, StoreContext.CurrentStore.StoreID, CurrentPromotionGroupID, BoolFilter.ShowTrue);

        if (!String.IsNullOrEmpty(promotionGroup.UrlName))
        {
            Response.Redirect(UrlManager.GetPromotionUrl(CurrentPromotionGroupID, promotionGroup.UrlName));
        }
        else
        {
            Response.Redirect("~/Error404.aspx");
        }
    }
Beispiel #14
0
        private static void PreparePromotion(PromotionHelper helper, Entry entry, bool checkEntryLevelDiscountLimit)
        {
            var     currentMarket = CurrentMarket.Service.GetCurrentMarket();
            decimal minQuantity   = 1;

            // get min quantity attribute
            if (entry.ItemAttributes != null)
            {
                minQuantity = entry.ItemAttributes.MinQuantity;
            }

            // we can't pass qauntity of 0, so make it default to 1
            if (minQuantity <= 0)
            {
                minQuantity = 1;
            }

            var price = StoreHelper.GetSalePrice(entry, minQuantity, currentMarket) ?? new Mediachase.Commerce.Catalog.Objects.Price(new Money(0, currentMarket.DefaultCurrency));

            // Create filter
            var filter = new PromotionFilter()
            {
                IgnoreConditions = false,
                IgnorePolicy     = false,
                IgnoreSegments   = false,
                IncludeCoupons   = false
            };

            // Create new entry
            // TPB: catalogNodes is determined by the front end. GetParentNodes(entry)
            var result = new PromotionEntry(String.Empty, String.Empty, entry.ID, price.Money.Amount);
            var promotionEntryPopulateService = (IPromotionEntryPopulate)MarketingContext.Current.PromotionEntryPopulateFunctionClassInfo.CreateInstance();

            promotionEntryPopulateService.Populate(result, entry, currentMarket.MarketId, currentMarket.DefaultCurrency);

            var sourceSet = new PromotionEntriesSet();

            sourceSet.Entries.Add(result);

            // Only target entries
            helper.PromotionContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key;

            // Configure promotion context
            helper.PromotionContext.SourceEntriesSet = sourceSet;
            helper.PromotionContext.TargetEntriesSet = sourceSet;

            // Execute the promotions and filter out basic collection of promotions, we need to execute with cache disabled, so we get latest info from the database
            helper.Eval(filter, checkEntryLevelDiscountLimit);
        }
    private PromotionGroup SetUpPromotionGroup(PromotionGroup promotionGroup)
    {
        promotionGroup.Name           = uxPromotionGroupNameText.Text;
        promotionGroup.Description    = uxDescriptionText.Text;
        promotionGroup.Price          = ConvertUtilities.ToDecimal(uxPriceText.Text);
        promotionGroup.TaxClassID     = uxTaxClassDrop.SelectedValue;
        promotionGroup.Weight         = ConvertUtilities.ToDouble(uxWeightText.Text);
        promotionGroup.IsEnabled      = uxIsEnabeldCheck.Checked;
        promotionGroup.IsFreeShipping = uxIsFreeShippingCheck.Checked;
        promotionGroup.StoreID        = StoreID;
        promotionGroup.SubGroupIDs    = uxMultiSubGroup.ConvertToSubGroupIDs();
        promotionGroup = uxPromotionImage.SetupImage(promotionGroup);

        return(promotionGroup);
    }
Beispiel #16
0
    protected string GetLink(object cartItem)
    {
        ICartItem baseCartItem = ( ICartItem )cartItem;

        if (baseCartItem.IsPromotion)
        {
            CartItemPromotion cartItemPromotion = (CartItemPromotion)baseCartItem;
            PromotionGroup    promotion         = cartItemPromotion.PromotionSelected.GetPromotionGroup();
            return(UrlManager.GetPromotionUrl(promotion.PromotionGroupID, promotion.Locales[StoreContext.Culture].UrlName));
        }
        else
        {
            Product product = baseCartItem.Product;
            return(UrlManager.GetProductUrl(product.ProductID, product.Locales[StoreContext.Culture].UrlName));
        }
    }
 private void PopulateControls()
 {
     if (CurrentID != null && int.Parse(CurrentID) >= 0)
     {
         PromotionGroup promotionGroup = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(uxLanguageControl.CurrentCulture, CurrentID);
         uxPromotionGroupNameText.Text = promotionGroup.Name;
         uxPriceText.Text              = String.Format("{0:f2}", promotionGroup.Price);
         uxTaxClassDrop.SelectedValue  = promotionGroup.TaxClassID;
         uxWeightText.Text             = promotionGroup.Weight.ToString();
         uxDescriptionText.Text        = promotionGroup.Description;
         uxIsEnabeldCheck.Checked      = promotionGroup.IsEnabled;
         uxIsFreeShippingCheck.Checked = promotionGroup.IsFreeShipping;
         uxStoreDrop.SelectedValue     = promotionGroup.StoreID;
         uxPromotionImage.PopulateControls(promotionGroup);
         InitMultiSubGroup();
     }
 }
Beispiel #18
0
    protected void uxSubmit_Click(object sender, EventArgs e)
    {
        if (!uxCaptchaControl.UserValidated)
        {
            return;
        }

        string subject     = string.Empty;
        string contentBody = string.Empty;

        if (!String.IsNullOrEmpty(CurrentProductID))
        {
            Product product = DataAccessContext.ProductRepository.GetOne(
                StoreContext.Culture, CurrentProductID, new StoreRetriever().GetCurrentStoreID());

            SetUpEmail(product, out subject, out contentBody);
        }
        else if (!String.IsNullOrEmpty(PromotionGroupID))
        {
            PromotionGroup group = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(StoreContext.Culture, StoreContext.CurrentStore.StoreID, PromotionGroupID, BoolFilter.ShowTrue);

            SetUpEmailPromotion(group, out subject, out contentBody);
        }

        string emailBody = contentBody + uxMessage.Text;

        emailBody = AddHeaderText(emailBody);

        try
        {
            MailAddress mailAddr = new MailAddress(uxSenderText.Text.Trim());
            WebUtilities.SendHtmlMail(
                DataAccessContext.Configurations.GetValue("CompanyEmail"),
                uxRecipientText.Text.Trim(),
                subject,
                emailBody
                );
            Response.Redirect("TellFriendFinished.aspx");
        }
        catch (Exception)
        {
            uxErrorMessage.DisplayError("[$SentErrorMessage]");
        }
    }
    public void Show(PromotionSelected promotion, int quantity)
    {
        PromotionGroup promotionGroupSelected = promotion.GetPromotionGroup();
        Culture        culture         = StoreContext.Culture;
        string         productListText = "";

        foreach (PromotionSelectedItem item in promotion.PromotionSelectedItems)
        {
            productListText += "&nbsp;&nbsp;&ndash;&nbsp;&nbsp;" + item.Product.Locales[culture].Name + GenerateOptionName(culture, StoreContext.Currency, item) + " x " + item.GetPromotionProduct.Quantity.ToString() + "<BR>";
        }
        string name = promotionGroupSelected.Locales[culture].Name + "<BR>" + productListText;

        uxProductImage.ImageUrl       = "~/" + promotionGroupSelected.ImageFile;
        uxProductNameLink.NavigateUrl = UrlManager.GetPromotionUrl(promotionGroupSelected.PromotionGroupID, promotionGroupSelected.Locales[StoreContext.Culture].UrlName);
        uxProductNameLink.Text        = "<div class='ProductName'>" + name + "</div>";
        uxQuantityLabel.Text          = quantity.ToString();
        uxPriceLabel.Text             = StoreContext.Currency.FormatPrice(promotionGroupSelected.Price);
        uxMessage.Text = promotionGroupSelected.Name + "[$AddSuccess]";
        uxAddToCartPopup.Show();
    }
    public string GetImageUrl(object promotionGroupID)
    {
        string         imageUrl       = "";
        PromotionGroup promotionGroup = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(
            StoreContext.Culture,
            StoreContext.CurrentStore.StoreID,
            ConvertUtilities.ToString(promotionGroupID),
            BoolFilter.ShowAll);

        if (String.IsNullOrEmpty(promotionGroup.ImageFile) || promotionGroup.ImageFile.Equals("~/"))
        {
            imageUrl = "~/" + DataAccessContext.Configurations.GetValue("DefaultImageUrl");
        }
        else
        {
            imageUrl = "~/" + promotionGroup.ImageFile;
        }

        return(imageUrl);
    }
        /// <summary>
        /// Gets the new elements.
        /// </summary>
        /// <param name="expressionPlace">The expression place.</param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public override FilterExpressionNodeCollection GetNewElements(string expressionPlace, FilterExpressionNode parent)
        {
            FilterExpressionNodeCollection retVal = new FilterExpressionNodeCollection();
            //set default group
            string currentPromotionGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key;

            string[] expressionPlaceParts = expressionPlace.Split(':');
            if (expressionPlaceParts.Length != 0)
            {
                currentPromotionGroup = expressionPlaceParts[0];
            }
            IEnumerable <FilterExpressionNode> resultColl;

            _filterElementsMap.TryGetValue(currentPromotionGroup, out resultColl);
            if (resultColl != null)
            {
                retVal.AddRange(resultColl.Select(x => x.Clone()).ToArray());
            }

            return(retVal);
        }
Beispiel #22
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack && !String.IsNullOrEmpty(CurrentProductID))
        {
            ClearData();
            uxFromText.Text = string.Empty;

            MembershipUser user = Membership.GetUser();
            if (user != null &&
                Roles.IsUserInRole(user.UserName, "Customers"))
            {
                string   customerID = DataAccessContext.CustomerRepository.GetIDFromUserName(user.UserName);
                Customer customer   = DataAccessContext.CustomerRepository.GetOne(customerID);
                uxFromText.Text = customer.Email;
            }

            Product product = DataAccessContext.ProductRepository.GetOne(
                StoreContext.Culture, CurrentProductID, new StoreRetriever().GetCurrentStoreID());

            SetUpEmail(product);
        }
        else if (!IsPostBack && !String.IsNullOrEmpty(PromotionGroupID))
        {
            ClearData();
            uxFromText.Text = string.Empty;

            MembershipUser user = Membership.GetUser();
            if (user != null &&
                Roles.IsUserInRole(user.UserName, "Customers"))
            {
                string   customerID = DataAccessContext.CustomerRepository.GetIDFromUserName(user.UserName);
                Customer customer   = DataAccessContext.CustomerRepository.GetOne(customerID);
                uxFromText.Text = customer.Email;
            }

            PromotionGroup group = DataAccessContextDeluxe.PromotionGroupRepository.GetOne(StoreContext.Culture, StoreContext.CurrentStore.StoreID, PromotionGroupID, BoolFilter.ShowTrue);

            SetUpEmailPromotion(group);
        }
    }
 public virtual void Reset()
 {
     _helper = new PromotionHelper();
     _helper.PromotionContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key;
 }
 public PromotionGroup SetupImage(PromotionGroup promotionGroup)
 {
     promotionGroup.ImageFile = uxPromotionImageText.Text;
     return(promotionGroup);
 }
 public void PopulateControls(PromotionGroup promotionGroup)
 {
     uxPromotionImageText.Text = promotionGroup.ImageFile;
 }
        /// <summary>
        /// Gets the new elements.
        /// </summary>
        /// <param name="expressionPlace">The expression place.</param>
        /// <param name="parent"></param>
        /// <returns></returns>
        public override FilterExpressionNodeCollection GetNewElements(string expressionPlace, FilterExpressionNode parent)
        {
            List <FilterExpressionNode> retVal           = new List <FilterExpressionNode>();
            FilterExpressionNode        parentMethodNode = null;
            FilterExpressionNode        parentNext       = parent;

            //set default group
            string currentPromotionGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key;
            //expressionPlace
            string realExpressionPlace = string.Empty;

            //Get current promotion target group from ExpressionPlace {promotionGroup : custom controls data }
            string[] expressionPlaceParts = expressionPlace.Split(':');
            if (expressionPlaceParts.Length != 0)
            {
                currentPromotionGroup = expressionPlaceParts[0];
            }
            if (expressionPlaceParts.Length > 1)
            {
                realExpressionPlace = expressionPlaceParts[1];
            }

            IEnumerable <FilterExpressionNode> resultColl;

            _filterElementsMap.TryGetValue(currentPromotionGroup, out resultColl);
            //detected presents parent block type MethodBlock
            while (parentNext != null && parentMethodNode == null)
            {
                if (parentNext.NodeType == FilterExpressionNodeType.MethodBlock)
                {
                    parentMethodNode = parentNext;
                }
                parentNext = parentNext.ParentNode;
            }

            if (parent == null || parentMethodNode == null)
            {
                if (resultColl != null)
                {
                    //Add all registered element
                    retVal.AddRange(resultColl);
                }
            }
            else
            {
                if (resultColl != null)
                {
                    //Collections support
                    FilterExpressionNode parentNode             = FilterNodeFindRecursively(resultColl, x => x.Key == parentMethodNode.Key);
                    IEnumerable <FilterExpressionNode> childEls = null;
                    if (parentNode != null)
                    {
                        //gets all child element for current parrent node
                        childEls = parentNode.ChildNodes;
                    }
                    //is call from custom cotrol for get elements for binding
                    if (realExpressionPlace == "Sum")
                    {
                        ElementDefs parentElementDef = FindElementDef(parent.Key);
                        ElementDefs methodDef        = parentElementDef.GetMethodDef(parent.Method.Key);
                        //For method SUM return only Decimal type elemnts
                        if (methodDef == MethodSumDef)
                        {
                            var result = new List <FilterExpressionNode>();
                            foreach (FilterExpressionNode node in childEls)
                            {
                                ElementDefs nodeDef = FindElementDef(node.Key);
                                if (nodeDef != null && nodeDef.Conditions == ConditionDecimalDefs)
                                {
                                    result.Add(node);
                                }
                            }
                            childEls = result;
                        }
                        else
                        {
                            childEls = new FilterExpressionNode[] { };
                        }
                    }

                    retVal.AddRange(childEls);
                }
            }

            // Sort retVal By Name
            retVal.Sort(delegate(FilterExpressionNode x, FilterExpressionNode y)
                        { return(x.Name.CompareTo(y.Name)); });

            return(new FilterExpressionNodeCollection(retVal.Select(x => x.Clone(true)).ToArray()));
        }
        // Old stuff... no demo... Legacy Promos
        // This is a slightly-refactored version of the StoreHelper.GetDiscountPrice() method
        // catalogName and catalogNodeCode... can be used to filter out certain nodes or catalogs
        private static Price GetDiscountPriceInternal(EntryContentBase contentSku, Entry sku, IPriceValue price, string catalogName, string catalogNodeCode)
        {
            string catalogNodes = String.Empty;
            string catalogs     = String.Empty;

            // Now cycle through all the catalog nodes where this entry is present filtering by specified catalog and node code
            // Note: The nodes are only populated when Full or Nodes response group is specified.
            if (sku.Nodes != null && sku.Nodes.CatalogNode != null && sku.Nodes.CatalogNode.Length > 0)
            {
                foreach (CatalogNode node in sku.Nodes.CatalogNode)
                {
                    string entryCatalogName = CatalogContext.Current.GetCatalogDto(node.CatalogId).Catalog[0].Name;

                    // Skip filtered catalogs
                    if (!String.IsNullOrEmpty(catalogName) && !entryCatalogName.Equals(catalogName))
                    {
                        continue;
                    }

                    // Skip filtered catalogs nodes
                    if (!String.IsNullOrEmpty(catalogNodeCode) && !node.ID.Equals(catalogNodeCode, StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }

                    if (String.IsNullOrEmpty(catalogs))
                    {
                        catalogs = entryCatalogName;
                    }
                    else
                    {
                        catalogs += ";" + entryCatalogName;
                    }

                    if (String.IsNullOrEmpty(catalogNodes))
                    {
                        catalogNodes = node.ID;
                    }
                    else
                    {
                        catalogNodes += ";" + node.ID;
                    }
                }
            }

            if (String.IsNullOrEmpty(catalogs))
            {
                catalogs = catalogName;
            }

            if (String.IsNullOrEmpty(catalogNodes))
            {
                catalogNodes = catalogNodeCode;
            }

            // Get current context
            Dictionary <string, object> context = MarketingContext.Current.MarketingProfileContext;

            // Create filter
            PromotionFilter filter = new PromotionFilter
            {
                IgnoreConditions = false,
                IgnorePolicy     = false,
                IgnoreSegments   = false,
                IncludeCoupons   = false
            };

            // Create new entry
            // Note: catalogNodes is determined by GetParentNodes(entry)
            PromotionEntry result = new PromotionEntry(catalogs, catalogNodes, sku.ID, price.UnitPrice.Amount);
            var            promotionEntryPopulateService =
                (IPromotionEntryPopulate)MarketingContext.Current.PromotionEntryPopulateFunctionClassInfo.CreateInstance();

            promotionEntryPopulateService.Populate(result, sku, _currentMarket.Service.GetCurrentMarket().MarketId,
                                                   _currentMarket.Service.GetCurrentMarket().DefaultCurrency);

            PromotionEntriesSet sourceSet = new PromotionEntriesSet();

            sourceSet.Entries.Add(result);

            // Create new promotion helper, which will initialize PromotionContext object for us and setup context dictionary
            PromotionHelper helper = new PromotionHelper();

            // Only target entries
            helper.PromotionContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key;

            // Configure promotion context
            helper.PromotionContext.SourceEntriesSet = sourceSet;
            helper.PromotionContext.TargetEntriesSet = sourceSet;

            // Execute the promotions and filter out basic collection of promotions, we need to execute with cache disabled, so we get latest info from the database
            helper.Eval(filter);

            Money discountedAmount;

            // Check the count, and get new price if promotion is applied
            if (helper.PromotionContext.PromotionResult.PromotionRecords.Count > 0)
            {
                discountedAmount = new Money(price.UnitPrice.Amount -
                                             GetDiscountPriceFromPromotionResult(
                                                 helper.PromotionContext.PromotionResult),
                                             _currentMarket.Service.GetCurrentMarket().DefaultCurrency);

                return(new Price
                {
                    UnitPrice = discountedAmount,
                    ValidFrom = price.ValidFrom,
                    ValidUntil = price.ValidUntil,
                    MinQuantity = price.MinQuantity,
                    MarketId = price.MarketId,
                    EntryContent = contentSku,
                    CustomerPricing = price.CustomerPricing
                });
            }
            else
            {
                return(new Price(price));
            }
        }
Beispiel #28
0
        /// <summary>
        /// Calculates the discounts.
        /// </summary>
        private void CalculateDiscounts()
        {
            // Update manual discount amount
            UpdateManualDiscounts(OrderGroup);

            PromotionDto promotionDto = PromotionManager.GetPromotionDto(FrameworkContext.Current.CurrentDateTime);

            if (promotionDto.Promotion.Count == 0)
            {
                return;
            }

            // Get current context
            Dictionary <string, object> context = MarketingContext.Current.MarketingProfileContext;

            // Parameter that tells if we need to use cached values for promotions or not
            bool useCache = false;

            // Constract the filter, ignore conditions for now
            PromotionFilter filter = new PromotionFilter();

            filter.IgnoreConditions = false;
            filter.IgnorePolicy     = false;
            filter.IgnoreSegments   = false;
            filter.IncludeCoupons   = false;

            // Get property
            OrderGroup order = OrderGroup;

            decimal runningTotal = 0;

            foreach (OrderForm orderForm in order.OrderForms)
            {
                runningTotal +=
                    orderForm.LineItems.Where(c => !IsGiftLineItem(c)).Sum(x => x.Quantity * x.PlacedPrice);
            }

            // Create Promotion Context
            PromotionEntriesSet sourceSet = null;

            // Reuse the same context so we can track exclusivity properly
            PromotionContext promoContext = new PromotionContext(context, new PromotionEntriesSet(), new PromotionEntriesSet());

            promoContext.PromotionResult.RunningTotal = runningTotal;

            #region Determine Line item level discounts
            int totalNumberOfItems = 0;
            // Process line item discounts first
            foreach (OrderForm form in order.OrderForms)
            {
                foreach (OrderFormDiscount discount in form.Discounts)
                {
                    if (!discount.DiscountName.StartsWith("@") /* && discount.DiscountId == -1*/) // ignore custom entries
                    {
                        discount.Delete();
                    }
                }

                // Create source from current form
                sourceSet = CreateSetFromOrderForm(form);

                // Build dictionary to keep track of entry discount limit
                Dictionary <PromotionDto.PromotionRow, decimal?> entryDiscountApplicationCount = new Dictionary <PromotionDto.PromotionRow, decimal?>();
                foreach (PromotionDto.PromotionRow promotion in promotionDto.Promotion)
                {
                    if (!promotion.IsMaxEntryDiscountQuantityNull())
                    {
                        entryDiscountApplicationCount.Add(promotion, promotion.MaxEntryDiscountQuantity);
                    }
                }

                // Now cycle through each line item one by one
                IOrderedEnumerable <LineItem> highPlacedPriceFirst = form.LineItems.ToArray().OrderByDescending(x => x.PlacedPrice);
                int lineItemCount = highPlacedPriceFirst.Count();
                List <PromotionEntriesSet> entriesSetCollection = new List <PromotionEntriesSet>();
                foreach (LineItem lineItem in highPlacedPriceFirst)
                {
                    // First remove items
                    foreach (LineItemDiscount discount in lineItem.Discounts)
                    {
                        if (!discount.DiscountName.StartsWith("@") /* && discount.DiscountId == -1*/) // ignore custom entries
                        {
                            discount.Delete();
                        }
                    }
                    //Exclude gift lineItems from evaluation discounts process
                    if (IsGiftLineItem(lineItem))
                    {
                        continue;
                    }

                    totalNumberOfItems++;

                    // Target only entry promotions
                    PromotionEntriesSet targetSet = new PromotionEntriesSet();
                    targetSet.OrderFormId = form.OrderFormId.ToString();
                    //ET [16.06.2009] If order contains two item with same code, in target hit only first
                    //targetSet.Entries.Add(sourceSet.FindEntryByCode(lineItem.CatalogEntryId));
                    targetSet.Entries.Add(CreatePromotionEntryFromLineItem(lineItem));

                    entriesSetCollection.Add(targetSet);
                }

                promoContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key;
                // Evaluate conditions
                MarketingContext.Current.EvaluatePromotions(useCache, promoContext, filter, entryDiscountApplicationCount, sourceSet, entriesSetCollection, null);
                // from now on use cache
                useCache = true;
            }
            #endregion

            #region Determine Order level discounts
            List <PromotionEntriesSet> orderEntriesSetCollection = new List <PromotionEntriesSet>();
            foreach (OrderForm form in order.OrderForms)
            {
                // Now process global order discounts
                // Now start processing it
                // Create source from current form
                sourceSet = CreateSetFromOrderForm(form);
                orderEntriesSetCollection.Add(sourceSet);
            }
            promoContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key;
            // Evaluate conditions
            MarketingContext.Current.EvaluatePromotions(useCache, promoContext, filter, null, orderEntriesSetCollection, false);
            //Removing now not aplyied Gift discounts from Order
            RemoveGiftPromotionFromOrder(order, promoContext);

            #endregion

            #region Determine Shipping Discounts

            // add shipping fee to RunningTotal after calculating item and order level discounts, in order to apply shipping discounts.
            foreach (OrderForm orderForm in order.OrderForms)
            {
                foreach (Shipment shipment in orderForm.Shipments)
                {
                    promoContext.PromotionResult.RunningTotal += shipment.ShippingSubTotal;
                }
            }
            foreach (OrderForm form in order.OrderForms)
            {
                List <PromotionEntriesSet> shipmentEntriesSetCollection = new List <PromotionEntriesSet>();
                foreach (Shipment shipment in form.Shipments)
                {
                    // Remove old discounts if any
                    foreach (ShipmentDiscount discount in shipment.Discounts)
                    {
                        if (!discount.DiscountName.StartsWith("@") /* && discount.DiscountId == -1*/) // ignore custom entries
                        {
                            discount.Delete();
                        }
                    }

                    // Create content for current shipment

                    /*
                     * sourceSet = CreateSetFromOrderForm(form);
                     * promoContext.SourceEntriesSet.Entries = sourceSet.Entries;
                     * */
                    PromotionEntriesSet targetSet = CreateSetFromShipment(shipment);
                    shipmentEntriesSetCollection.Add(targetSet);
                }
                promoContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Shipping).Key;
                // Evaluate promotions
                MarketingContext.Current.EvaluatePromotions(useCache, promoContext, filter, null, shipmentEntriesSetCollection, false);
            }

            #endregion

            #region Start Applying Discounts
            foreach (PromotionItemRecord itemRecord in promoContext.PromotionResult.PromotionRecords)
            {
                if (itemRecord.Status != PromotionItemRecordStatus.Commited)
                {
                    continue;
                }

                // Pre process item record
                PreProcessItemRecord(order, itemRecord);


                // Applies discount and adjusts the running total
                if (itemRecord.AffectedEntriesSet.Entries.Count > 0)
                {
                    var discountAmount = ApplyItemDiscount(order, itemRecord, runningTotal);
                    if (!(itemRecord.PromotionReward is GiftPromotionReward))
                    {
                        runningTotal -= discountAmount;
                    }
                }
            }
            #endregion

            #region True up order level discounts (from Mark's fix for Teleflora)
            decimal orderLevelAmount        = 0;
            decimal lineItemOrderLevelTotal = 0;
            foreach (OrderForm form in order.OrderForms)
            {
                orderLevelAmount        += form.Discounts.Cast <OrderFormDiscount>().Where(y => !y.DiscountName.StartsWith("@")).Sum(x => x.DiscountValue);
                lineItemOrderLevelTotal += form.LineItems.ToArray().Sum(x => x.OrderLevelDiscountAmount);
                if (orderLevelAmount != lineItemOrderLevelTotal)
                {
                    form.LineItems[0].OrderLevelDiscountAmount += orderLevelAmount - lineItemOrderLevelTotal;
                }
            }
            #endregion
        }
Beispiel #29
0
        /// <summary>
        /// Applies the item discount.
        /// </summary>
        /// <param name="order">The order.</param>
        /// <param name="record">The record.</param>
        /// <param name="totalAmount">The total amount.</param>
        /// <returns></returns>
        private decimal ApplyItemDiscount(OrderGroup order, PromotionItemRecord record, decimal totalAmount)
        {
            decimal discountAmount = 0;

            if (record.PromotionReward.RewardType == PromotionRewardType.AllAffectedEntries)
            {
                decimal averageDiscountAmount;
                if (record.PromotionReward.AmountType == PromotionRewardAmountType.Percentage)
                {
                    discountAmount        = _currency.Percentage(record.AffectedEntriesSet.TotalCost, record.PromotionReward.AmountOff);
                    averageDiscountAmount = discountAmount / record.AffectedEntriesSet.TotalQuantity;
                }
                else // need to split discount between all items
                {
                    discountAmount        = record.PromotionReward.AmountOff;
                    averageDiscountAmount = record.PromotionReward.AmountOff / record.AffectedEntriesSet.TotalQuantity;
                }

                foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
                {
                    AddDiscountToLineItem(order, record, entry, averageDiscountAmount * entry.Quantity, 0);
                }
            }
            else if (record.PromotionReward.RewardType == PromotionRewardType.EachAffectedEntry)
            {
                if (record.PromotionReward.AmountType == PromotionRewardAmountType.Percentage)
                {
                    discountAmount = _currency.Percentage(record.AffectedEntriesSet.TotalCost, record.PromotionReward.AmountOff);
                    foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
                    {
                        AddDiscountToLineItem(order, record, entry, entry.CostPerEntry * entry.Quantity * record.PromotionReward.AmountOff / 100, 0);
                    }
                }
                else
                {
                    discountAmount = record.AffectedEntriesSet.TotalQuantity * record.PromotionReward.AmountOff;
                    foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
                    {
                        AddDiscountToLineItem(order, record, entry, record.PromotionReward.AmountOff * entry.Quantity, 0);
                    }
                }
            }
            else if (record.PromotionReward.RewardType == PromotionRewardType.WholeOrder)
            {
                decimal percentageOffTotal = 0;
                if (record.PromotionReward.AmountType == PromotionRewardAmountType.Percentage)
                {
                    decimal extendedCost = 0;
                    foreach (OrderForm orderForm in order.OrderForms)
                    {
                        extendedCost += orderForm.LineItems.ToArray().Sum(x => x.ExtendedPrice);
                    }
                    // calculate percentage adjusted by the running amount, so it will be a little less if running amount is less than total
                    percentageOffTotal = (record.PromotionReward.AmountOff / 100) * (totalAmount / extendedCost);
                    discountAmount     = _currency.Percentage(totalAmount, record.PromotionReward.AmountOff);
                }
                else
                {
                    // Calculate percentage off discount price
                    if (totalAmount > 0)
                    {
                        percentageOffTotal = record.PromotionReward.AmountOff / totalAmount;
                        // but since CostPerEntry is not an adjusted price, we need to take into account additional discounts already applied
                        percentageOffTotal = percentageOffTotal * (totalAmount / record.AffectedEntriesSet.TotalCost);
                        discountAmount     = record.PromotionReward.AmountOff;
                    }
                    else
                    {
                        percentageOffTotal = 100m;
                        discountAmount     = 0;
                    }
                }

                // Now distribute discount amount evenly over all entries taking into account running total
                // Special case for shipments, we consider WholeOrder to be a shipment
                if (!record.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Shipping).Key, StringComparison.OrdinalIgnoreCase))
                {
                    foreach (PromotionEntry entry in record.AffectedEntriesSet.Entries)
                    {
                        LineItem item = FindLineItemByPromotionEntry(order, entry);
                        var      orderLevelDiscount = _currency.Round(item.ExtendedPrice * percentageOffTotal);
                        AddDiscountToLineItem(order, record, entry, 0, orderLevelDiscount);
                    }
                }
            }

            // Save discounts
            if (record.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key, StringComparison.OrdinalIgnoreCase) ||
                record.PromotionReward is GiftPromotionReward)
            {
                if (record.PromotionReward.RewardType == PromotionRewardType.WholeOrder && discountAmount > 0)
                {
                    OrderFormDiscount discount = FindOrderFormDiscountById(order, record.PromotionItem.DataRow.PromotionId, Int32.Parse(record.AffectedEntriesSet.OrderFormId));
                    bool hasOrderFormDiscount  = true;
                    if (discount == null)
                    {
                        discount             = new OrderFormDiscount();
                        hasOrderFormDiscount = false;
                    }

                    var discountName = record.PromotionItem.DataRow.Name;
                    if (record.PromotionReward is GiftPromotionReward)
                    {
                        discountName = GetGiftPromotionName(record);
                    }
                    discount.DiscountName = discountName;

                    discount.DiscountAmount = record.PromotionReward.AmountOff;
                    discount.DiscountCode   = record.PromotionItem.DataRow.CouponCode;
                    discount.DiscountValue  = hasOrderFormDiscount ? discountAmount + discount.DiscountValue : discountAmount;
                    discount.DisplayMessage = GetDisplayName(record.PromotionItem.DataRow, Thread.CurrentThread.CurrentCulture.Name);
                    discount.OrderFormId    = Int32.Parse(record.AffectedEntriesSet.OrderFormId);
                    discount.DiscountId     = record.PromotionItem.DataRow.PromotionId;

                    foreach (OrderForm form in order.OrderForms)
                    {
                        if (form.OrderFormId == discount.OrderFormId && !hasOrderFormDiscount)
                        {
                            form.Discounts.Add(discount);
                        }
                    }
                }
            }
            else if (record.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Shipping).Key, StringComparison.OrdinalIgnoreCase))
            {
                ShipmentDiscount discount = FindShipmentDiscountById(order, record.PromotionItem.DataRow.PromotionId, Int32.Parse(record.AffectedEntriesSet.ShipmentId));

                if (discount == null)
                {
                    discount = new ShipmentDiscount();
                }

                discount.DiscountAmount = record.PromotionReward.AmountOff;
                discount.DiscountCode   = record.PromotionItem.DataRow.CouponCode;
                discount.DiscountName   = record.PromotionItem.DataRow.Name;
                discount.DisplayMessage = GetDisplayName(record.PromotionItem.DataRow, Thread.CurrentThread.CurrentCulture.Name);
                discount.ShipmentId     = Int32.Parse(record.AffectedEntriesSet.ShipmentId);
                discount.DiscountId     = record.PromotionItem.DataRow.PromotionId;

                var shipment = order.OrderForms.SelectMany(o => o.Shipments).FirstOrDefault(s => s.ShipmentId == discount.ShipmentId);
                if (shipment != null)
                {
                    shipment.Discounts.Add(discount);

                    if (record.PromotionReward.AmountType == PromotionRewardAmountType.Percentage)
                    {
                        discountAmount = _currency.Percentage(shipment.ShippingSubTotal, record.PromotionReward.AmountOff);
                    }
                    else
                    {
                        // PromotionReward.AmountOff was calculated in Promotion context, it's not be rounded.
                        discountAmount = _currency.Round(Math.Min(record.PromotionReward.AmountOff, shipment.ShippingSubTotal));
                    }

                    shipment.ShippingDiscountAmount = Math.Min(shipment.ShippingDiscountAmount + discountAmount, shipment.ShippingSubTotal);
                    // ShippingDiscountAmount will not be subtracted from the ShipmentTotal per discussions on 2/22/2012.
                }
                discount.DiscountValue = discountAmount;
            }
            return(discountAmount);
        }
Beispiel #30
0
        private void AddDiscountToLineItem(OrderGroup order, PromotionItemRecord itemRecord, PromotionEntry promotionEntry,
                                           decimal itemDiscount, decimal orderLevelDiscount)
        {
            itemDiscount       = _currency.Round(itemDiscount);
            orderLevelDiscount = _currency.Round(orderLevelDiscount);
            LineItem item = FindLineItemByPromotionEntry(order, promotionEntry);

            if (item != null)
            {
                //reset gift line item discount
                if (IsGiftLineItem(item))
                {
                    item.PlacedPrice              = promotionEntry.CostPerEntry;
                    item.LineItemDiscountAmount   = itemDiscount;
                    item.OrderLevelDiscountAmount = 0;
                    item.ExtendedPrice            = item.PlacedPrice;
                }
                else
                {
                    // Add line item properties
                    item.LineItemDiscountAmount   += itemDiscount;
                    item.OrderLevelDiscountAmount += orderLevelDiscount;
                    item.ExtendedPrice             = item.PlacedPrice * item.Quantity - item.LineItemDiscountAmount - item.OrderLevelDiscountAmount;
                }

                if (itemRecord.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key, StringComparison.OrdinalIgnoreCase) ||
                    itemRecord.PromotionReward is GiftPromotionReward ||
                    (itemRecord.PromotionItem.DataRow.PromotionGroup.Equals(PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key,
                                                                            StringComparison.OrdinalIgnoreCase) && itemRecord.PromotionReward.RewardType == PromotionRewardType.EachAffectedEntry))
                {
                    LineItemDiscount discount = FindLineItemDiscountById(order, itemRecord.PromotionItem.DataRow.PromotionId, item.LineItemId);

                    if (discount == null)
                    {
                        discount = new LineItemDiscount();
                        item.Discounts.Add(discount);
                    }

                    var discountName = itemRecord.PromotionItem.DataRow.Name;
                    if (itemRecord.PromotionReward is GiftPromotionReward)
                    {
                        discount.DiscountName = GetGiftPromotionName(itemRecord);
                    }
                    else
                    {
                        discount.DiscountName = String.Format("{0}{1}", itemRecord.PromotionItem.DataRow.Name,
                                                              itemRecord.PromotionItem.DataRow.OfferType == 1 ? ":PercentageBased" : ":ValueBased");
                    }

                    discount.DiscountAmount = itemRecord.PromotionReward.AmountOff;
                    discount.DiscountCode   = itemRecord.PromotionItem.DataRow.CouponCode;

                    discount.DiscountValue = itemDiscount;
                    // use the promotion name if the localized display message is null or empty
                    discount.DisplayMessage = GetDisplayName(itemRecord.PromotionItem.DataRow, Thread.CurrentThread.CurrentCulture.Name);
                    if (string.IsNullOrEmpty(discount.DisplayMessage))
                    {
                        discount.DisplayMessage = itemRecord.PromotionItem.DataRow.Name;
                    }
                    discount.LineItemId = item.LineItemId;
                    discount.DiscountId = itemRecord.PromotionItem.DataRow.PromotionId;
                }
            }
        }