public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.Product == null)
            {
                return(false);
            }
            if (context.UserPrice == null)
            {
                return(false);
            }

            string match = context.Product.ProductTypeId.Trim().ToLowerInvariant();

            // for "generic" type we need to match 0 instead of empty string
            if (match == string.Empty)
            {
                match = "0";
            }

            return(this.CurrentTypeIds().Contains(match));
        }
        public override bool ApplyAction(PromotionContext context)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.Order == null)
            {
                return(false);
            }

            // only apply when applying to sub total
            if (context.Mode != PromotionType.OfferForOrder)
            {
                return(false);
            }

            var adjustment = 0m;

            switch (AdjustmentType)
            {
            case AmountTypes.MonetaryAmount:
                adjustment = Money.GetDiscountAmount(context.Order.GetTotal(false, false, false), Amount);
                break;

            case AmountTypes.Percent:
                adjustment = Money.GetDiscountAmountByPercent(context.Order.GetTotal(false, false, false), Amount);
                break;
            }

            context.Order.AddOrderDiscount(adjustment, context.CustomerDescription, context.PromotionId, Id);

            return(true);
        }
        public void Execute(PromotionContext context)
        {
            var promotion = context.Promotion;

            if (String.IsNullOrEmpty(promotion.PromotionPolicyData))
            {
                return;
            }

            var data = DefaultPromotionPolicyData.Deserialize(promotion.PromotionPolicyData);

            if (data.DiscountAppliedTo == DiscountAppliedTo.MatchedProducts)
            {
                foreach (var matchedItem in context.ConditionMatchedItems)
                {
                    matchedItem.Subtotal.AddDiscount(
                        ComputeDiscount(matchedItem.Subtotal.OriginalValue, data));
                }
            }
            else if (data.DiscountAppliedTo == DiscountAppliedTo.OrderShipping)
            {
                context.PricingContext.ShippingCost.AddDiscount(
                    ComputeDiscount(context.PricingContext.ShippingCost.OriginalValue, data));
            }
            else if (data.DiscountAppliedTo == DiscountAppliedTo.OrderSubtotal)
            {
                context.PricingContext.Subtotal.AddDiscount(
                    ComputeDiscount(context.PricingContext.Subtotal.OriginalValue, data));
            }
        }
Exemple #4
0
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.Mode != PromotionType.Offer)
            {
                return(false);
            }
            if (context.Order == null)
            {
                return(false);
            }
            if (context.Order.ShippingMethodId.Trim().Length < 1)
            {
                return(false);
            }

            foreach (string itemid in this.ItemIds())
            {
                if (context.Order.ShippingMethodId == itemid)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #5
0
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.CurrentCustomer == null)
            {
                return(false);
            }
            if (context.CurrentCustomer.Bvin == string.Empty)
            {
                return(false);
            }

            string currentId = context.CurrentCustomer.Bvin.Trim().ToUpperInvariant();

            foreach (string uid in UserIds())
            {
                if (currentId == uid)
                {
                    return(true);
                }
            }

            return(false);
        }
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.Mode != PromotionType.Offer)
            {
                return(false);
            }
            if (context.Order == null)
            {
                return(false);
            }
            if (context.Order.Coupons == null)
            {
                return(false);
            }

            foreach (string coupon in CurrentCoupons())
            {
                if (context.Order.CouponCodeExists(coupon))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #7
0
        public override bool MeetsQualification(PromotionContext context, PromotionQualificationMode mode)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.Order == null)
            {
                return(false);
            }
            if (context.Order.Items == null)
            {
                return(false);
            }

            if (mode == PromotionQualificationMode.LineItems)
            {
                if (context.CurrentlyProcessingLineItem == null)
                {
                    return(false);
                }

                var li = context.CurrentlyProcessingLineItem;

                return(MeetLineItem(context, li));
            }
            if (mode == PromotionQualificationMode.Orders)
            {
                var items = context.Order.Items;
                return(items.Any(i => MeetLineItem(context, i)));
            }

            return(false);
        }
