/// <summary> /// Populates the line item. /// </summary> /// <param name="entry">The entry.</param> /// <param name="lineItem">The line item.</param> private void PopulateLineItem(ref PromotionEntry entry, LineItem lineItem) { entry.Quantity = lineItem.Quantity; entry.Owner = lineItem; // Save line item id, so it is easier to distinguish to which item discount is applied entry["LineItemId"] = lineItem.LineItemId; entry["ShippingAddressId"] = lineItem.ShippingAddressId; entry["MinQuantity"] = lineItem.MinQuantity; entry["MaxQuantity"] = lineItem.MaxQuantity; entry["LineItemDiscountAmount"] = lineItem.LineItemDiscountAmount; entry["OrderLevelDiscountAmount"] = lineItem.OrderLevelDiscountAmount; entry["ShippingMethodName"] = lineItem.ShippingMethodName ?? string.Empty; entry["ExtendedPrice"] = lineItem.ExtendedPrice; entry["Description"] = lineItem.Description ?? string.Empty; entry["Status"] = lineItem.Status ?? string.Empty; entry["DisplayName"] = lineItem.DisplayName ?? string.Empty; entry["AllowBackordersAndPreorders"] = lineItem.AllowBackordersAndPreorders; entry["InStockQuantity"] = lineItem.InStockQuantity; entry["PreorderQuantity"] = lineItem.PreorderQuantity; entry["BackorderQuantity"] = lineItem.BackorderQuantity; entry["InventoryStatus"] = lineItem.InventoryStatus; // Now populate all the custom meta fields foreach (MetaField field in lineItem.MetaClass.MetaFields) { entry[field.Name] = lineItem[field]; } }
public void MerketingSystem_BuyXGetNoffYatReducedPrice() { PromotionEntriesSet sourceSet = new PromotionEntriesSet(); PromotionEntriesSet targetSet = new PromotionEntriesSet(); PromotionEntry itemY1 = new PromotionEntry("", "Apple iPod touch 16 GB (Old)", "ELCB000JNYWBG6", 100); PromotionEntry itemY2 = new PromotionEntry("", "Apple iPod touch 16 GB (Old)", "ELCB000JNYWBG6", 100); itemY2.Quantity = 10; PromotionEntry itemXspecified = new PromotionEntry("", "Plantronics Voyager 510 - Bluetooth Headset Carrying Case", "ELCB000FOM68A6", 100); PromotionEntry itemXnotspecified = new PromotionEntry("", "510 Headset Charger", "ELCB000GKLGX46", 100); PromotionFilter filter = new PromotionFilter(); filter.IgnoreConditions = false; //Exsist promotion //X promotion entry set is ELCB000PBOWNK6, ELCB000GKLGX46 //Exclude set to off //Y promotion entry is ELCB000JNYWBG6 //Max Y quantity is 3 //Amount 15 percent //First use case. X entry not contains in promotion X entry set itemXnotspecified.Quantity = 2; sourceSet.Entries.Add(itemXnotspecified); //Two Y entry one 1 quantity , other 10 quantity targetSet.Entries.Add(itemY1); targetSet.Entries.Add(itemY2); PromotionContext context = PrepareMarketingContext(sourceSet, targetSet); MarketingContext.Current.EvaluatePromotions(true, context, filter); Assert.IsTrue(context.PromotionResult.PromotionRecords.Count == 0); //Second use case. X entry contains in promotion X entry set sourceSet.Entries.Clear(); sourceSet.Entries.Add(itemXspecified); context = PrepareMarketingContext(sourceSet, targetSet); MarketingContext.Current.EvaluatePromotions(true, context, filter); Assert.IsTrue(context.PromotionResult.PromotionRecords.Count == 1); foreach (PromotionItemRecord record in context.PromotionResult.PromotionRecords) { Assert.IsTrue(record.AffectedEntriesSet.TotalQuantity == 3); Assert.IsTrue(record.PromotionReward.AmountOff == 15); } //Third use case. X entry empty. Y entry specified. First instanse of item Y becomes the eligible item X, and charged bu regular price sourceSet.Entries.Clear(); targetSet.Entries.Clear(); itemY1.Quantity = 3; targetSet.Entries.Add(itemY1); context = PrepareMarketingContext(sourceSet, targetSet); MarketingContext.Current.EvaluatePromotions(true, context, filter); Assert.IsTrue(context.PromotionResult.PromotionRecords.Count == 1); foreach (PromotionItemRecord record in context.PromotionResult.PromotionRecords) { Assert.IsTrue(record.AffectedEntriesSet.TotalQuantity == 2); Assert.IsTrue(record.PromotionReward.AmountOff == 15); } }
public void MerketingSystem_BuyXOffShipment_10PercentOff() { // three Promotion #1 - 10 MinQuantity, 5$ reward; // #2 - 20 MinQuantity, 10$ Reward; // #3 - 30 MinQuantity 15$ Reward. PromotionEntriesSet sourceSet = new PromotionEntriesSet(); PromotionEntry entry = new PromotionEntry("", "", "Plasma-EDTV", 100); entry.Quantity = 20; sourceSet.Entries.Add(entry); MarketingContext ctx = MarketingContext.Current; Assert.IsNotNull(ctx); Assert.IsNotNull(ctx.MarketingProfileContext); //IDictionary<string, object> ctx = new Dictionary<string, object>(); PromotionContext context = new PromotionContext(ctx.MarketingProfileContext, sourceSet, sourceSet); PromotionFilter filter = new PromotionFilter(); filter.IgnoreConditions = false; MarketingContext.Current.EvaluatePromotions(true, context, filter); foreach (PromotionItemRecord record in context.PromotionResult.PromotionRecords) { decimal amountOff = record.PromotionReward.AmountOff; // Validate promotion Assert.IsTrue(amountOff == 10); } }
/// <summary> /// Creates the promotion entry from line item. /// </summary> /// <param name="lineItem">The line item.</param> /// <returns></returns> private PromotionEntry CreatePromotionEntryFromLineItem(LineItem lineItem) { PromotionEntry entry = new PromotionEntry(lineItem.Catalog, lineItem.CatalogNode, lineItem.CatalogEntryId, lineItem.ListPrice); ((IPromotionEntryPopulate)MarketingContext.Current.PromotionEntryPopulateFunctionClassInfo.CreateInstance()).Populate(ref entry, lineItem); return(entry); }
private void Populate(PromotionEntry entry, EntryContentBase catalogEntry, IPriceValue price) { entry.Quantity = 1; entry.Owner = catalogEntry; entry["Id"] = catalogEntry.Code; if (catalogEntry.Property != null) { foreach (var prop in catalogEntry.Property.Where(x => x.IsPropertyData)) { entry[prop.Name] = prop.Value; } } entry["ExtendedPrice"] = price.UnitPrice.Amount; var inventories = _inventoryService.List(price.CatalogKey, _warehouseRepository.List()).ToList(); if (!inventories.Any()) { return; } entry["AllowBackordersAndPreorders"] = inventories.Any(i => i.AllowBackorder) && inventories.Any(i => i.AllowPreorder); entry["InStockQuantity"] = inventories.Sum(i => i.InStockQuantity - i.ReservedQuantity); entry["PreorderQuantity"] = inventories.Sum(i => i.PreorderQuantity); entry["BackorderQuantity"] = inventories.Sum(i => i.BackorderQuantity); entry["InventoryStatus"] = inventories.First().InventoryStatus; }
private void Populate(PromotionEntry entry, EntryContentBase catalogEntry, IPriceValue price) { entry.Quantity = 1; entry.Owner = catalogEntry; entry["Id"] = catalogEntry.Code; if (catalogEntry.Property != null) { foreach (var prop in catalogEntry.Property.Where(x => x.IsPropertyData)) { entry[prop.Name] = prop.Value; } } entry["ExtendedPrice"] = price.UnitPrice.Amount; var inventories = _inventoryService.QueryByEntry(new [] { price.CatalogKey.CatalogEntryCode }).ToList(); if (!inventories.Any()) { return; } entry["AllowBackordersAndPreorders"] = inventories.Any(i => i.CanBackorder(DateTime.UtcNow)) && inventories.Any(i => i.CanPreorder(DateTime.UtcNow)); entry["InStockQuantity"] = inventories.Sum(i => i.BackorderAvailableQuantity); entry["PreorderQuantity"] = inventories.Sum(i => i.PreorderAvailableQuantity); entry["BackorderQuantity"] = inventories.Sum(i => i.BackorderAvailableQuantity); }
private PromotionEntry GetPromotionEntryFromLineItem(LineItem lineItem) { var populate = PromotionEntryPopulate; var entry = new PromotionEntry(lineItem.Catalog, lineItem.CatalogItemId, lineItem.ExtendedPrice / lineItem.Quantity); populate.Populate(ref entry, lineItem); return(entry); }
/// <summary> /// Creates the promotion entry from line item. /// </summary> /// <param name="lineItem">The line item.</param> /// <returns></returns> private PromotionEntry CreatePromotionEntryFromLineItem(LineItem lineItem) { string catalogNodes = String.Empty; string catalogs = String.Empty; string catalogName = lineItem.Catalog; string catalogNodeCode = lineItem.CatalogNode; // Now cycle through all the catalog nodes where this entry is present filtering by specified catalog and node code // The nodes are only populated when Full or Nodes response group is specified. // Request full response group so we can reuse the same cached item Entry entry = CatalogContext.Current.GetCatalogEntry(lineItem.Code, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Nodes)); if (entry != null && entry.Nodes != null && entry.Nodes.CatalogNode != null && entry.Nodes.CatalogNode.Length > 0) { foreach (CatalogNode node in entry.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; } } } PromotionEntry result = new PromotionEntry(catalogs, catalogNodes, lineItem.Code, lineItem.PlacedPrice); var promotionEntryPopulateService = (IPromotionEntryPopulate)MarketingContext.Current.PromotionEntryPopulateFunctionClassInfo.CreateInstance(); promotionEntryPopulateService.Populate(result, lineItem); return(result); }
public PromotionEnrichedForCart(PromotionEntry entry) { id = entry.id; Message = entry.Message; qualifyingProducts = entry.qualifyingProducts; reward = entry.reward; maxRewardQuantity = entry.maxRewardQuantity; nextTieredDealLevel = entry.nextTieredDealLevel; nextTieredDealQualifyingQuantity = entry.nextTieredDealQualifyingQuantity; nextTieredDealRewardQuantity = entry.nextTieredDealRewardQuantity; nextTieredDealQualifyingQuantityLiters = entry.nextTieredDealQualifyingQuantityLiters; }
private PromotionEntry CreatePromotionEntry(EntryContentBase entry, IPriceValue price) { var catalogNodes = string.Empty; var catalogs = string.Empty; foreach (var node in entry.GetNodeRelations(_linksRepository).Select(x => _contentLoader.Get<NodeContent>(x.Target))) { var entryCatalogName = _catalogSystem.GetCatalogDto(node.CatalogId).Catalog[0].Name; catalogs = string.IsNullOrEmpty(catalogs) ? entryCatalogName : catalogs + ";" + entryCatalogName; catalogNodes = string.IsNullOrEmpty(catalogNodes) ? node.Code : catalogNodes + ";" + node.Code; } var promotionEntry = new PromotionEntry(catalogs, catalogNodes, entry.Code, price.UnitPrice.Amount); Populate(promotionEntry, entry, price); return promotionEntry; }
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 PromotionEntrySet GetPromotionEntrySetFromItem(Item item, decimal price, Hashtable tags) { var set = new PromotionEntrySet(); var populate = new PromotionEntryPopulate(); var entry = new PromotionEntry(tags ?? new Hashtable()) { CostPerEntry = price }; populate.Populate(ref entry, item); set.Entries.Add(entry); return(set); }
private PromotionEntry CreatePromotionEntry(EntryContentBase entry, IPriceValue price) { var catalogNodes = string.Empty; var catalogs = string.Empty; foreach (var node in entry.GetNodeRelations(_linksRepository).Select(x => _contentLoader.Get <NodeContent>(x.Target))) { var entryCatalogName = _catalogSystem.GetCatalogDto(node.CatalogId).Catalog[0].Name; catalogs = string.IsNullOrEmpty(catalogs) ? entryCatalogName : catalogs + ";" + entryCatalogName; catalogNodes = string.IsNullOrEmpty(catalogNodes) ? node.Code : catalogNodes + ";" + node.Code; } var promotionEntry = new PromotionEntry(catalogs, catalogNodes, entry.Code, price.UnitPrice.Amount); Populate(promotionEntry, entry, price); return(promotionEntry); }
public IEnumerable <PromotionEntry> PreparePromotionEntries(IEnumerable <PromotionEntry> entries) { foreach (PromotionEntry entry in entries) { PromotionEntry retVal = entry; LineItem ownerLineItem = retVal.Owner != null ? retVal.Owner as LineItem : null; if (ownerLineItem == null) { foreach (LineItem lineItem in this.PromotionCurrentOrderForm.LineItems) { if (lineItem.CatalogEntryId == entry.CatalogEntryCode) { ownerLineItem = lineItem; break; } } } if (ownerLineItem == null) { ownerLineItem = new LineItem(); } //PromotionFilterExpressionProvider.CopyLineItemTopromotionEntryProperty(retVal, ownerLineItem); object shippingAddressId = retVal["ShippingAddressId"]; if (this.ShoppingCart != null && shippingAddressId != null) { //found OrderAddress by address id OrderAddress orderAddress = null; foreach (OrderAddress address in this.ShoppingCart.OrderAddresses) { if (address.Name.ToString() == shippingAddressId.ToString()) { orderAddress = address; break; } } //if (orderAddress != null) //{ // //copy all properties OrderAddress to entry // PromotionFilterExpressionProvider.CopyOrderAddressToPromotionEntryProperty(retVal, orderAddress); //} } yield return(retVal); } }
/// <summary> /// Get info from entry and update properties accordingly /// </summary> /// <param name="entry"></param> private void ParseEntry(JournalEntry entry) { if (entry.Event == "FSDJump") { FSDJumpEntry jumpInfo = (FSDJumpEntry)entry; FuelLevel = jumpInfo.FuelLevel; CurrentPosition = jumpInfo.StarPos; } else if (entry.Event == "FuelScoop") { FuelScoopEntry scoopInfo = (FuelScoopEntry)entry; FuelLevel = scoopInfo.Total; } else if (entry.Event == "LoadGame") { LoadGameEntry loadGameInfo = (LoadGameEntry)entry; FuelLevel = loadGameInfo.FuelLevel; FuelCapacity = loadGameInfo.FuelCapacity; } else if (entry.Event == "Location") { LocationEntry locationInfo = (LocationEntry)entry; CurrentPosition = locationInfo.StarPos; } else if (entry.Event == "Promotion") { PromotionEntry promotionInfo = (PromotionEntry)entry; if (promotionInfo.RankName == "Explore") { RankExplore = new Rank("Exploration", promotionInfo.NewRank); } } else if (entry.Event == "Rank") { RankEntry rankInfo = (RankEntry)entry; RankExplore = new Rank("Exploration", rankInfo.Explore); } else if (entry.Event == "RefuelAll" || entry.Event == "RefuelPartial") { RefuelEntry refuelInfo = (RefuelEntry)entry; FuelLevel += refuelInfo.Amount; } UpdateProperties(); }
/// <summary> /// Creates the set from shipment. /// </summary> /// <param name="shipment">The shipment.</param> /// <returns></returns> private PromotionEntriesSet CreateSetFromShipment(Shipment shipment) { PromotionEntriesSet set = new PromotionEntriesSet(); set.OwnerId = shipment.ShipmentId.ToString(); foreach (string lineItemIndex in shipment.LineItemIndexes) { LineItem lineItem = shipment.Parent.LineItems[Int32.Parse(lineItemIndex)]; if (lineItem != null) { PromotionEntry entry = CreatePromotionEntryFromLineItem(lineItem); set.Entries.Add(entry); } } return(set); }
/// <summary> /// Populates the specified promotion entry with attribute values from the val object. Automatically adds all the meta fields. /// The objects supported are LineItem and Entry. /// </summary> /// <param name="entry">The entry.</param> /// <param name="val">The val. Can be LineItem or Entry.</param> public void Populate(ref PromotionEntry entry, object val) { if (!(val is LineItem) && !(val is Entry)) { throw new InvalidCastException("This interface only support types of LineItem or Entry"); } if (val is LineItem) { LineItem lineItem = val as LineItem; PopulateLineItem(ref entry, lineItem); } else { Entry catEntry = val as Entry; PopulateCatalogEntry(ref entry, catEntry); } }
/// <summary> /// Adds the free gift to cart. /// </summary> /// <remarks> This method using in promotion actions rulset</remarks> /// <param name="quantity">The quantity.</param> /// <param name="entryCodes">The entry codes.</param> public void AddFreeGiftToCart(string quantity, params string[] entryCodes) { decimal giftQuantity = Convert.ToDecimal(quantity, System.Globalization.CultureInfo.InvariantCulture); GiftPromotionReward giftAddWhenNeedReward = new GiftPromotionReward(PromotionRewardType.EachAffectedEntry, 0, PromotionRewardAmountType.Percentage, GiftPromotionReward.Strategy.AddWhenNeeded); PromotionEntriesSet giftEntrySet = new PromotionEntriesSet(); giftEntrySet.OwnerId = this.PromotionContext.TargetEntriesSet.OwnerId; foreach (string entryCode in entryCodes) { PromotionEntry entry = new PromotionEntry(entryCode, entryCode, entryCode, 0); entry.Quantity = giftQuantity; giftEntrySet.Entries.Add(entry); } this.AddPromotionItemRecord(giftAddWhenNeedReward, giftEntrySet); }
private static LineItem FindLineItemByPromotionEntry(OrderGroup order, PromotionEntry prmotionEntry) { LineItem retVal = null; foreach (OrderForm form in order.OrderForms) { foreach (LineItem item in form.LineItems) { if (item == prmotionEntry.Owner) { retVal = item; break; } } if (retVal != null) { break; } } return(retVal); }
/// <summary> /// Populates the catalog entry. /// </summary> /// <param name="entry">The entry.</param> /// <param name="catEntry">The cat entry.</param> private void PopulateCatalogEntry(ref PromotionEntry entry, Entry catEntry) { entry.Quantity = 1; entry.Owner = catEntry; // Save line item id, so it is easier to distinguish to which item discount is applied entry["Id"] = catEntry.ID; if (catEntry.ItemAttributes != null) { entry["MinQuantity"] = catEntry.ItemAttributes.MinQuantity; entry["MaxQuantity"] = catEntry.ItemAttributes.MaxQuantity; entry["ExtendedPrice"] = catEntry.ItemAttributes.ListPrice; if (catEntry.ItemAttributes.Attribute != null) { // Now populate all the custom attributes foreach (ItemAttribute attr in catEntry.ItemAttributes.Attribute) { if (attr.Value != null && attr.Value.Length > 0) { entry[attr.Name] = attr.Value[0]; } } } } if (catEntry.Inventory != null) { entry["AllowBackordersAndPreorders"] = catEntry.Inventory.AllowBackorder && catEntry.Inventory.AllowPreorder; entry["InStockQuantity"] = catEntry.Inventory.InStockQuantity; entry["PreorderQuantity"] = catEntry.Inventory.PreorderQuantity; entry["BackorderQuantity"] = catEntry.Inventory.BackorderQuantity; entry["InventoryStatus"] = catEntry.Inventory.InventoryStatus; } }
/// <summary> /// Creates the entry from target. /// </summary> /// <param name="entryCode">The entry code.</param> /// <param name="quantity">The quantity.</param> /// <returns></returns> public PromotionEntriesSet CreatePromotionEntriesSetFromTarget(string entryCode, decimal quantity) { PromotionEntriesSet retVal = new PromotionEntriesSet(); retVal.OwnerId = this.PromotionContext.TargetEntriesSet.OwnerId; foreach (PromotionEntry entry in PromotionContext.TargetEntriesSet.Entries) { if (quantity == 0) { break; } if (entry.CatalogEntryCode.Equals(entryCode, StringComparison.CurrentCultureIgnoreCase)) { PromotionEntry entryToAdd = (PromotionEntry)entry.Clone(); entryToAdd.Quantity = Math.Min(quantity, entryToAdd.Quantity); quantity -= entryToAdd.Quantity; retVal.Entries.Add(entryToAdd); } } return(retVal); }
/// <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); } } }
/// <summary> /// Gets the discount price by evaluating the discount rules and taking into account segments customer belongs to. /// </summary> /// <param name="entry">The entry.</param> /// <param name="catalogName">Name of the catalog.</param> /// <returns></returns> public static Price GetDiscountPrice(Entry entry, string catalogName) { if (entry == null) { throw new NullReferenceException("entry can't be null"); } 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; } // Get sale price for the current user Price price = StoreHelper.GetSalePrice(entry, minQuantity); // Create new promotion helper, which will initialize PromotionContext object for us and setup context dictionary PromotionHelper helper = new PromotionHelper(); // Get current context Dictionary <string, object> context = MarketingContext.Current.MarketingProfileContext; // Create filter PromotionFilter filter = new PromotionFilter(); filter.IgnoreConditions = false; filter.IgnorePolicy = false; filter.IgnoreSegments = false; filter.IncludeCoupons = false; // Create new entry PromotionEntry promotEntry = new PromotionEntry(catalogName, String.Empty, entry.ID, price.Amount); // Populate entry parameters ((IPromotionEntryPopulate)MarketingContext.Current.PromotionEntryPopulateFunctionClassInfo.CreateInstance()).Populate(ref promotEntry, entry); PromotionEntriesSet sourceSet = new PromotionEntriesSet(); sourceSet.Entries.Add(promotEntry); // Configure promotion context helper.PromotionContext.SourceEntriesSet = sourceSet; helper.PromotionContext.TargetEntriesSet = sourceSet; // Only target entries helper.PromotionContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key; // 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); // Check the count, and get new price if (helper.PromotionContext.PromotionResult.PromotionRecords.Count > 0) { return(ObjectHelper.CreatePrice(price.Amount - GetDiscountPrice(helper.PromotionContext.PromotionResult), price.CurrencyCode)); } else { return(price); } }
// 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)); } }
/// <summary> /// Creates the promotion entry from line item. /// </summary> /// <param name="lineItem">The line item.</param> /// <returns></returns> private PromotionEntry CreatePromotionEntryFromLineItem(LineItem lineItem) { string catalogNodes = String.Empty; string catalogs = String.Empty; string catalogName = lineItem.Catalog; string catalogNodeCode = lineItem.CatalogNode; // Now cycle through all the catalog nodes where this entry is present filtering by specified catalog and node code // The nodes are only populated when Full or Nodes response group is specified. // Request full response group so we can reuse the same cached item Entry entry = CatalogContext.Current.GetCatalogEntry(lineItem.Code, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Nodes)); if (entry != null && entry.Nodes != null && entry.Nodes.CatalogNode != null && entry.Nodes.CatalogNode.Length > 0) { foreach (CatalogNode node in entry.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; } } PromotionEntry result = new PromotionEntry(catalogs, catalogNodes, lineItem.Code, lineItem.PlacedPrice); var promotionEntryPopulateService = (IPromotionEntryPopulate)MarketingContext.Current.PromotionEntryPopulateFunctionClassInfo.CreateInstance(); promotionEntryPopulateService.Populate(result, lineItem); return result; }
private static LineItem FindLineItemByPromotionEntry(OrderGroup order, PromotionEntry prmotionEntry) { LineItem retVal = null; foreach (OrderForm form in order.OrderForms) { foreach (LineItem item in form.LineItems) { if (item == prmotionEntry.Owner) { retVal = item; break; } } if (retVal != null) break; } return retVal; }
private void AddDiscountToLineItem(OrderGroup order, PromotionItemRecord itemRecord, PromotionEntry promotionEntry, decimal itemDiscount, decimal orderLevelDiscount) { orderLevelDiscount = Math.Floor(orderLevelDiscount * 100) * 0.01m; 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; } } }
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; } } }