public string GetOfferLabel(OfferRule offerRule, OfferAction action) { switch (action.OfferActionAttributeId) { case FIXED_PERCENT_DISCOUNT_FOR_PRODUCT_SUBSELECTION: case FIXED_PERCENT_DISCOUNT_FOR_WHOLE_CART: case FIXED_AMOUNT_DISCOUNT_FOR_WHOLE_CART: return(GetDefaultOfferLabel(offerRule) ?? "Sales"); case FREE_ITEM_OFFER: return(GetDefaultOfferLabel(offerRule) ?? "Free Gift"); case BUY_X_QUANTITY_FOR_Y_QUANTITY: return(GetDefaultOfferLabel(offerRule) ?? string.Format("{0} For {1}", offerRule.Action.XValue, offerRule.Action.YValue)); case BUY_X_QUANTITY_FOR_Y_PRICE: return(GetDefaultOfferLabel(offerRule) ?? string.Format("{0} For Price Of {1}", offerRule.Action.XValue, offerRule.Action.YValue)); case BUY_X_QUANTITY_CHEAPEST_FREE: return(GetDefaultOfferLabel(offerRule) ?? "Cheapest Free"); case DO_NOTHING: default: return(null); } }
private OfferRule BuildOfferRule(OfferRule rule) { var conditions = (List <OfferCondition>)GetOfferConditionListByOfferRuleId(rule.Id); if (conditions != null && conditions.Count > 0) { OfferCondition parent = conditions.Find(delegate(OfferCondition item) { return(item.ParentId == 0); }); if (parent != null) { rule.Condition = parent; rule.Condition.ChildOfferConditions = BuildTreeOfferConditionInfoByParent(parent, conditions, parent.Id); } } rule.Action = GetOfferActionByOfferRuleId(rule.Id); rule.RelatedItems = _offerRelatedItemRepository.Table.Where(o => o.OfferRuleId == rule.Id).ToList(); for (int i = 0; i < rule.RelatedItems.Count; i++) { var productId = rule.RelatedItems[i].ProductId; var product = _productRepository.Table.Where(x => x.Id == productId) .Select(x => new { x.Name, x.OptionType }) .FirstOrDefault(); if (product != null) { rule.RelatedItems[i].ProductName = product.Name; } } return(rule); }
private OfferRule BuildOfferRule(OfferRule rule) { var conditions = _offerConditionRepository.TableNoTracking.Where(c => c.OfferRuleId == rule.Id).ToList(); if (conditions != null && conditions.Count > 0) { for (int i = 0; i < conditions.Count; i++) { conditions[i] = DetermineOfferConditionType(conditions[i]); } var parent = conditions.Find(delegate(OfferCondition item) { return(item.ParentId == 0); }); if (parent != null) { rule.Condition = parent; rule.Condition.ChildOfferConditions = BuildTreeOfferConditionInfoByParent(parent, conditions, parent.Id); } } rule.Action = GetOfferActionByOfferRuleId(rule.Id); return(rule); }
private void InsertOffers(int ratePlanId, IList <OTA_HotelRatePlanRS.RatePlansLocalType.RatePlanLocalType.OffersLocalType> offers) { if (Check(offers)) { using (var context = new TravelDBContext()) { EfRepository <Offer> offerContext = new EfRepository <Offer>(context); EfRepository <OfferRule> offerRuleContext = new EfRepository <OfferRule>(context); Int32 offerInserted = -1; foreach (var offer in offers[0].Offer) { Offer offerModel = new Offer(); offerModel.OfferCode = Convert.ToInt32(offer.OfferCode); var description = offer.OfferDescription; if (Check(description)) { var descriptionText = description[0].Text; offerModel.OfferDescription = descriptionText; } var discounts = offer.Discount; if (Check(discounts)) { var discount = discounts[0]; offerModel.NightsDiscounted = Convert.ToInt32(discount.NightsDiscounted); offerModel.NightsRequired = Convert.ToInt32(discount.NightsRequired); offerModel.DiscountPattern = discount.DiscountPattern; } offerModel.ratePlanId = ratePlanId; offerContext.Insert(offerModel); LoggerHelper(ratePlanId, " Offer" + description + "Inserted"); offerInserted = offerModel.Id; var offerRules = offer.OfferRules; if (Check(offerRules) && Check(offerRules[0].OfferRule[0].DateRestriction)) { foreach (var item in offerRules[0].OfferRule[0].DateRestriction) { OfferRule or = new OfferRule(); or.RestrictionDateCode = Convert.ToInt32(item.RestrictionDateCode); or.LastModifyTime = DateTime.Now; or.OfferId = offerInserted; or.EndTime = item.End; or.StartTime = item.Start; or.RestrictionType = item.RestrictionType; offerRuleContext.Insert(or); LoggerHelper(ratePlanId, " Offer Rule" + or.RestrictionDateCode + "Inserted"); } } } } } }
public OfferRule GetOfferRuleById(int id) { OfferRule rule = _offerRuleRepository.Return(id); rule = BuildOfferRule(rule); return(rule); }
public OfferRule GetOfferRuleByPromocode(string promocode) { OfferRule rule = _offerRuleRepository.TableNoTracking.Where(o => o.PromoCode == promocode).FirstOrDefault(); if (rule != null) { rule = BuildOfferRule(rule); } return(rule); }
public OfferRule GetOfferRuleByUrlKey(string urlKey) { OfferRule rule = _offerRuleRepository.TableNoTracking.Where(o => o.UrlRewrite == urlKey).FirstOrDefault(); if (rule != null) { rule = BuildOfferRule(rule); } return(rule); }
public int CalculateActionMatchedQty(IList <CartItem> items, OfferRule offerRule, OfferCondition condition) { var matchedItems = GetActionMatchedItems(items, offerRule, condition); int qty = 0; if (matchedItems != null) { qty = matchedItems .Where(x => x.Product.OpenForOffer == true) .Select(x => x.Quantity).DefaultIfEmpty(0).Sum(); } return(qty); }
public decimal CalculateActionMatchedAmount(IList <CartItem> items, OfferRule offerRule, OfferCondition condition, bool isECcountry) { var matchedItems = GetActionMatchedItems(items, offerRule, condition); decimal amount = 0M; if (matchedItems != null) { if (offerRule.UseInitialPrice) { SetToUseInitialPrice(matchedItems); } if (isECcountry) { if (offerRule.UseInitialPrice) { amount = matchedItems .Where(x => x.Product.OpenForOffer == true) .Select(x => x.ProductPrice.PriceInclTax * x.Quantity).DefaultIfEmpty(0).Sum(); } else { amount = matchedItems .Where(x => x.Product.OpenForOffer == true) .Select(x => x.ProductPrice.OfferPriceInclTax * x.Quantity).DefaultIfEmpty(0).Sum(); } } else { if (offerRule.UseInitialPrice) { amount = matchedItems .Where(x => x.Product.OpenForOffer == true) .Select(x => x.ProductPrice.PriceExclTax * x.Quantity).DefaultIfEmpty(0).Sum(); } else { amount = matchedItems .Where(x => x.Product.OpenForOffer == true) .Select(x => x.ProductPrice.OfferPriceExclTax * x.Quantity).DefaultIfEmpty(0).Sum(); } } } return(amount); }
private string GetDefaultOfferLabel(OfferRule offerRule) { if (string.IsNullOrEmpty(offerRule.OfferLabel) == false) { return(offerRule.OfferLabel); } if (offerRule.OfferTypeId > 0) { var type = _offerTypeRepository.Return(offerRule.OfferTypeId); if (type != null) { return(type.Type); } } return(null); }
public bool ProcessOfferUpdation(OfferRule rule) { // Update offer rule _offerRuleRepository.Update(rule); // Remove conditions var offerConditions = _offerConditionRepository.Table.Where(x => x.OfferRuleId == rule.Id).ToList(); if (offerConditions != null) { foreach (var offerCondition in offerConditions) { _offerConditionRepository.Delete(offerCondition); } } // Create conditions InsertConditionWithOfferRuleId(rule.Condition, rule.Id); // Update action _offerActionRepository.Update(rule.Action); // Remove action conditions var actionConditions = _offerConditionRepository.Table.Where(x => x.OfferActionId == rule.Action.Id).ToList(); if (actionConditions != null) { foreach (var actionCondition in actionConditions) { _offerConditionRepository.Delete(actionCondition); } } // Update action conditions (if available) if (rule.Action.Condition != null) { InsertConditionWithOfferActionId(rule.Action.Condition, rule.Action.Id); } // Clear cache _cacheManager.RemoveByPattern(CacheKey.OFFER_RULE_PATTERN_KEY); return(false); }
public int ProcessOfferInsertion(OfferRule rule) { // Create offer rule int offerRuleId = _offerRuleRepository.Create(rule); // Create conditions InsertConditionWithOfferRuleId(rule.Condition, offerRuleId); // Create action rule.Action.OfferRuleId = offerRuleId; int offerActionId = _offerActionRepository.Create(rule.Action); // Create conditions from action (if available) if (rule.Action.Condition != null) { InsertConditionWithOfferActionId(rule.Action.Condition, offerActionId); } return(offerRuleId); }
public List <CartItem> GetActionMatchedItems(IList <CartItem> items, OfferRule offerRule, OfferCondition condition) { var matchedItems = items.Where(x => { // Exclude item bound to an offer provided that rule says offered item is NOT included if (x.ProductPrice.OfferRuleId > 0 && !offerRule.OfferedItemIncluded) { return(false); } // If there is no condition, matched as default if (condition.ChildOfferConditions.Count <= 0) { return(true); } return(ProcessCartActionCondition(condition, x)); }).ToList(); return(matchedItems); }
public Product ProcessCatalogOfferAction(Product product, OfferRule offerRule) { if (product == null) { _logger.InsertLog(LogLevel.Error, "Product is null."); return(product); } if (offerRule == null) { _logger.InsertLog(LogLevel.Error, "Offer rule is null."); return(product); } if (offerRule.Action == null) { _logger.InsertLog(LogLevel.Error, string.Format("Offer action is null. Offer rule ID={{{0}}}", offerRule.Id)); return(product); } bool isBySize = offerRule.Action.OptionOperator != null; // it could be colour too bool proceed = true; for (int i = 0; i < product.ProductPrices.Count; i++) { if (product.ProductPrices[i].OfferRuleId <= 0) { if (isBySize) { string option = product.ProductPrices[i].Size; proceed = _attributeUtility.ValidateAttribute(option, offerRule.Action.OptionOperator.Operator, offerRule.Action.OptionOperand); } if (proceed) { var assignOfferRuleId = true; switch (offerRule.Action.OfferActionAttributeId) { case BY_FIXED_AMOUNT: // Fixed amount is assumed to have tax included. product.ProductPrices[i].OfferPriceInclTax = product.ProductPrices[i].PriceInclTax - offerRule.Action.DiscountAmount.Value; product.ProductPrices[i].OfferPriceExclTax = product.ProductPrices[i].PriceExclTax - (offerRule.Action.DiscountAmount.Value / (100 + product.TaxCategory.Rate) * 100M); break; case BY_PERCENT_OF_THE_ORIGINAL_PRICE: product.ProductPrices[i].OfferPriceExclTax = product.ProductPrices[i].PriceExclTax / 100M * (100M - offerRule.Action.DiscountAmount.Value); product.ProductPrices[i].OfferPriceInclTax = product.ProductPrices[i].OfferPriceExclTax * (100 + product.TaxCategory.Rate) / 100M; break; case TO_FIXED_AMOUNT: // Fixed amount is assumed to have tax included. product.ProductPrices[i].OfferPriceInclTax = offerRule.Action.DiscountAmount.Value; product.ProductPrices[i].OfferPriceExclTax = offerRule.Action.DiscountAmount.Value / (100 + product.TaxCategory.Rate) * 100M; break; case TO_PERCENT_OF_THE_ORIGINAL_PRICE: product.ProductPrices[i].OfferPriceExclTax = product.ProductPrices[i].PriceExclTax / 100M * offerRule.Action.DiscountAmount.Value; product.ProductPrices[i].OfferPriceInclTax = product.ProductPrices[i].OfferPriceExclTax * (100 + product.TaxCategory.Rate) / 100M; break; case DO_NOTHING: assignOfferRuleId = false; break; } // Flag this item with offer rule id to isolate from other offers // It is important to check if we need to assign offer rule Id. If action is DO NOTHING, then we should not assign any offer rule Id at all if (assignOfferRuleId) { product.ProductPrices[i].OfferRuleId = offerRule.Action.OfferRuleId; } // Set fields for offer visibility on store front product.ProductPrices[i].ShowOfferTag = offerRule.ShowOfferTag; product.ProductPrices[i].ShowRRP = offerRule.ShowRRP; // Set expiry date if (offerRule.EndDate.HasValue) { product.CacheExpiryDate = offerRule.EndDate; } // Must make sure price excl tax is not zero // If action is DO NOTHING, do not add to related offer if (assignOfferRuleId && product.RelatedCatalogOffer == null && product.ProductPrices[i].PriceExclTax > 0) { product.RelatedCatalogOffer = new OfferRuleOverviewModel { Name = offerRule.Name, OfferTag = string.IsNullOrEmpty(offerRule.OfferLabel) ? string.Format("{0:#.##}% Off", (product.ProductPrices[i].PriceExclTax - product.ProductPrices[i].OfferPriceExclTax) / product.ProductPrices[i].PriceExclTax * 100) : offerRule.OfferLabel, UrlKey = offerRule.UrlRewrite, OfferRuleType = OfferRuleType.Catalog, DisableOfferLabel = offerRule.DisableOfferLabel, ShowInOfferPage = offerRule.ShowInOfferPage }; } } } } return(product); }
public CartOffer ProcessCartOfferAction(int profileId, IList <CartItem> items, string shippingCountryCode, OfferRule offerRule, OfferAction action, CartOffer cartOffer) { if (action == null) { return(cartOffer); } List <CartItem> list; decimal matchedAmount = 0M; decimal discount = 0M; int steps = 0; Country country = _countryRepository.Table.Where(x => x.ISO3166Code == shippingCountryCode).FirstOrDefault(); cartOffer.FreeDelivery = action.FreeShipping; cartOffer.RewardPoint += action.RewardPoint; switch (action.OfferActionAttributeId) { #region FIXED_PERCENT_DISCOUNT_FOR_PRODUCT_SUBSELECTION case FIXED_PERCENT_DISCOUNT_FOR_PRODUCT_SUBSELECTION: // Run acton condition first if (offerRule.Action.Condition != null && offerRule.Action.Condition.ChildOfferConditions.Count > 0) { matchedAmount = CalculateActionMatchedAmount(items, offerRule, action.Condition, country.IsEC); } else // Else use condition from offer rule.. { matchedAmount = CalculateActionMatchedAmount(items, offerRule, offerRule.Condition, country.IsEC); } discount = matchedAmount / 100M * action.DiscountAmount.Value; cartOffer.Discounts.Add(offerRule.Id, discount); cartOffer.DiscountAmount += discount; cartOffer.IsValid = true; break; #endregion #region FIXED_PERCENT_DISCOUNT_FOR_WHOLE_CART case FIXED_PERCENT_DISCOUNT_FOR_WHOLE_CART: if (country.IsEC) { discount = items.Select(x => x.ProductPrice.OfferPriceInclTax * x.Quantity) .DefaultIfEmpty(0).Sum() * Convert.ToInt32(action.DiscountAmount.Value) / 100; } else { discount = items.Select(x => x.ProductPrice.OfferPriceExclTax * x.Quantity) .DefaultIfEmpty(0).Sum() * Convert.ToInt32(action.DiscountAmount.Value) / 100; } cartOffer.DiscountAmount += discount; cartOffer.Discounts.Add(offerRule.Id, discount); cartOffer.IsValid = true; break; #endregion #region FIXED_AMOUNT_DISCOUNT_FOR_WHOLE_CART case FIXED_AMOUNT_DISCOUNT_FOR_WHOLE_CART: cartOffer.DiscountAmount += action.DiscountAmount.Value; cartOffer.Discounts.Add(offerRule.Id, action.DiscountAmount.Value); cartOffer.IsValid = true; break; #endregion #region FREE_ITEM_OFFER case FREE_ITEM_OFFER: bool proceed = false; if (action.MinimumAmount.HasValue) { if (action.Condition == null) { proceed = true; } else { proceed = CalculateActionMatchedAmount(items, offerRule, action.Condition, country.IsEC) > action.MinimumAmount.Value; } } else { proceed = true; } int qtyStep = 1; int qtyFound = 1; if (action.DiscountQtyStep.HasValue && proceed) { // To calculate how many free items need to be added qtyStep = action.DiscountQtyStep.Value; if (action.Condition == null || action.Condition.ChildOfferConditions.Count == 0) { qtyFound = CalculateActionMatchedQty(items, offerRule, offerRule.Condition); } else { qtyFound = CalculateActionMatchedQty(items, offerRule, action.Condition); } proceed = qtyFound > 0; } bool isByOption = action.OptionOperator != null; var foundList = new List <CartItem>(); // If there is an action condition if (offerRule.Action.Condition != null && offerRule.Action.Condition.ChildOfferConditions.Count > 0) { foundList = GetActionMatchedItems(items, offerRule, action.Condition); } else // Else use condition from offer rule { foundList = GetActionMatchedItems(items, offerRule, offerRule.Condition); } list = new List <CartItem>(); if (isByOption) { for (int i = 0; i < foundList.Count; i++) { if (foundList[i].ProductPrice.OfferRuleId <= 0) { string targetOption = foundList[i].ProductPrice.Option; bool isOkay = _attributeUtility.ValidateAttribute(targetOption, action.OptionOperator.Operator, action.OptionOperand); if (isOkay) { list.Add(foundList[i]); } } } if (list.Count > 0) { proceed = true; } } else { list = foundList; } if (proceed) { // TODO: Do we need to prevent other process? // Flag item with offer rule id to prevent other process //FlagOfferRuleIdInBasket(action.OfferRuleId, list.Select(x => x.Id).ToList()); // Add free item if (action.FreeProductItself.Value) { for (int i = 0; i < list.Count; i++) { if (list[i].Product == null) { _logger.InsertLog(LogLevel.Warning, string.Format("Free item could not be loaded. Product ID={{{0}}}", list[i].ProductId)); break; } if (list[i].ProductPrice == null) { _logger.InsertLog(LogLevel.Warning, string.Format("Product price for free item could not be loaded. Product Price ID={{{0}}}", list[i].ProductPriceId)); break; } if (list[i].Product.Brand == null) { _logger.InsertLog(LogLevel.Warning, string.Format("Brand for free item could not be loaded. Brand ID={{{0}}}", list[i].Product.BrandId)); break; } var message = _cartValidator.ValidateCartItem( profileId, list[i].ProductId, list[i].Product.BrandId, shippingCountryCode, list[i].Product.IsPharmaceutical, list[i].Product.Discontinued, list[i].ProductPrice.Stock, list[i].Product.Name, list[i].Product.EnforceStockCount, list[i].Product.Brand.EnforceStockCount, list[i].Product.Enabled, list[i].ProductPrice.Enabled, list[i].Quantity, list[i].Quantity / qtyStep, list[i].Product.StepQuantity, list[i].Product.IsPhoneOrder, list[i].ProductPrice.OfferPriceExclTax, allowZeroPrice: true); // Empty message is ok status from cart item validation if (string.IsNullOrEmpty(message)) { var cartItem = new CartItem { ProfileId = profileId, ProductPriceId = list[i].ProductPriceId, ProductId = list[i].ProductId, Quantity = list[i].Quantity / qtyStep, Product = list[i].Product, ProductPrice = list[i].ProductPrice, CartItemMode = (int)CartItemMode.FreeItem }; items.Add(cartItem); } } } else { // Load free item var freeItem = _productBuilder.Build(action.FreeProductId.Value); if (freeItem == null) { _logger.InsertLog(LogLevel.Warning, string.Format("Free item could not be loaded. Product ID={{{0}}}", action.FreeProductId.Value)); break; } var freeItemPriceOption = freeItem.ProductPrices.Where(x => x.Id == action.FreeProductPriceId).FirstOrDefault(); if (freeItemPriceOption == null) { _logger.InsertLog(LogLevel.Warning, string.Format("Product price for free item could not be loaded. Product Price ID={{{0}}}", action.FreeProductPriceId)); break; } if (freeItem.Brand == null) { _logger.InsertLog(LogLevel.Warning, string.Format("Brand for free item could not be loaded. Brand ID={{{0}}}", freeItem.BrandId)); break; } // While stock lasts if (freeItemPriceOption.Stock > 0) { var message = _cartValidator.ValidateCartItem( profileId, freeItem.Id, freeItem.BrandId, shippingCountryCode, freeItem.IsPharmaceutical, freeItem.Discontinued, freeItemPriceOption.Stock, freeItem.Name, freeItem.EnforceStockCount, freeItem.Brand.EnforceStockCount, freeItem.Enabled, freeItemPriceOption.Enabled, 0, action.FreeProductQty.Value * (qtyFound / qtyStep), freeItem.StepQuantity, freeItem.IsPhoneOrder, freeItemPriceOption.OfferPriceExclTax, allowZeroPrice: true); // Empty message is ok status from cart item validation if (string.IsNullOrEmpty(message)) { var cartItem = new CartItem { ProfileId = profileId, ProductPriceId = freeItemPriceOption.Id, ProductId = freeItem.Id, Quantity = action.FreeProductQty.Value * (qtyFound / qtyStep), Product = freeItem, ProductPrice = freeItemPriceOption, CartItemMode = (int)CartItemMode.FreeItem }; items.Add(cartItem); } } } } cartOffer.IsValid = true; break; #endregion #region DO_NOTHING case DO_NOTHING: // do nothing cartOffer.IsValid = true; break; #endregion #region BUY_X_QUANTITY_FOR_Y_QUANTITY case BUY_X_QUANTITY_FOR_Y_QUANTITY: // Must have X quantity // Must have Y quantity // X > Y if (offerRule.Action.XValue.HasValue && offerRule.Action.YValue.HasValue && offerRule.Action.XValue > offerRule.Action.YValue) { list = new List <CartItem>(); if (offerRule.Action.Condition != null && offerRule.Action.Condition.ChildOfferConditions.Count > 0) // If there is condition for action { list = GetActionMatchedItems(items, offerRule, action.Condition); } else // Else use condition from offer rule.. { list = GetActionMatchedItems(items, offerRule, offerRule.Condition); } // Revert to old price if necessary if (offerRule.UseInitialPrice) { SetToUseInitialPrice(list); } // List down individual price List <decimal> listIndividualPrice = new List <decimal>(); for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list[i].Quantity; j++) { if (country.IsEC) { listIndividualPrice.Add(list[i].ProductPrice.OfferPriceInclTax); } else { listIndividualPrice.Add(list[i].ProductPrice.OfferPriceExclTax); } } } // Calculate how many steps for X quantity steps = listIndividualPrice.Count / offerRule.Action.XValue.Value; // Find quantity X of total value decimal totalXValue = 0M; for (int i = 0; i < offerRule.Action.XValue.Value; i++) { if (i < listIndividualPrice.Count) { totalXValue += listIndividualPrice[i]; } } // Find quantity Y of total value decimal totalYValue = 0M; for (int i = 0; i < offerRule.Action.YValue.Value; i++) { if (i < listIndividualPrice.Count) { totalYValue += listIndividualPrice[i]; } } // Get the difference decimal differenceValue = totalXValue - totalYValue; discount = steps * differenceValue; cartOffer.DiscountAmount += discount; cartOffer.Discounts.Add(offerRule.Id, discount); } cartOffer.IsValid = true; break; #endregion #region BUY_X_QUANTITY_FOR_Y_PRICE case BUY_X_QUANTITY_FOR_Y_PRICE: // Must have X quantity // Must have Y price if (offerRule.Action.XValue.HasValue && offerRule.Action.YValue.HasValue) { list = new List <CartItem>(); if (offerRule.Action.Condition != null && offerRule.Action.Condition.ChildOfferConditions.Count > 0) // If there is condition for action { list = GetActionMatchedItems(items, offerRule, action.Condition); } else // Else use condition from offer rule.. { list = GetActionMatchedItems(items, offerRule, offerRule.Condition); } // Revert to old price if necessary if (offerRule.UseInitialPrice) { SetToUseInitialPrice(list); } // List down individual price List <decimal> listIndividualPrice = new List <decimal>(); decimal totalValue = 0M; for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list[i].Quantity; j++) { if (country.IsEC) { listIndividualPrice.Add(list[i].ProductPrice.OfferPriceInclTax); totalValue += list[i].ProductPrice.OfferPriceInclTax; } else { listIndividualPrice.Add(list[i].ProductPrice.OfferPriceExclTax); totalValue += list[i].ProductPrice.OfferPriceExclTax; } } } // Calculate how many steps for X quantity steps = listIndividualPrice.Count / offerRule.Action.XValue.Value; // Find total value int lastRemoveCount = listIndividualPrice.Count % offerRule.Action.XValue.Value; if (lastRemoveCount != 0) { for (int i = 0; i < lastRemoveCount; i++) { totalValue -= listIndividualPrice[listIndividualPrice.Count - 1 - i]; } } // Find total value of Y in current currency decimal totalYValue = steps * (offerRule.Action.YValue.Value); // Get the difference discount = totalValue - totalYValue; cartOffer.DiscountAmount += discount; cartOffer.Discounts.Add(offerRule.Id, discount); } cartOffer.IsValid = true; break; #endregion #region BUY_X_QUANTITY_CHEAPEST_FREE case BUY_X_QUANTITY_CHEAPEST_FREE: // Must have X quantity if (offerRule.Action.XValue.HasValue) { list = new List <CartItem>(); if (offerRule.Action.Condition != null && offerRule.Action.Condition.ChildOfferConditions.Count > 0) // If there is condition for action { list = GetActionMatchedItems(items, offerRule, action.Condition); } else // Else use condition from offer rule.. { list = GetActionMatchedItems(items, offerRule, offerRule.Condition); } // List down individual price List <decimal> listIndividualPrice = new List <decimal>(); decimal totalValue = 0M; for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list[i].Quantity; j++) { if (country.IsEC) { listIndividualPrice.Add(list[i].ProductPrice.OfferPriceInclTax); totalValue += list[i].ProductPrice.OfferPriceInclTax; } else { listIndividualPrice.Add(list[i].ProductPrice.OfferPriceExclTax); totalValue += list[i].ProductPrice.OfferPriceExclTax; } } } // Calculate how many steps for X quantity steps = listIndividualPrice.Count / offerRule.Action.XValue.Value; // Get the smallest price listIndividualPrice.Sort(delegate(decimal price1, decimal price2) { return(price1.CompareTo(price2)); }); for (int i = 0; i < steps; i++) { discount += listIndividualPrice[i]; } cartOffer.DiscountAmount += discount; cartOffer.Discounts.Add(offerRule.Id, discount); } cartOffer.IsValid = true; break; #endregion } cartOffer.DiscountAmount = Math.Round(cartOffer.DiscountAmount, 2, MidpointRounding.AwayFromZero); return(cartOffer); }
protected void lbSave_Click(object sender, EventArgs e) { string urlKey = txtUrlKey.Text.Trim(); // If urlKey is empty, regenerate with given name if (urlKey == string.Empty) { urlKey = AdminStoreUtility.GetFriendlyUrlKey(txtRuleAlias.Text.Trim()); txtUrlKey.Text = urlKey; } // Make sure urlKey is unique if (((OfferService.GetOfferRuleByUrlKey(urlKey) != null) && (OfferService.GetOfferRuleByUrlKey(urlKey).Id != QueryOfferRuleId))) { enbNotice.Message = "Offer was failed to create. URL key is not unique."; } else { string htmlMsg; if (ftbDesc.Visible) { htmlMsg = AdminStoreUtility.CleanFtbOutput(ftbDesc.Text); } else { htmlMsg = txtDescription.Text.Trim(); } var rule = new OfferRule { Name = txtRuleName.Text.Trim(), ProceedForNext = Convert.ToBoolean(rblProceed.SelectedValue), IsActive = Convert.ToBoolean(rblStatus.SelectedValue), IsCart = true, PromoCode = txtPromoCode.Text.Trim(), UsesPerCustomer = Convert.ToInt32(txtUsesPerCust.Text.Trim()), Priority = Convert.ToInt32(txtPriority.Text.Trim()), HtmlMessage = htmlMsg, OfferedItemIncluded = cbOfferedItemIncluded.Checked, Alias = txtRuleAlias.Text.Trim(), ShowOfferTag = false, ShowRRP = false, ShortDescription = string.Empty, LongDescription = string.Empty, SmallImage = string.Empty, LargeImage = string.Empty, UrlRewrite = urlKey, ShowInOfferPage = false, OfferUrl = string.Empty, PointSpendable = chkPointSpendable.Checked, UseInitialPrice = cbUseInitialPrice.Checked, NewCustomerOnly = cbNewCustomerOnly.Checked, ShowCountDown = cbShowCountDownTimer.Checked, DisplayOnProductPage = cbDisplayOnProductPage.Checked, OfferTypeId = Convert.ToInt32(ddlOfferTypes.SelectedValue) }; if (ddlRelatedTypes.SelectedValue != string.Empty) { switch (ddlRelatedTypes.SelectedValue) { case "products": rule.RelatedProducts = txtRelatedItems.Text.ToString(); break; case "brands": rule.RelatedBrands = txtRelatedItems.Text.ToString(); break; case "category": rule.RelatedCategory = txtRelatedItems.Text.ToString(); break; } } if (!string.IsNullOrEmpty(txtDateFrom.Text.Trim())) { rule.StartDate = DateTime.ParseExact(txtDateFrom.Text, AppConstant.DATE_FORM1, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(txtDateTo.Text.Trim())) { rule.EndDate = DateTime.ParseExact(txtDateTo.Text, AppConstant.DATE_FORM1, CultureInfo.InvariantCulture); } object freeProductItself = DBNull.Value; object freeProductId = DBNull.Value; object freeProductPriceId = DBNull.Value; object freeProductQty = DBNull.Value; // Determine if there is any free item settings if (rbFreeItself.Checked || rbFreeItem.Checked) { freeProductItself = rbFreeItself.Checked; if (rbFreeItem.Checked) { freeProductId = txtFreeProductId.Text.Trim(); freeProductPriceId = txtFreeProductPriceId.Text.Trim(); freeProductQty = txtFreeQuantity.Text.Trim(); } } object discountQtyStep = DBNull.Value; object minimumAmount = DBNull.Value; object discountAmount = DBNull.Value; int rewardPoint = 0; if (txtDiscountQtyStep.Text.Trim() != string.Empty) { discountQtyStep = txtDiscountQtyStep.Text.Trim(); } if (txtMinimumAmount.Text.Trim() != string.Empty) { minimumAmount = txtMinimumAmount.Text.Trim(); } if (txtDiscountAmount.Text.Trim() != string.Empty) { discountAmount = txtDiscountAmount.Text.Trim(); } if (txtRewardPoint.Text.Trim() != string.Empty) { rewardPoint = Convert.ToInt32(txtRewardPoint.Text.Trim()); } // Retrieve option target if any object optionOperatorId = DBNull.Value; object optionOperator = DBNull.Value; object optionOperand = DBNull.Value; if (txtOption.Text.Trim() != string.Empty) { optionOperand = txtOption.Text.Trim(); optionOperatorId = ddlOptionOperator.SelectedValue; optionOperator = OfferService.GetOfferOperator(Convert.ToInt32(optionOperatorId)).Operator; } // Assign action to this rule object's action var newAction = new OfferAction(); if (discountAmount != DBNull.Value) { newAction.DiscountAmount = Convert.ToDecimal(discountAmount); } if (freeProductItself != DBNull.Value) { newAction.FreeProductItself = Convert.ToBoolean(freeProductItself); } if (freeProductId != DBNull.Value) { newAction.FreeProductId = Convert.ToInt32(freeProductId); } if (freeProductPriceId != DBNull.Value) { newAction.FreeProductPriceId = Convert.ToInt32(freeProductPriceId); } if (freeProductQty != DBNull.Value) { newAction.FreeProductQty = Convert.ToInt32(freeProductQty); } newAction.OfferActionAttributeId = Convert.ToInt32(ddlAction.SelectedValue); newAction.Name = ddlAction.SelectedItem.Text; newAction.IsCart = true; if (discountQtyStep != DBNull.Value) { newAction.DiscountQtyStep = Convert.ToInt32(discountQtyStep); } if (minimumAmount != DBNull.Value) { newAction.MinimumAmount = Convert.ToDecimal(minimumAmount); } newAction.RewardPoint = rewardPoint; if (optionOperatorId != DBNull.Value) { newAction.OptionOperatorId = Convert.ToInt32(optionOperatorId); } if (optionOperand != DBNull.Value) { newAction.OptionOperand = Convert.ToString(optionOperand); } if ((optionOperator != DBNull.Value) && (optionOperatorId != DBNull.Value)) { newAction.OptionOperator = new OfferOperator { Id = Convert.ToInt32(optionOperatorId), Operator = Convert.ToString(optionOperator) } } ; newAction.XValue = Convert.ToInt32(txtXValue.Text.Trim()); newAction.YValue = Convert.ToDecimal(txtYValue.Text.Trim()); rule.Action = newAction; var proceed = true; // Assign root condition to this rule object's condition rule.Condition = OfferUtility.OfferRuleConditions[QueryTempOfferRuleId]; if (rule.Condition == null) { enbNotice.Message = "Offer was failed to create. There is no condition setup for this offer. It could be due to session lost. Please try to create again."; proceed = false; } // Assign root condition to this action object's condition rule.Action.Condition = OfferUtility.OfferActionConditions[QueryTempOfferRuleId]; if (rule.Action.Condition == null) { enbNotice.Message = "Offer was failed to create. There is no <u>action</u> condition setup for this offer. It could be due to session lost. Please try to create again."; proceed = false; } if (proceed) { // Save into database var id = OfferService.ProcessOfferInsertion(rule); ResetCartOfferSessions(); // Redirect to info page Response.Redirect("/marketing/promo_cart_offer_info.aspx?offerruleid=" + id + "&" + QueryKey.MSG_TYPE + "=" + (int)MessageType.OfferCreated); } } }
protected void lbSave_Click(object sender, EventArgs e) { string urlKey = txtUrlKey.Text.Trim(); // If urlKey is empty, regenerate with given name if (urlKey == string.Empty) { urlKey = AdminStoreUtility.GetFriendlyUrlKey(txtRuleAlias.Text.Trim()); txtUrlKey.Text = urlKey; } // Make sure urlKey is unique if (((OfferService.GetOfferRuleByUrlKey(urlKey) != null) && (OfferService.GetOfferRuleByUrlKey(urlKey).Id != QueryOfferRuleId))) { enbNotice.Message = "Offer was failed to create. URL key is not unique."; } else { // Instantiate rule object var rule = new OfferRule { Name = txtRuleName.Text.Trim(), ProceedForNext = Convert.ToBoolean(rblProceed.SelectedValue), IsActive = Convert.ToBoolean(rblStatus.SelectedValue), Priority = Convert.ToInt32(txtPriority.Text.Trim()), Alias = txtRuleAlias.Text.Trim(), ShowOfferTag = chkShowOfferTag.Checked, ShowRRP = chkShowRRP.Checked, ShortDescription = string.Empty, LongDescription = string.Empty, SmallImage = string.Empty, LargeImage = string.Empty, UrlRewrite = urlKey, ShowInOfferPage = false, OfferUrl = string.Empty, PointSpendable = chkPointSpendable.Checked, ShowCountDown = cbShowCountDownTimer.Checked, DisplayOnProductPage = cbDisplayOnProductPage.Checked, OfferTypeId = Convert.ToInt32(ddlOfferTypes.SelectedValue) }; if (!string.IsNullOrEmpty(txtDateFrom.Text.Trim())) { rule.StartDate = DateTime.ParseExact(txtDateFrom.Text, AppConstant.DATE_FORM1, CultureInfo.InvariantCulture); } if (!string.IsNullOrEmpty(txtDateTo.Text.Trim())) { rule.EndDate = DateTime.ParseExact(txtDateTo.Text, AppConstant.DATE_FORM1, CultureInfo.InvariantCulture); } if (ddlRelatedTypes.SelectedValue != string.Empty) { switch (ddlRelatedTypes.SelectedValue) { case "products": rule.RelatedProducts = txtRelatedItems.Text.ToString(); break; case "brands": rule.RelatedBrands = txtRelatedItems.Text.ToString(); break; case "category": rule.RelatedCategory = txtRelatedItems.Text.ToString(); break; } } // Assign action to this rule object's action var newAction = new OfferAction { Name = ddlAction.SelectedItem.Text, IsCatalog = true, DiscountAmount = Convert.ToDecimal(txtDiscountAmount.Text), OfferActionAttributeId = Convert.ToInt32(ddlAction.SelectedValue) }; // Retrieve size target if any string optionOperatorId = null; string optionOperator = null; string optionOperand = null; if (txtOption.Text.Trim() != string.Empty) { optionOperand = txtOption.Text.Trim(); optionOperatorId = ddlOptionOperator.SelectedValue; optionOperator = OfferService.GetOfferOperator(Convert.ToInt32(optionOperatorId)).Operator; } if (!string.IsNullOrEmpty(optionOperatorId)) { newAction.OptionOperatorId = Convert.ToInt32(optionOperatorId); } if (!string.IsNullOrEmpty(optionOperand)) { newAction.OptionOperand = Convert.ToString(optionOperand); } if ((!string.IsNullOrEmpty(optionOperator)) && (!string.IsNullOrEmpty(optionOperatorId))) { newAction.OptionOperator = new OfferOperator { Id = Convert.ToInt32(optionOperatorId), Operator = Convert.ToString(optionOperator) } } ; rule.Action = newAction; var proceed = true; // Assign root condition to this rule object's condition rule.Condition = OfferUtility.OfferRuleConditions[QueryTempOfferRuleId]; if (rule.Condition == null) { enbNotice.Message = "Offer was failed to create. There is no condition setup for this offer. It could be due to session lost. Please try to create again."; proceed = false; } if (proceed) { // Save into database var id = OfferService.ProcessOfferInsertion(rule); // Reset value ResetCatalogOfferSessions(); // Redirect to info page Response.Redirect("/marketing/promo_catalog_offer_info.aspx?offerruleid=" + id + "&" + QueryKey.MSG_TYPE + "=" + (int)MessageType.OfferCreated); } } }