Exemple #8
0
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.Mode != PromotionType.Offer)
            {
                return(false);
            }
            if (context.Order == null)
            {
                return(false);
            }
            if (context.Order.Items == null)
            {
                return(false);
            }

            switch (SetMode)
            {
            case QualificationSetMode.AnyOfTheseItems:
                return(MatchAny(this.Quantity, context.Order.Items, this.CurrentProductIds()));

            case QualificationSetMode.AllOfTheseItems:
                return(MatchAll(this.Quantity, context.Order.Items, this.CurrentProductIds()));
            }

            return(false);
        }
        public override bool ApplyAction(PromotionContext context, PromotionActionMode mode)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.Product == null)
            {
                return(false);
            }

            decimal adjustment = 0m;

            switch (this.AdjustmentType)
            {
            case AmountTypes.MonetaryAmount:
                adjustment = Utilities.Money.GetDiscountAmount(context.UserPrice.BasePrice, this.Amount);
                break;

            case AmountTypes.Percent:
                adjustment = Utilities.Money.GetDiscountAmountByPercent(context.UserPrice.BasePrice, this.Amount);
                break;
            }

            context.UserPrice.AddAdjustment(adjustment, context.CustomerDescription);

            return(true);
        }
        private void CleanItemFromCart(PromotionContext context, Dictionary <string, int> products)
        {
            var needUpdate = false;

            foreach (var bvin in products.Keys)
            {
                var li = context.Order.Items.FirstOrDefault(i => i.ProductId.ToUpperInvariant() == bvin);

                if (li != null)
                {
                    var freeCount = li.GetFreeCountByPromotionId(context.PromotionId);

                    if (freeCount != -1)
                    {
                        needUpdate = true;
                        context.Order.Items.Remove(li);
                    }
                }
            }

            if (needUpdate)
            {
                context.HccApp.OrderServices.Orders.Update(context.Order);
            }
        }
Exemple #11
0
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.Order == null) return false;

            return true;
        }
Exemple #12
0
        public override bool MeetsQualification(PromotionContext context, PromotionQualificationMode mode)
        {
            if (mode != PromotionQualificationMode.Orders && mode != PromotionQualificationMode.LineItems)
            {
                return(false);
            }
            if (context == null)
            {
                return(false);
            }
            if (context.Order == null)
            {
                return(false);
            }
            if (context.Order.Coupons == null)
            {
                return(false);
            }

            foreach (var coupon in CurrentCoupons())
            {
                if (context.Order.CouponCodeExists(coupon))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #13
0
        public override bool ApplyAction(PromotionContext context)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.CurrentCustomer == null)
            {
                return(false);
            }
            if (context.Mode != PromotionType.Affiliate)
            {
                return(false);
            }

            if (Recipient == RecipientType.Self)
            {
                return(context.HccApp.CustomerPointsManager.IssuePoints(context.CurrentCustomer.Bvin, Amount));
            }
            if (Recipient == RecipientType.ReferralAffiliate)
            {
                var userId = Convert.ToInt32(context.CurrentCustomer.Bvin);
                var aff    = context.HccApp.ContactServices.Affiliates.FindByUserId(userId);
                if (aff != null && aff.Enabled)
                {
                    var refAff = context.HccApp.ContactServices.Affiliates.FindByAffiliateId(aff.ReferralAffiliateId);
                    if (refAff != null && refAff.Enabled)
                    {
                        return(context.HccApp.CustomerPointsManager.IssuePoints(refAff.UserId.ToString(), Amount));
                    }
                }
            }

            return(false);
        }
        public override bool ApplyAction(PromotionContext context, PromotionActionMode mode)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.Order == null)
            {
                return(false);
            }

            // only apply when applying to shipping areas
            if (mode != PromotionActionMode.ForShipping)
            {
                return(false);
            }

            decimal adjustment = 0m;

            switch (this.AdjustmentType)
            {
            case AmountTypes.MonetaryAmount:
                adjustment = Utilities.Money.GetDiscountAmount(context.Order.TotalShippingBeforeDiscounts, this.Amount);
                break;

            case AmountTypes.Percent:
                adjustment = Utilities.Money.GetDiscountAmountByPercent(context.Order.TotalShippingBeforeDiscounts, this.Amount);
                break;
            }

            context.Order.AddShippingDiscount(adjustment, context.CustomerDescription);

            return(true);
        }
Exemple #15
0
        public override bool MeetsQualification(PromotionContext context, PromotionQualificationMode mode)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.CurrentCustomer == null)
            {
                return(false);
            }
            if (context.CurrentCustomer.Bvin == string.Empty)
            {
                return(false);
            }

            var customer = context.CurrentCustomer;
            var roles    = GetCustomerRoles(customer);
            var roleIds  = GetRoleIds();

            foreach (var role in roles)
            {
                if (roleIds.Contains(role.RoleID))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #16
0
        public override bool MeetsQualification(PromotionContext context, PromotionQualificationMode mode)
        {
            if (context == null)
            {
                return(false);
            }
            if (context.CurrentCustomer == null)
            {
                return(false);
            }
            if (string.IsNullOrEmpty(context.CurrentCustomer.Bvin))
            {
                return(false);
            }

            var userId    = Convert.ToInt32(context.CurrentCustomer.Bvin);
            var affiliate = context.HccApp.ContactServices.Affiliates.FindByUserId(userId);

            if (HasReffferalID)
            {
                var refAffiliate =
                    context.HccApp.ContactServices.Affiliates.FindByAffiliateId(affiliate.ReferralAffiliateId);
                return(refAffiliate != null && refAffiliate.Enabled && affiliate.Approved && affiliate.Enabled);
            }

            return(affiliate.Approved && affiliate.Enabled);
        }
Exemple #17
0
        public override bool MeetsQualification(PromotionContext context, PromotionQualificationMode mode)
        {
            if (context == null)
            {
                return(false);
            }

            var idToTest = context.CurrentShippingMethodId.Trim();

            if (idToTest.Length < 1)
            {
                if (context.Order == null)
                {
                    return(false);
                }
                idToTest = context.Order.ShippingMethodId.Trim();
            }
            if (idToTest.Length < 1)
            {
                return(false);
            }

            foreach (var itemid in ItemIds())
            {
                if (idToTest.ToUpperInvariant() == itemid.ToUpperInvariant())
                {
                    return(true);
                }
            }

            return(false);
        }
        public void Execute(PromotionContext context)
        {
            var data = context.PolicyConfig as DefaultPromotionPolicyConfig;

            if (data == null)
            {
                return;
            }

            if (data.DiscountAppliedTo == DiscountAppliedTo.MatchedProducts)
            {
                foreach (var matchedItem in context.ConditionMatchedItems)
                {
                    matchedItem.Discount += ComputeDiscount(matchedItem.Subtotal, data);
                }
            }
            else if (data.DiscountAppliedTo == DiscountAppliedTo.OrderShipping)
            {
                context.PricingContext.ShippingCost -= ComputeDiscount(context.PricingContext.ShippingCost, data);
            }
            else if (data.DiscountAppliedTo == DiscountAppliedTo.OrderSubtotal)
            {
                context.PricingContext.Discount += ComputeDiscount(context.PricingContext.Subtotal, data);
            }
        }
        private void CleanCart(PromotionContext context, Dictionary <string, int> products)
        {
            var needUpdate = false;

            foreach (var bvin in products.Keys)
            {
                var li = context.Order.Items.FirstOrDefault(i => i.ProductId.ToUpperInvariant() == bvin);

                if (li != null)
                {
                    var freeCount = li.GetFreeCountByPromotionId(context.PromotionId);

                    if (freeCount != -1)
                    {
                        needUpdate = true;

                        li.RemovePromotionId(context.PromotionId);
                        li.CustomProperties.SetProperty(HCC_KEY, "freeQuantity", "false");
                        var disc =
                            li.DiscountDetails.FirstOrDefault(s => s.DiscountType == PromotionType.OfferForFreeItems &&
                                                              s.PromotionId == context.PromotionId);
                        li.DiscountDetails.Remove(disc);
                    }
                }
            }

            if (needUpdate)
            {
                context.HccApp.OrderServices.Orders.Update(context.Order);
            }
        }
        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);
            }
        }
        private int CalculateProductQuantity(PromotionContext context, Product prod, LineItem li, int mainQuantity)
        {
            var quantity = mainQuantity;

            foreach (var item in context.Order.Items)
            {
                if (item.IsBundle)
                {
                    var p = context.HccApp.CatalogServices.Products.FindWithCache(item.ProductId);

                    var prods =
                        p.BundledProducts.Where(
                            pr => pr.BundledProductId.ToLowerInvariant() == li.ProductId.ToLowerInvariant()).ToList();

                    foreach (var bundledProd in prods)
                    {
                        var options = item.SelectionData.GetSelections(bundledProd.Id);

                        if (li.SelectionData.OptionSelectionList.Equals(options))
                        {
                            quantity += bundledProd.Quantity;
                        }
                    }
                }
                else
                {
                    if (item.ProductId.ToLowerInvariant() == li.ProductId.ToLowerInvariant() &&
                        item.SelectionData.Equals(li.SelectionData))
                    {
                        quantity = Math.Max(quantity, item.Quantity);
                    }
                }
            }
            return(quantity);
        }
        private decimal RemoveDiscountedAmount(PromotionContext context)
        {
            if (context == null)
            {
                return(0);
            }
            if (context.Order == null)
            {
                return(0);
            }

            decimal totalDiscountedAmount = 0;

            foreach (var item in context.Order.Items)
            {
                if (item.IsFreeItem)
                {
                    totalDiscountedAmount += item.BasePricePerItem * item.FreeQuantity;
                }
                else if (item.DiscountDetails != null && item.DiscountDetails.Any())
                {
                    foreach (var discount in item.DiscountDetails)
                    {
                        totalDiscountedAmount += discount.Amount > 0 ? discount.Amount * -1 : 0;
                    }
                }
            }
            return(totalDiscountedAmount);
        }
        public override bool MeetsQualification(PromotionContext context, PromotionQualificationMode mode)
        {
            if (mode != PromotionQualificationMode.Products)
            {
                return(false);
            }
            if (context == null)
            {
                return(false);
            }
            if (context.Product == null)
            {
                return(false);
            }
            if (context.UserPrice == null)
            {
                return(false);
            }

            var ids   = CurrentIds();
            var match = context.Product.ProductTypeId.Trim().ToLowerInvariant();

            // for "generic" type we need to match 0 instead of empty string
            if (match == string.Empty)
            {
                match = "0";
            }

            if (IsNotMode)
            {
                return(!ids.Contains(match));
            }
            return(ids.Contains(match));
        }
Exemple #24
0
        public override bool MeetsQualification(PromotionContext context, PromotionQualificationMode mode)
        {
            if (mode != PromotionQualificationMode.Orders &&
                mode != PromotionQualificationMode.LineItems)
            {
                return(false);
            }
            if (context == null)
            {
                return(false);
            }
            if (context.Order == null)
            {
                return(false);
            }
            if (context.Order.Items == null)
            {
                return(false);
            }

            switch (SetMode)
            {
            case QualificationSetMode.AnyOfTheseItems:
                return(MatchAny(Quantity, context.Order.Items, CurrentIds()));

            case QualificationSetMode.AllOfTheseItems:
                return(MatchAll(Quantity, context.Order.Items, CurrentIds()));
            }

            return(false);
        }
        private void CannotAddProductsNotification(PromotionContext context, List <LineItem> productIds)
        {
            var flag =
                context.Order.CustomProperties
                .FirstOrDefault(s => s.DeveloperId == HCC_KEY && s.Key == "sendflag");

            if (flag == null || flag.Value != ONE)
            {
                var itemF = new CustomProperty(HCC_KEY, "sendflag", "1");
                context.Order.CustomProperties.Add(itemF);

                foreach (var product in productIds)
                {
                    var note = new OrderNote();
                    note.IsPublic = false;
                    note.Note     = string.Format(GlobalLocalization.GetString("SkippingReceiveFreeProduct"),
                                                  product.ProductName, product.ProductSku);
                    context.Order.Notes.Add(note);
                }

                // sent mail to the store
                var epio = new EmailProductIsOut();
                epio.Execute(context.HccApp, context.Order);
            }
        }
        public override async Task <PromotionRequirementStatus> GetStatusAsync(PromotionContext context)
        {
            var entity = InfrastructureEntity.Create(serverName: this.Server, roleName: this.Role);

            if (entity == null)
            {
                return(new PromotionRequirementStatus(PromotionRequirementState.NotApplicable, "A server or role must be specified to determine drift status."));
            }

            var credentials = ResourceCredentials.Create <InedoProductCredentials>(this.CredentialName);

            var client = OtterClient.Create(credentials.Host, credentials.ApiKey);

            try
            {
                await client.TriggerConfigurationCheckAsync(entity).ConfigureAwait(false);

                await Task.Delay(2 * 1000).ConfigureAwait(false);

                var config = await client.GetConfigurationStatusAsync(entity).ConfigureAwait(false);

                if (string.Equals(config.Status, this.Status.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    return(new PromotionRequirementStatus(PromotionRequirementState.Met, $"{entity} status is {config.Status}."));
                }
                else
                {
                    return(new PromotionRequirementStatus(PromotionRequirementState.NotMet, $"{entity} status is {config.Status}, must be {this.Status.ToString().ToLowerInvariant()}."));
                }
            }
            catch (OtterException ex)
            {
                return(new PromotionRequirementStatus(PromotionRequirementState.NotMet, ex.FullMessage));
            }
        }
Exemple #27
0
        /// <summary>
        /// Removing now not aplyied Gift discounts from Order
        /// </summary>
        private void RemoveGiftPromotionFromOrder(OrderGroup order, PromotionContext promoContext)
        {
            var notApliedOldGiftDiscounts = new List <OrderFormDiscount>();

            foreach (OrderFormDiscount discount in order.OrderForms[0].Discounts)
            {
                var promoRecord = promoContext.PromotionResult.PromotionRecords.FirstOrDefault(x => GetGiftPromotionName(x) == discount.DiscountName);
                if (promoRecord == null)
                {
                    notApliedOldGiftDiscounts.Add(discount);
                }
            }

            foreach (OrderFormDiscount toRemoveDiscount in notApliedOldGiftDiscounts)
            {
                toRemoveDiscount.Delete();
                //remove Gift items from order
                var lineitems = order.OrderForms[0].LineItems.ToArray();
                foreach (LineItem lineItem in lineitems)
                {
                    foreach (LineItemDiscount lineItemDiscount in lineItem.Discounts)
                    {
                        if (lineItemDiscount.DiscountName == toRemoveDiscount.DiscountName)
                        {
                            lineItem.Delete();
                        }
                    }
                }
            }
        }
        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);
            }
        }
Exemple #29
0
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.Product == null) return false;
            if (context.UserPrice == null) return false;

            return true;
        }
        public VenueTests()
        {
            var repository = new PromotionContext(new DbContextOptionsBuilder <PromotionContext>()
                                                  .UseInMemoryDatabase(Guid.NewGuid().ToString())
                                                  .Options, null);

            venueQueries  = new VenueQueries(repository);
            venueCommands = new VenueCommands(repository);
        }
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.Mode != PromotionType.Offer) return false;
            if (context.Order == null) return false;

            if (context.Order.TotalOrderAfterDiscounts >= this.Amount) return true;

            return false;

        }
Exemple #32
0
 public PromotionController(PromotionContext context,
                            ILogger <PromotionController> logger,
                            IPromotionService promotionService,
                            IMapper mapper
                            )
 {
     _promotionContext = context ?? throw new ArgumentNullException(nameof(context));
     _logger           = logger ?? throw new ArgumentNullException(nameof(logger));
     _promotionService = promotionService;
     _mapper           = mapper;
 }
        public PromotionControllerTest()
        {
            _dbOptions = new DbContextOptionsBuilder <PromotionContext>()
                         .UseInMemoryDatabase(databaseName: "in-memory")
                         .Options;

            using (var dbContext = new PromotionContext(_dbOptions))
            {
                dbContext.AddRange(GetFakeCatalog());
                dbContext.SaveChanges();
            }
        }
        private PromotionContext PrepareMarketingContext(PromotionEntriesSet sourceSet, PromotionEntriesSet targetSet)
        {
            PromotionContext retVal = null;
            MarketingContext ctx    = MarketingContext.Current;

            Assert.IsNotNull(ctx);
            Assert.IsNotNull(ctx.MarketingProfileContext);
            //IDictionary<string, object> ctx = new Dictionary<string, object>();
            retVal = new PromotionContext(ctx.MarketingProfileContext, sourceSet, targetSet);

            return(retVal);
        }
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.CurrentCustomer == null) return false;
            if (context.CurrentCustomer.PricingGroupId == string.Empty) return false;
            
            if (CurrentGroupIds().Contains(context.CurrentCustomer.PricingGroupId.Trim().ToLowerInvariant()))
            {
                return true;
            }

            return false;
        }
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.Mode != PromotionType.Offer) return false;
            if (context.Order == null) return false;
            if (context.Order.Coupons == null) return false;

            foreach (string coupon in CurrentCoupons())
            {
                if (context.Order.CouponCodeExists(coupon)) return true;
            }

            return false;            
        }
Exemple #37
0
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.CurrentCustomer == null) return false;
            if (context.CurrentCustomer.Bvin == string.Empty) return false;

            string currentId = context.CurrentCustomer.Bvin.Trim().ToUpperInvariant();

            foreach (string uid in UserIds())
            {
                if (currentId == uid) return true;
            }

            return false;            
        }
        public override bool ApplyAction(PromotionContext context, PromotionActionMode mode)
        {
            if (context == null) return false;
            if (context.Product == null) return false;

            decimal adjustment = 0m;

            switch(this.AdjustmentType)
            {
                case AmountTypes.MonetaryAmount:
                    adjustment = Utilities.Money.GetDiscountAmount(context.UserPrice.BasePrice, this.Amount);
                    break;
                case AmountTypes.Percent:
                    adjustment = Utilities.Money.GetDiscountAmountByPercent(context.UserPrice.BasePrice, this.Amount);
                    break;
            }

            context.UserPrice.AddAdjustment(adjustment, context.CustomerDescription);

            return true;
        }
        public void Execute(PromotionContext context)
        {
            var data = context.PolicyConfig as DefaultPromotionPolicyConfig;
            if (data == null)
            {
                return;
            }

            if (data.DiscountAppliedTo == DiscountAppliedTo.MatchedProducts)
            {
                foreach (var matchedItem in context.ConditionMatchedItems)
                {
                    matchedItem.Discount += ComputeDiscount(matchedItem.Subtotal, data);
                }
            }
            else if (data.DiscountAppliedTo == DiscountAppliedTo.OrderShipping)
            {
                context.PricingContext.ShippingCost -= ComputeDiscount(context.PricingContext.ShippingCost, data);
            }
            else if (data.DiscountAppliedTo == DiscountAppliedTo.OrderSubtotal)
            {
                context.PricingContext.Discount += ComputeDiscount(context.PricingContext.Subtotal, data);
            }
        }
        public override bool ApplyAction(PromotionContext context, PromotionActionMode mode)
        {
            if (context == null) return false;
            if (context.Order == null) return false;
            
            // only apply when applying to shipping areas
            if (mode != PromotionActionMode.ForShipping) return false;

            decimal adjustment = 0m;

            switch(this.AdjustmentType)
            {
                case AmountTypes.MonetaryAmount:
                    adjustment = Utilities.Money.GetDiscountAmount(context.Order.TotalShippingBeforeDiscounts, this.Amount);
                    break;
                case AmountTypes.Percent:
                    adjustment = Utilities.Money.GetDiscountAmountByPercent(context.Order.TotalShippingBeforeDiscounts, this.Amount);
                    break;
            }

            context.Order.AddShippingDiscount(adjustment, context.CustomerDescription);
            
            return true;
        }
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.Mode != PromotionType.Offer) return false;
            if (context.Order == null) return false;
            if (context.Order.Items == null) return false;
            
            switch (SetMode)
            {
                case QualificationSetMode.AnyOfTheseItems:
                    return MatchAny(this.Quantity, context.Order.Items, this.CurrentProductIds());                    
                case QualificationSetMode.AllOfTheseItems:
                    return MatchAll(this.Quantity, context.Order.Items, this.CurrentProductIds());                    
            }                                 

            return false;            
        }
 public virtual bool ApplyAction(PromotionContext context, PromotionActionMode mode)
 {
     return false;
 }
Exemple #43
0
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.Product == null) return false;
            if (context.UserPrice == null) return false;

            string match = context.Product.Bvin.Trim().ToLowerInvariant();

            return this.CurrentProductIds().Contains(match);
        }
 public virtual bool MeetsQualification(PromotionContext context)
 {
     return false;
 }
Exemple #45
0
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.Product == null) return false;
            if (context.UserPrice == null) return false;

            string match = context.Product.ProductTypeId.Trim().ToLowerInvariant();
            
            // for "generic" type we need to match 0 instead of empty string
            if (match == string.Empty) match = "0";

            return this.CurrentTypeIds().Contains(match);            
        }
 private decimal GetDiscountPrice(PromotionContext promotionContext)
 {
     var result = promotionContext.PromotionResult;
     return result.PromotionRecords.Sum(record => GetDiscountAmount(record, record.PromotionReward));
 }
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.Mode != PromotionType.Sale) return false;
            if (context.Product == null) return false;
            if (context.UserPrice == null) return false;
            if (context.MTApp == null) return false;

            // Note: this only checks the first 100 categories. You're pretty much insane if you're
            // running a promotion on a product by category and it's in more than 100 categories.
            List<Catalog.CategoryProductAssociation> assignments
                = context.MTApp.CatalogServices.CategoriesXProducts.FindForProduct(context.Product.Bvin, 1, 100);

            foreach (Catalog.CategoryProductAssociation cross in assignments)
            {
                string match = cross.CategoryId.Trim().ToLowerInvariant();
                if (this.CurrentCategoryIds().Contains(match)) return true;
            }
            return false;
        }
        /// <summary>
        /// Calculates the discounts.
        /// </summary>
        private void CalculateDiscounts()
        {
            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 = this.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();
                int i = 0;
                foreach (LineItem lineItem in highPlacedPriceFirst)
                {
                    i++;
                    // 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));

                    promoContext.SourceEntriesSet = sourceSet;
                    promoContext.TargetEntriesSet = targetSet;

                    promoContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Entry).Key;

                    // Evaluate conditions
                    bool checkEntryLevelDiscountLimit = i == lineItemCount;
                    MarketingContext.Current.EvaluatePromotions(useCache, promoContext, filter, entryDiscountApplicationCount, checkEntryLevelDiscountLimit);
                    // from now on use cache
                    useCache = true;
                }
            }
            #endregion

            #region Determine Order level discounts
            foreach (OrderForm form in order.OrderForms)
            {
                // Now process global order discounts
                // Now start processing it
                // Create source from current form
                sourceSet = CreateSetFromOrderForm(form);
                promoContext.SourceEntriesSet = sourceSet;
                promoContext.TargetEntriesSet = sourceSet;
                promoContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Order).Key;
            }

            // Evaluate conditions
            MarketingContext.Current.EvaluatePromotions(useCache, promoContext, filter, null, 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)
            {
                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);
                    promoContext.SourceEntriesSet = targetSet;
                    promoContext.TargetEntriesSet = targetSet;
                    promoContext.TargetGroup = PromotionGroup.GetPromotionGroup(PromotionGroup.PromotionGroupKey.Shipping).Key;

                    // Evaluate promotions
                    MarketingContext.Current.EvaluatePromotions(useCache, promoContext, filter, null, false);

                    // Set the total discount for the shipment
                    // shipment.ShippingDiscountAmount = GetDiscountPrice(order, promoContext.PromotionResult);
                }
            }

            #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
        }
        /// <summary>
        /// Removing now not aplyied Gift discounts from Order 
        /// </summary>
        private void RemoveGiftPromotionFromOrder(OrderGroup order, PromotionContext promoContext)
        {
            var notApliedOldGiftDiscounts = new List<OrderFormDiscount>();

            foreach (OrderFormDiscount discount in order.OrderForms[0].Discounts)
            {
                var promoRecord = promoContext.PromotionResult.PromotionRecords.FirstOrDefault(x => GetGiftPromotionName(x) == discount.DiscountName);
                if (promoRecord == null)
                {
                    notApliedOldGiftDiscounts.Add(discount);
                }
            }

            foreach (OrderFormDiscount toRemoveDiscount in notApliedOldGiftDiscounts)
            {
                toRemoveDiscount.Delete();
                //remove Gift items from order
                var lineitems = order.OrderForms[0].LineItems.ToArray();
                foreach (LineItem lineItem in lineitems)
                {
                    foreach (LineItemDiscount lineItemDiscount in lineItem.Discounts)
                    {
                        if (lineItemDiscount.DiscountName == toRemoveDiscount.DiscountName)
                        {
                            lineItem.Delete();
                        }
                    }
                }
            }
        }
 public FakePromotionHelper()
 {
     _promotionContext = new PromotionContext(null, null, null);
 }
Exemple #51
0
        public bool ApplyToOrder(MerchantTribeApplication app,
                                 Orders.Order o,
                                 Membership.CustomerAccount currentCustomer,
                                 DateTime currentDateTimeUtc,
                                 PromotionActionMode mode)
        {
            if (app == null) return false;
            if (o == null) return false;
            if (currentDateTimeUtc == null) return false;

            PromotionContext context = new PromotionContext(app, o, currentCustomer, currentDateTimeUtc);
            context.CustomerDescription = this.CustomerDescription;

            // Make sure we have an active promotion before applying
            if (GetStatus(context.CurrentDateAndTimeUtc) != PromotionStatus.Active) return false;

            // Make sure we meet all requirements
            // NOTE: we order by processing cost which should allow us to check
            // the fastest items first. For example, checking userID is faster
            // than checking user group because ID is in the context and group
            // requires a database call.
            foreach (IPromotionQualification q in this._Qualifications.OrderBy(y => y.ProcessingCost))
            {
                if (!q.MeetsQualification(context)) return false;
            }

            // We're qualified, do actions
            foreach (IPromotionAction a in this._Actions)
            {
                a.ApplyAction(context, mode);
            }

            return true;
        }
        public override bool MeetsQualification(PromotionContext context)
        {
            if (context == null) return false;
            if (context.Mode != PromotionType.Offer) return false;
            if (context.Order == null) return false;                        
            if (context.Order.ShippingMethodId.Trim().Length < 1) return false;

            foreach (string itemid in this.ItemIds())
            {
                if (context.Order.ShippingMethodId == itemid) return true;
            }

            return false;            
        }