public static decimal TotalsExcludeAPF(MyHLShoppingCart cart, string countryCode)
        {
            if (APFDueProvider.IsAPFSkuPresent(cart.CartItems))
            {
                var calcTheseItems = new List <ShoppingCartItem_V01>();
                calcTheseItems.AddRange(from i in cart.CartItems
                                        where !APFDueProvider.IsAPFSku(i.SKU)
                                        select
                                        new ShoppingCartItem_V01(i.ID, i.SKU, i.Quantity, i.Updated,
                                                                 i.MinQuantity));

                // remove A and L type
                var allItems =
                    CatalogProvider.GetCatalogItems(
                        (from s in calcTheseItems where s.SKU != null select s.SKU).ToList(), countryCode);
                if (null != allItems && allItems.Count > 0)
                {
                    var skuExcluded = (from c in allItems.Values
                                       where (c as CatalogItem_V01).ProductType != ServiceProvider.CatalogSvc.ProductType.Product
                                       select c.SKU);
                    calcTheseItems.RemoveAll(s => skuExcluded.Contains(s.SKU));
                }

                var totals = cart.Calculate(calcTheseItems);
                return(totals != null ? (totals as OrderTotals_V01).AmountDue : decimal.Zero);
            }
            return(cart.Totals != null ? (cart.Totals as OrderTotals_V01).AmountDue : decimal.Zero);
        }
Beispiel #2
0
 private bool isEventTicketSKU(CatalogItem_V01 item, string sku)
 {
     return(item.IsEventTicket &&
            !_systemSKUS.Contains(sku) &&
            !APFDueProvider.IsAPFSku(sku) &&
            !HLConfigManager.Configurations.CheckoutConfiguration.SpecialSKUList.Exists(s => s.Equals(sku)) &&
            !(sku.Equals(HLConfigManager.Configurations.DOConfiguration.HFFHerbalifeSku) || HLConfigManager.Configurations.DOConfiguration.HFFSkuList.Exists(s => s.Equals(sku))));
 }
Beispiel #3
0
        protected string GetLink(DistributorShoppingCartItem item)
        {
            string link = string.Empty;

            if (!APFDueProvider.IsAPFSku(item.SKU) && null != item.ProdInfo && null != item.ParentCat)
            {
                link = string.Format("~/Ordering/ProductDetail.aspx?ProdInfoID={0}&CategoryID={1}", item.ProdInfo.ID,
                                     item.ParentCat.ID);
            }

            return(link);
        }
        private bool checkPerOrderLimit(MyHLShoppingCart cart, List <ShoppingCartItem_V01> previousItems, ShoppingCartRuleResult Result, string sku, int qty)
        {
            decimal MaxAmount = 999.99m;

            var calcTheseItems = new List <ShoppingCartItem_V01>();

            calcTheseItems.AddRange(from i in cart.CartItems
                                    where !APFDueProvider.IsAPFSku(i.SKU)
                                    select
                                    new ShoppingCartItem_V01(i.ID, i.SKU, i.Quantity, i.Updated,
                                                             i.MinQuantity));
            calcTheseItems.AddRange(previousItems);

            var existingItem =
                calcTheseItems.Find(ci => ci.SKU == sku);

            if (null != existingItem)
            {
                existingItem.Quantity += qty;
            }
            else
            {
                calcTheseItems.Add(new ShoppingCartItem_V01(0, sku, qty, DateTime.Now));
            }

            var Totals = cart.Calculate(calcTheseItems, false) as OrderTotals_V01;

            if (Totals != null && Totals.AmountDue > MaxAmount)
            {
                var globalResourceObject =
                    HttpContext.GetGlobalResourceObject(
                        string.Format("{0}_Rules", HLConfigManager.Platform), "AmountLimitExceeds");
                if (globalResourceObject != null)
                {
                    Result.AddMessage(
                        string.Format(
                            globalResourceObject
                            .ToString(), MaxAmount.ToString()));
                }
                Result.Result = RulesResult.Failure;
                return(false);
            }
            return(true);
        }
Beispiel #5
0
        public static decimal TotalsExcludeAPF(MyHLShoppingCart cart, string countryCode)
        {
            var calcTheseItems = new List <ShoppingCartItem_V01>();

            calcTheseItems.AddRange(from i in cart.CartItems
                                    where !APFDueProvider.IsAPFSku(i.SKU)
                                    select
                                    new ShoppingCartItem_V01(i.ID, i.SKU, i.Quantity, i.Updated,
                                                             i.MinQuantity));

            // remove A and L type
            var allItems =
                CatalogProvider.GetCatalogItems(
                    (from s in calcTheseItems where s.SKU != null select s.SKU).ToList(), countryCode);

            if (null != allItems && allItems.Count > 0)
            {
                var totals = cart.Calculate(calcTheseItems);
                return(totals != null ? (totals as OrderTotals_V01).AmountDue : decimal.Zero);
            }

            return(decimal.Zero);
        }
        private ShoppingCartRuleResult CartItemBeingAddedRuleHandler(ShoppingCart_V01 cart,
                                                                     ShoppingCartRuleResult result,
                                                                     string level)
        {
            var hlCart = cart as MyHLShoppingCart;

            if (null != hlCart)
            {
                foreach (ShoppingCartItem_V01 item in cart.CurrentItems)
                {
                    if (APFDueProvider.IsAPFSku(item.SKU))
                    {
                        bool canAddAPF = ShouldAddAPFPT(cart as MyHLShoppingCart);

                        if (!canAddAPF)
                        {
                            result.Result = RulesResult.Failure;
                            result.AddMessage(
                                HttpContext.GetGlobalResourceObject(
                                    string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "CannotAddAPFSku")
                                as string);
                            var sku = APFDueProvider.GetAPFSku();
                            SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                               "CannotRemoveAPFSku");

                            cart.RuleResults.Add(result);
                            cart.APFEdited = false;
                            return(result);
                        }
                    }
                }
                Global.APFRules globalRules = new Global.APFRules();
                hlCart.RuleResults = globalRules.ProcessCart(hlCart, ShoppingCartRuleReason.CartItemsBeingAdded);
            }
            return(result);
        }
        private ShoppingCartRuleResult CartRetrievedRuleHandler(ShoppingCart_V01 cart, ShoppingCartRuleResult result, string level)
        {
            if (cart != null)
            {
                var myhlCart = cart as MyHLShoppingCart;

                if (APFDueProvider.IsAPFSkuPresent(cart.CartItems) && myhlCart != null)
                {
                    // Change the APF sku according tins
                    var tins = DistributorOrderingProfileProvider.GetTinList(cart.DistributorID, true);
                    var huvt = tins.Find(p => p.IDType.Key == "HUVT");
                    var hupt = tins.Find(p => p.IDType.Key == "HUPT");
                    if (huvt != null && hupt != null)
                    {
                        myhlCart.DeleteItemsFromCart(null, true);
                        myhlCart.AddItemsToCart(new List <ShoppingCartItem_V01>(new[] { new ShoppingCartItem_V01(0, AlternAPFSku, 1, DateTime.Now) }), true);
                        return(result);
                    }
                    //Prevent to have a cart with skus Bug 148170
                    if (cart.CartItems.Count > 1)
                    {
                        //get the skus != apf
                        var nonApfItems =
                            (from c in cart.CartItems where APFDueProvider.IsAPFSku(c.SKU.Trim()) == false select c)
                            .ToList <ShoppingCartItem_V01>();
                        if (nonApfItems.Count > 0 ||
                            HLConfigManager.Configurations.APFConfiguration.StandaloneAPFOnlyAllowed)
                        {
                            var skuToBeRemoved = nonApfItems.Select(x => x.SKU).ToList();
                            myhlCart.DeleteItemsFromCart(skuToBeRemoved);
                        }
                    }
                }
            }
            return(result);
        }
        /// <summary>
        ///     The IShoppingCart Rule Interface implementation
        /// </summary>
        /// <param name="cart">The current Shopping Cart</param>
        /// <param name="reason">The Rule invoke Reason</param>
        /// <param name="Result">The Rule Results collection</param>
        /// <returns>The cumulative rule results - including the results of this iteration</returns>
        protected virtual ShoppingCartRuleResult PerformRules(ShoppingCart_V02 cart,
                                                              ShoppingCartRuleReason reason,
                                                              ShoppingCartRuleResult Result)
        {
            if (reason == ShoppingCartRuleReason.CartItemsBeingAdded)
            {
                var     purchasingLimitManager               = PurchasingLimitManager(cart.DistributorID);
                decimal DistributorRemainingVolumePoints     = 0;
                decimal DistributorRemainingDiscountedRetail = 0;
                //decimal CartVolumePoints = 0;
                decimal NewVolumePoints = 0;

                decimal DistributorRemainingEarnings = 0;
                //decimal CartEarnings = 0;
                decimal NewEarnings = 0;

                decimal Discount = 0;

                var myhlCart = cart as MyHLShoppingCart;

                if (null == myhlCart)
                {
                    LoggerHelper.Error(
                        string.Format("{0} myhlCart is null {1}", Locale, cart.DistributorID));
                    Result.Result = RulesResult.Failure;
                    return(Result);
                }

                PurchasingLimits_V01 PurchasingLimits =
                    PurchasingLimitProvider.GetCurrentPurchasingLimits(cart.DistributorID);

                purchasingLimitManager.SetPurchasingLimits(PurchasingLimits);


                if (null == PurchasingLimits)
                {
                    LoggerHelper.Error(
                        string.Format("{0} PurchasingLimits could not be retrieved for distributor {1}", Locale,
                                      cart.DistributorID));
                    Result.Result = RulesResult.Failure;
                    return(Result);
                }

                DistributorRemainingVolumePoints         =
                    DistributorRemainingDiscountedRetail = PurchasingLimits.RemainingVolume;
                DistributorRemainingEarnings             = PurchasingLimits.RemainingEarnings;

                var distributorOrderingProfile = DistributorOrderingProfileProvider.GetProfile(cart.DistributorID,
                                                                                               Country);
                Discount = Convert.ToDecimal(distributorOrderingProfile.StaticDiscount);


                if (myhlCart.Totals != null && (myhlCart.Totals as OrderTotals_V01).DiscountPercentage != 0.0M)
                {
                    Discount = (myhlCart.Totals as OrderTotals_V01).DiscountPercentage;
                }

                myhlCart.SetDiscountForLimits(Discount);

                var currentItem = CatalogProvider.GetCatalogItem(cart.CurrentItems[0].SKU, Country);
                if (currentItem != null)
                {
                    if (currentItem.ProductType == ServiceProvider.CatalogSvc.ProductType.EventTicket)
                    {
                        PurchasingLimitProvider.GetPurchasingLimits(cart.DistributorID, "ETO");
                    }
                    else
                    {
                        NewVolumePoints = currentItem.VolumePoints * cart.CurrentItems[0].Quantity;
                    }
                }

                if (NewVolumePoints > 0 || PurchasingLimits.PurchaseLimitType == PurchaseLimitType.Earnings ||
                    purchasingLimitManager.PurchasingLimitsRestriction == PurchasingLimitRestrictionType.MarketingPlan)
                {
                    if (PurchasingLimits.PurchaseLimitType == PurchaseLimitType.Volume)
                    {
                        if (PurchasingLimits.maxVolumeLimit == -1)
                        {
                            return(Result);
                        }
                        decimal cartVolume = (cart as MyHLShoppingCart).VolumeInCart;

                        if (DistributorRemainingVolumePoints - (cartVolume + NewVolumePoints) < 0)
                        {
                            Result.Result = RulesResult.Failure;
                            if (purchasingLimitManager.PurchasingLimitsRestriction ==
                                PurchasingLimitRestrictionType.MarketingPlan)
                            //MPE Thresholds
                            {
                                if (cart.CartItems.Exists(item => item.SKU == cart.CurrentItems[0].SKU))
                                {
                                    Result.AddMessage(
                                        string.Format(
                                            HttpContext.GetGlobalResourceObject(
                                                string.Format("{0}_Rules", HLConfigManager.Platform),
                                                "VolumePointExceedsThresholdByIncreasingQuantity").ToString(),
                                            cart.CurrentItems[0].SKU, cart.CurrentItems[0].Quantity));
                                }
                                else
                                {
                                    Result.AddMessage(
                                        string.Format(
                                            HttpContext.GetGlobalResourceObject(
                                                string.Format("{0}_Rules", HLConfigManager.Platform),
                                                "VolumePointExceedsThreshold").ToString(), cart.CurrentItems[0].SKU));
                                }
                            }
                            else
                            {
                                if (cart.CartItems.Exists(item => item.SKU == cart.CurrentItems[0].SKU))
                                {
                                    Result.AddMessage(
                                        string.Format(
                                            HttpContext.GetGlobalResourceObject(
                                                string.Format("{0}_Rules", HLConfigManager.Platform),
                                                "VolumePointExceedsByIncreasingQuantity").ToString(),
                                            cart.CurrentItems[0].SKU, cart.CurrentItems[0].Quantity));
                                }
                                else
                                {
                                    Result.AddMessage(
                                        string.Format(
                                            HttpContext.GetGlobalResourceObject(
                                                string.Format("{0}_Rules", HLConfigManager.Platform),
                                                "VolumePointExceeds").ToString(), cart.CurrentItems[0].SKU));
                                }
                            }
                            cart.RuleResults.Add(Result);
                        }
                    }
                    else if (PurchasingLimits.PurchaseLimitType == PurchaseLimitType.DiscountedRetail)
                    {
                        var myHlCart       = cart as MyHLShoppingCart;
                        var calcTheseItems = new List <ShoppingCartItem_V01>(cart.CartItems);
                        var existingItem   = cart.CartItems.Find(ci => ci.SKU == cart.CurrentItems[0].SKU);
                        if (null != existingItem)
                        {
                            existingItem.Quantity += cart.CurrentItems[0].Quantity;
                        }
                        else
                        {
                            calcTheseItems.Add(new ShoppingCartItem_V01(0, cart.CurrentItems[0].SKU,
                                                                        cart.CurrentItems[0].Quantity, DateTime.Now));
                        }
                        var totals = myhlCart.Calculate(calcTheseItems) as OrderTotals_V01;
                        if (null != existingItem)
                        {
                            existingItem.Quantity -= cart.CurrentItems[0].Quantity;
                        }
                        if (null == totals)
                        {
                            var message =
                                string.Format(
                                    "Purchasing Limits DiscountedRetail calculation failed due to Order Totals returning a null for Distributor {0}",
                                    cart.DistributorID);
                            LoggerHelper.Error(message);
                            throw new ApplicationException(message);
                        }
                        decimal newDiscountedRetail = 0.0M;

                        decimal dsicount = totals.DiscountPercentage;

                        var skus     = (from s in calcTheseItems where s.SKU != null select s.SKU).ToList();
                        var allItems = CatalogProvider.GetCatalogItems(skus, Country);
                        if (null != allItems && allItems.Count > 0)
                        {
                            newDiscountedRetail = (from t in totals.ItemTotalsList
                                                   from c in allItems.Values
                                                   where
                                                   (c as CatalogItem_V01).ProductType == ServiceProvider.CatalogSvc.ProductType.Product &&
                                                   c.SKU == (t as ItemTotal_V01).SKU
                                                   select(t as ItemTotal_V01).DiscountedPrice).Sum();
                        }

                        myhlCart.SetDiscountForLimits(totals.DiscountPercentage);

                        if (DistributorRemainingDiscountedRetail - newDiscountedRetail < 0)
                        {
                            Result.Result = RulesResult.Failure;
                            if (cart.CartItems.Exists(item => item.SKU == cart.CurrentItems[0].SKU))
                            {
                                Result.AddMessage(
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform),
                                            "DiscountedRetailExceedsByIncreasingQuantity").ToString(),
                                        cart.CurrentItems[0].SKU, cart.CurrentItems[0].Quantity));
                            }
                            else
                            {
                                Result.AddMessage(
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform),
                                            "DiscountedRetailExceeds").ToString(), cart.CurrentItems[0].SKU));
                            }
                            cart.RuleResults.Add(Result);
                        }
                    }
                    else if (PurchasingLimits.PurchaseLimitType == PurchaseLimitType.Earnings &&
                             cart.OrderSubType == "B1")
                    {
                        NewEarnings += (currentItem.EarnBase) * cart.CurrentItems[0].Quantity * Discount / 100;

                        if (DistributorRemainingEarnings -
                            ((cart as MyHLShoppingCart).ProductEarningsInCart + NewEarnings) < 0)
                        {
                            Result.Result = RulesResult.Failure;
                            if (cart.CartItems.Exists(item => item.SKU == cart.CurrentItems[0].SKU))
                            {
                                Result.AddMessage(
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform),
                                            "EarningExceedsByIncreasingQuantity").ToString(),
                                        cart.CurrentItems[0].SKU, cart.CurrentItems[0].Quantity));
                            }
                            else
                            {
                                Result.AddMessage(
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform), "EarningExceeds")
                                        .ToString(), cart.CurrentItems[0].SKU));
                            }
                            cart.RuleResults.Add(Result);
                        }
                    }
                    else if (PurchasingLimits.PurchaseLimitType == PurchaseLimitType.ProductCategory)
                    {
                        if (currentItem.ProductType == ServiceProvider.CatalogSvc.ProductType.Product)
                        {
                            Result.Result = RulesResult.Failure;
                            Result.AddMessage(
                                string.Format(
                                    HttpContext.GetGlobalResourceObject(
                                        string.Format("{0}_Rules", HLConfigManager.Platform),
                                        "PurchaseLimitTypeProductCategory").ToString(), cart.CurrentItems[0].SKU));
                            cart.RuleResults.Add(Result);
                        }
                        else
                        {
                            if (DistributorRemainingVolumePoints -
                                ((cart as MyHLShoppingCart).VolumeInCart + NewVolumePoints) < 0)
                            {
                                Result.Result = RulesResult.Failure;
                                if (cart.CartItems.Exists(item => item.SKU == cart.CurrentItems[0].SKU))
                                {
                                    Result.AddMessage(
                                        string.Format(
                                            HttpContext.GetGlobalResourceObject(
                                                string.Format("{0}_Rules", HLConfigManager.Platform),
                                                "VolumePointExceedsThresholdByIncreasingQuantity").ToString(),
                                            cart.CurrentItems[0].SKU, cart.CurrentItems[0].Quantity));
                                }
                                else
                                {
                                    Result.AddMessage(
                                        string.Format(
                                            HttpContext.GetGlobalResourceObject(
                                                string.Format("{0}_Rules", HLConfigManager.Platform),
                                                "VolumePointExceedsThreshold").ToString(), cart.CurrentItems[0].SKU));
                                }
                            }
                        }
                    }
                    else if (PurchasingLimits.PurchaseLimitType == PurchaseLimitType.TotalPaid)
                    {
                        Result.Result = RulesResult.Success;

                        var myHlCart       = cart as MyHLShoppingCart;
                        var calcTheseItems = new List <ShoppingCartItem_V01>();
                        calcTheseItems.AddRange(from i in cart.CartItems
                                                where !APFDueProvider.IsAPFSku(i.SKU)
                                                select
                                                new ShoppingCartItem_V01(i.ID, i.SKU, i.Quantity, i.Updated,
                                                                         i.MinQuantity));

                        var existingItem =
                            calcTheseItems.Find(ci => ci.SKU == cart.CurrentItems[0].SKU);
                        if (null != existingItem)
                        {
                            existingItem.Quantity += cart.CurrentItems[0].Quantity;
                        }
                        else
                        {
                            calcTheseItems.Add(new ShoppingCartItem_V01(0, cart.CurrentItems[0].SKU,
                                                                        cart.CurrentItems[0].Quantity, DateTime.Now));
                        }

                        // remove A and L type
                        var allItems =
                            CatalogProvider.GetCatalogItems(
                                (from s in calcTheseItems where s.SKU != null select s.SKU).ToList(), Country);
                        if (null != allItems && allItems.Count > 0)
                        {
                            var skuExcluded = (from c in allItems.Values
                                               where (c as CatalogItem_V01).ProductType != ServiceProvider.CatalogSvc.ProductType.Product
                                               select c.SKU);
                            calcTheseItems.RemoveAll(s => skuExcluded.Contains(s.SKU));
                        }

                        var totals = myhlCart.Calculate(calcTheseItems);
                        if (null == totals)
                        {
                            var message =
                                string.Format(
                                    "Purchasing Limits DiscountedRetail calculation failed due to Order Totals returning a null for Distributor {0}",
                                    cart.DistributorID);
                            LoggerHelper.Error(message);
                            throw new ApplicationException(message);
                        }
                        if (DistributorRemainingVolumePoints - (totals as OrderTotals_V01).AmountDue < 0)
                        {
                            Result.Result = RulesResult.Failure;
                            if (cart.CartItems.Exists(item => item.SKU == cart.CurrentItems[0].SKU))
                            {
                                Result.AddMessage(
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform),
                                            "DiscountedRetailExceedsByIncreasingQuantity").ToString(),
                                        cart.CurrentItems[0].SKU, cart.CurrentItems[0].Quantity));
                            }
                            else
                            {
                                Result.AddMessage(
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform),
                                            "DiscountedRetailExceeds").ToString(), cart.CurrentItems[0].SKU));
                            }
                            cart.RuleResults.Add(Result);
                        }
                    }
                    else
                    {
                        Result.Result = RulesResult.Success;
                    }
                }
            }

            return(Result);
        }
        private void DoApfDue(string distributorID,
                              ShoppingCart_V01 result,
                              string cacheKey,
                              string locale,
                              bool cartHasItems,
                              ShoppingCartRuleResult ruleResult,
                              bool justEntered)
        {
            var cart = result as MyHLShoppingCart;

            if (cart == null)
            {
                return;
            }

            try
            {
                string level;
                if (DistributorProfileModel != null)
                {
                    level = DistributorProfileModel.TypeCode.ToUpper();
                }
                else
                {
                    level = GetMemberLevelFromDistributorProfile(cart.DistributorID);
                }

                var distributorOrderingProfile = DistributorOrderingProfileProvider.GetProfile(cart.DistributorID,
                                                                                               cart.CountryCode);
                if ((distributorOrderingProfile.HardCashOnly &&
                     !HLConfigManager.Configurations.PaymentsConfiguration.AllowWireForHardCash))
                {
                    return;
                }
                var apfItems = new List <ShoppingCartItem_V01>();
                if (cart.CartItems != null && cart.CartItems.Count > 0)
                {
                    //Stash off all non-APF items - to be re-added if appropriate
                    var nonApfItems =
                        (from c in cart.CartItems where APFDueProvider.IsAPFSku(c.SKU.Trim()) == false select c)
                        .ToList <ShoppingCartItem_V01>();
                    apfItems =
                        (from c in cart.CartItems where APFDueProvider.IsAPFSku(c.SKU.Trim()) select c)
                        .ToList <ShoppingCartItem_V01>();
                    if (nonApfItems.Count > 0 ||
                        HLConfigManager.Configurations.APFConfiguration.StandaloneAPFOnlyAllowed)
                    {
                        // Clear the cart
                        cart.DeleteItemsFromCart(null, true);
                        //if (APFDueProvider.CanEditAPFOrder(distributorID, locale, level))
                        //{
                        //Global rule - they can always edit the cart ie add remove products at least
                        var list =
                            CatalogProvider.GetCatalogItems((from p in nonApfItems select p.SKU).ToList(), Country);
                        var products =
                            (from c in list where c.Value.ProductType == ProductType.Product select c.Value.SKU).ToList();
                        var nonproducts =
                            (from c in list where c.Value.ProductType != ProductType.Product select c.Value.SKU).ToList();
                        if (!HLConfigManager.Configurations.APFConfiguration.AllowNonProductItemsWithStandaloneAPF)
                        //We don't allow non product items alone on an apf order
                        {
                            if (products.Count == 0)
                            {
                                if (nonproducts.Count > 0)
                                {
                                    ruleResult.Result = RulesResult.Success;
                                    ruleResult.AddMessage(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                            "NonProductItemsRemovedForStandaloneAPF") as string);
                                    cart.RuleResults.Add(ruleResult);
                                }
                            }
                            else
                            {
                                cart.AddItemsToCart(nonApfItems, true);
                            }
                        }
                        else
                        {
                            if (!HLConfigManager.Configurations.APFConfiguration.StandaloneAPFOnlyAllowed)
                            {
                                cart.AddItemsToCart(nonApfItems, true);
                            }
                        }
                    }
                }
                else if (null != cart && null != cart.RuleResults)
                {
                    var rules =
                        (from rule in cart.RuleResults
                         where rule.RuleName == RuleName && rule.Result == RulesResult.Failure
                         select rule);
                    if (null != rules && rules.Count() > 0)
                    {
                        cart.RuleResults.Remove(rules.First());
                    }
                }

                //Add the APF in
                var apfSku = new List <ShoppingCartItem_V01>();
                var sku    = APFDueProvider.GetAPFSku();
                apfSku.Add(new ShoppingCartItem_V01(0, sku, 1, DateTime.Now));
                if (!cart.APFEdited)
                {
                    apfSku[0].Quantity = 1; //CalcQuantity(distributorOrderingProfile.ApfDueDate);
                    if (cart.CartItems.Exists(c => c.SKU == apfSku[0].SKU))
                    {
                        var apf =
                            (from a in cart.CartItems where a.SKU == apfSku[0].SKU select a).First();
                        cart.DeleteItemsFromCart(
                            (from a in cart.CartItems where a.SKU == apfSku[0].SKU select a.SKU).ToList(), true);
                    }
                    if (cart.CartItems.Count == 0) //This is now a Standalone APF
                    {
                        SetAPFDeliveryOption(cart);
                    }
                    cart.AddItemsToCart(apfSku, true);

                    if (justEntered)
                    {
                        ruleResult.AddMessage(
                            HttpContext.GetGlobalResourceObject(
                                string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "APFDueAdded") as string);
                        ruleResult.Result = RulesResult.Success;

                        SetApfRuleResponse(ruleResult, ApfAction.None, sku, "ApfRule", TypeOfApf.CantDSRemoveAPF,
                                           "APFDueAdded");

                        cart.RuleResults.Add(ruleResult);
                    }
                    else
                    {
                        foreach (ShoppingCartRuleResult r in cart.RuleResults)
                        {
                            if (r.RuleName == RuleName)
                            {
                                r.Messages.Clear();
                                r.AddMessage(string.Empty);
                            }
                        }
                    }
                }
                //else
                //{
                //    if (APFDueProvider.CanRemoveAPF(distributorID, locale, level))
                //    {
                //        cart.AddItemsToCart(apfSku, true);
                //    }
                //}
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(string.Format("doAPFDue DS:{0} ERR:{1}", distributorID, ex));
            }
        }
        protected override ShoppingCartRuleResult PerformRules(MyHLShoppingCart cart,
                                                               ShoppingCartRuleReason reason,
                                                               ShoppingCartRuleResult Result)
        {
            Result.Result = RulesResult.Success;

            if (cart == null)
            {
                return(Result);
            }

            base.PerformRules(cart, reason, Result);

            var currentlimits = GetCurrentPurchasingLimits(cart.DistributorID, GetCurrentOrderMonth());

            if (currentlimits.PurchaseLimitType == PurchaseLimitType.None || currentlimits.LimitsRestrictionType != LimitsRestrictionType.PurchasingLimits)
            {
                return(Result);
            }

            if (cart.ItemsBeingAdded != null && cart.ItemsBeingAdded.Count > 0)
            {
                var calcTheseItems = new List <ShoppingCartItem_V01>();
                calcTheseItems.AddRange(from i in cart.CartItems
                                        where !APFDueProvider.IsAPFSku(i.SKU)
                                        select
                                        new ShoppingCartItem_V01(i.ID, i.SKU, i.Quantity, i.Updated,
                                                                 i.MinQuantity));
                bool          bExceed  = false;
                List <string> skuToAdd = new List <string>();

                foreach (var item in cart.ItemsBeingAdded)
                {
                    if (bExceed == true)
                    {
                        Result = reportError(cart, item, Result);
                        continue;
                    }
                    var existingItem =
                        calcTheseItems.Find(ci => ci.SKU == item.SKU);
                    if (null != existingItem)
                    {
                        existingItem.Quantity += item.Quantity;
                    }
                    else
                    {
                        calcTheseItems.Add(new ShoppingCartItem_V01(0, item.SKU, item.Quantity, DateTime.Now));
                    }

                    // remove A and L type
                    var allItems =
                        CatalogProvider.GetCatalogItems(
                            (from s in calcTheseItems where s.SKU != null select s.SKU).ToList(), Country);
                    if (null != allItems && allItems.Count > 0)
                    {
                        var skuExcluded = (from c in allItems.Values
                                           where (c as CatalogItem_V01).ProductType != ServiceProvider.CatalogSvc.ProductType.Product
                                           select c.SKU);
                        calcTheseItems.RemoveAll(s => skuExcluded.Contains(s.SKU));
                    }

                    var totals = cart.Calculate(calcTheseItems, false);
                    if (null == totals)
                    {
                        var message =
                            string.Format(
                                "Purchasing Limits DiscountedRetail calculation failed due to Order Totals returning a null for Distributor {0}",
                                cart.DistributorID);
                        LoggerHelper.Error(message);
                        throw new ApplicationException(message);
                    }

                    if (currentlimits.RemainingVolume - (totals as OrderTotals_V01).AmountDue < 0)
                    {
                        bExceed = true;
                        Result  = reportError(cart, item, Result);
                    }
                    else
                    {
                        skuToAdd.Add(item.SKU);
                    }
                }

                cart.ItemsBeingAdded.RemoveAll(s => !skuToAdd.Contains(s.SKU));
            }
            return(Result);
        }
        private ShoppingCartRuleResult CartItemBeingDeletedRuleHandler(ShoppingCart_V01 cart,
                                                                       ShoppingCartRuleResult result,
                                                                       string level)
        {
            if (APFDueProvider.IsAPFDueAndNotPaid(cart.DistributorID, Locale) &&
                HLConfigManager.Configurations.APFConfiguration.StandaloneAPFOnlyAllowed)
            {
                result.Result = RulesResult.Failure;
                result.AddMessage(
                    HttpContext.GetGlobalResourceObject(string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                                        "CompleteAPFPurchase") as string);
                var sku = APFDueProvider.GetAPFSku();
                SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                   "CompleteAPFPurchase");

                cart.RuleResults.Add(result);
                return(result);
            }

            //Deleting is a little different than Inserting, because delete handles multiple skus while insert only does one
            //so we can use the cart.CurrentItems to control this. Anything the rule says to not delete, we remove from the CurrentItems
            //Delete post-rule will only delete what is left in there
            bool isStandaloneAPF = APFDueProvider.hasOnlyAPFSku(cart.CartItems, Locale);
            var  toRemove        = new List <ShoppingCartItem_V01>();
            var  hlCart          = cart as MyHLShoppingCart;

            if (null != hlCart)
            {
                foreach (ShoppingCartItem_V01 item in cart.CurrentItems)
                {
                    if (APFDueProvider.IsAPFSku(item.SKU))
                    {
                        if (
                            !APFDueProvider.CanRemoveAPF(cart.DistributorID, Thread.CurrentThread.CurrentCulture.Name,
                                                         level))
                        {
                            result.Result = RulesResult.Failure;
                            result.AddMessage(
                                HttpContext.GetGlobalResourceObject(
                                    string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "CannotRemoveAPFSku")
                                as string);
                            var sku = APFDueProvider.GetAPFSku();
                            SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                               "CannotRemoveAPFSku");

                            cart.RuleResults.Add(result);
                        }
                        else
                        {
                            if (APFDueProvider.IsAPFDueAndNotPaid(cart.DistributorID, Locale))
                            {
                                var originalItem =
                                    (from c in cart.CartItems where c.SKU == cart.CurrentItems[0].SKU select c).ToList();
                                int requiredQuantity = APFDueProvider.APFQuantityDue(cart.DistributorID, Locale);
                                if (level == "SP")
                                {
                                    item.Quantity = requiredQuantity;
                                    result.Result = RulesResult.Recalc;
                                    result.AddMessage(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                            "RequiredAPFLeftInCart") as string);
                                    var sku = APFDueProvider.GetAPFSku();
                                    SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                                       "RequiredAPFLeftInCart");
                                    cart.RuleResults.Add(result);
                                    //toRemove.Add(item);
                                    cart.APFEdited = false;
                                    return(result);
                                }

                                //Add for ChinaDO
                                if (HLConfigManager.Configurations.APFConfiguration.CantDSRemoveAPF)
                                {
                                    result.Result = RulesResult.Recalc;
                                    result.AddMessage(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                            "RequiredAPFLeftInCart") as string);
                                    var sku = APFDueProvider.GetAPFSku();
                                    SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                                       "RequiredAPFLeftInCart");
                                    cart.RuleResults.Add(result);
                                    //toRemove.Add(item);
                                    cart.APFEdited = false;
                                    return(result);
                                }
                            }
                            cart.APFEdited = true;
                            toRemove.Add(item); // added
                        }
                    }
                    else
                    {
                        toRemove.Add(item); // added
                    }
                }
                //if (toRemove.Count > 0)
                //{
                //    cart.CurrentItems.Remove(toRemove[0]);
                //}
                var remainingItems = (from c in cart.CartItems
                                      where !toRemove.Any(x => x.SKU == c.SKU)
                                      select c).ToList();

                //List<ShoppingCartItem_V01> remainingItems = (from c in cart.CartItems where c.SKU != cart.CurrentItems[0].SKU select c).ToList();
                var mags = CartHasOnlyTodaysMagazine(remainingItems);
                if (mags.Count > 0)
                {
                    foreach (ShoppingCartItem_V01 item in mags)
                    {
                        (cart as MyHLShoppingCart).DeleteTodayMagazine(item.SKU);
                        remainingItems.Remove(item);
                        if (!cart.CurrentItems.Exists(c => c.SKU == item.SKU))
                        {
                            cart.CurrentItems.Add(item);
                        }
                    }
                    result.Result = RulesResult.Failure;
                    result.AddMessage(
                        HttpContext.GetGlobalResourceObject(
                            string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                            "NoTodayMagazineWithStandalonAPF") as string);
                    var sku = APFDueProvider.GetAPFSku();
                    SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                       "NoTodayMagazineWithStandalonAPF");
                    cart.RuleResults.Add(result);
                }

                // added
                if (remainingItems.Count > 0)
                {
                    var list = new ShoppingCartItemList();
                    list.AddRange(remainingItems);
                    isStandaloneAPF = APFDueProvider.hasOnlyAPFSku(list, Locale);
                    if (isStandaloneAPF)
                    {
                        SetAPFDeliveryOption(hlCart);
                    }
                    else
                    {
                        if (APFDueProvider.IsAPFSkuPresent(cart.CurrentItems))
                        {
                            SetNonStandAloneAPFDeliveryOption(hlCart);
                        }
                    }
                }
                else
                {
                    SetNonStandAloneAPFDeliveryOption(hlCart);
                }
            }
            //if((from c in cart.CurrentItems where APFDueProvider.IsAPFSku(c.SKU) select c).Count() >0)
            //{
            //    if (isStandaloneAPF)
            //    {
            //        SetAPFDeliveryOption(hlCart);
            //    }
            //}

            return(result);
        }
        private ShoppingCartRuleResult CartItemBeingAddedRuleHandler(ShoppingCart_V01 cart,
                                                                     ShoppingCartRuleResult result,
                                                                     string level)
        {
            var distributorId      = cart.DistributorID;
            var isAPFDueandNotPaid = APFDueProvider.IsAPFDueAndNotPaid(distributorId, Locale);

            if (isAPFDueandNotPaid && HLConfigManager.Configurations.APFConfiguration.StandaloneAPFOnlyAllowed)
            {
                result.Result = RulesResult.Failure;
                result.AddMessage(
                    HttpContext.GetGlobalResourceObject(string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                                        "CompleteAPFPurchase") as string);
                var sku = APFDueProvider.GetAPFSku();
                SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                   "CompleteAPFPurchase");

                cart.RuleResults.Add(result);
                return(result);
            }
            else if (isAPFDueandNotPaid && HLConfigManager.Configurations.DOConfiguration.IsChina)
            {
                string cacheKey   = string.Empty;
                bool   reloadAPFs = (null != cart && null != cart.CartItems) && isAPFDueandNotPaid &&
                                    !APFDueProvider.IsAPFSkuPresent(cart.CartItems);

                DoApfDue(cart.DistributorID, cart, cacheKey, Locale, reloadAPFs, result, true);
            }

            if ((cart as MyHLShoppingCart).OrderCategory == OrderCategoryType.ETO) //No APFs allowed in ETO cart
            {
                result.Result = RulesResult.Success;
                return(result);
            }

            //cart.CurrentItems[0] contains the current item being added
            //because the provider only adds one at a time, we just need to return a single error, but aggregate to the cart errors for the UI
            if (APFDueProvider.IsAPFSku(cart.CurrentItems[0].SKU))
            {
                if (APFDueProvider.CanRemoveAPF(distributorId, Locale, level))
                {
                    if (APFDueProvider.IsAPFSku(cart.CurrentItems[0].SKU))
                    {
                        var originaItem =
                            (from c in cart.CartItems where c.SKU == cart.CurrentItems[0].SKU select c).ToList();
                        int previousQuantity = 0;
                        if (null != originaItem && originaItem.Count > 0)
                        {
                            previousQuantity = originaItem[0].Quantity;
                        }
                        if (APFDueProvider.IsAPFDueAndNotPaid(distributorId, Locale))
                        {
                            int requiredQuantity = APFDueProvider.APFQuantityDue(distributorId, Locale);
                            if (cart.CurrentItems[0].Quantity + previousQuantity <= requiredQuantity)
                            {
                                if (level == "SP")
                                {
                                    cart.CurrentItems[0].Quantity = requiredQuantity - previousQuantity;
                                    result.Result = RulesResult.Recalc;
                                    result.AddMessage(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                            "RequiredAPFLeftInCart") as string);
                                    var sku = APFDueProvider.GetAPFSku();
                                    SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.CantDSRemoveAPF,
                                                       "RequiredAPFLeftInCart");
                                    cart.RuleResults.Add(result);
                                    cart.APFEdited = false;
                                    return(result);
                                }
                                else
                                {
                                    result.Result = RulesResult.Recalc;
                                    result.AddMessage(string.Empty);
                                    cart.RuleResults.Add(result);
                                    cart.APFEdited = true;
                                    return(result);
                                }
                            }
                            else if (cart.CurrentItems[0].Quantity + previousQuantity > requiredQuantity)
                            {
                                cart.CurrentItems[0].Quantity = requiredQuantity - previousQuantity;
                                result.Result = RulesResult.Recalc;
                                result.AddMessage(
                                    HttpContext.GetGlobalResourceObject(
                                        string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                        "RequiredAPFLeftInCart") as string);
                                var sku = APFDueProvider.GetAPFSku();
                                SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.CantDSRemoveAPF,
                                                   "RequiredAPFLeftInCart");
                                cart.RuleResults.Add(result);
                                cart.APFEdited = false;
                                return(result);
                            }
                        }
                        else
                        {
                            if (cart.CurrentItems[0].Quantity + previousQuantity > 1)
                            {
                                if (APFDueProvider.CanAddAPF(distributorId))
                                {
                                    result.Result = RulesResult.Failure;
                                    result.AddMessage(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                            "CanOnlyPrepayOneAPF") as string);
                                    var sku = APFDueProvider.GetAPFSku();
                                    SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.CantDSRemoveAPF,
                                                       "CanOnlyPrepayOneAPF");
                                    cart.RuleResults.Add(result);
                                    cart.APFEdited = true;
                                    return(result);
                                }
                            }
                        }
                    }
                }

                if (!APFDueProvider.CanAddAPF(distributorId))
                {
                    result.Result = RulesResult.Failure;
                    result.AddMessage(
                        HttpContext.GetGlobalResourceObject(
                            string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "CannotAddAPFSku") as string);
                    var sku = APFDueProvider.GetAPFSku();
                    SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.CannotAddAPFSku,
                                       "CannotAddAPFSku");

                    cart.RuleResults.Add(result);
                    return(result);
                }
                else
                {
                    string apfSku = APFDueProvider.GetAPFSku();
                    if (cart.CurrentItems[0].SKU == apfSku)
                    {
                        cart.APFEdited = true;
                    }
                    else
                    {
                        result.Result = RulesResult.Failure;
                        result.AddMessage(
                            HttpContext.GetGlobalResourceObject(
                                string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "SkuNotValid") as string);
                        var sku = APFDueProvider.GetAPFSku();
                        SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.CannotAddAPFSku,
                                           "SkuNotValid");
                        cart.RuleResults.Add(result);
                        return(result);
                    }
                }
            }

            if (APFDueProvider.IsAPFSkuPresent(cart.CartItems))
            {
                var currentSession = SessionInfo.GetSessionInfo(cart.DistributorID, cart.Locale);
                if ((!APFDueProvider.CanEditAPFOrder(cart.DistributorID, Thread.CurrentThread.CurrentCulture.Name, level)) || (currentSession.IsAPFOrderFromPopUp))
                {
                    result.Result = RulesResult.Failure;
                    result.AddMessage(
                        HttpContext.GetGlobalResourceObject(
                            string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "CompleteAPFPurchase") as
                        string);
                    var sku = APFDueProvider.GetAPFSku();
                    SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                       "CompleteAPFPurchase");
                    cart.RuleResults.Add(result);
                    return(result);
                }
                else
                {
                    if (APFDueProvider.containsOnlyAPFSku(cart.CartItems))
                    {
                        CatalogItem item = CatalogProvider.GetCatalogItem(cart.CurrentItems[0].SKU, Country);
                        if (null != item)
                        {
                            if (!HLConfigManager.Configurations.APFConfiguration.AllowNonProductItemsWithStandaloneAPF)
                            {
                                if (item.ProductType != ProductType.Product)
                                {
                                    result.Result = RulesResult.Failure;
                                    result.AddMessage(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                            "NoNonProductToStandaloneAPF") as string);

                                    var sku = APFDueProvider.GetAPFSku();
                                    SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.AllowNonProductItemsWithStandaloneAPF,
                                                       "NoNonProductToStandaloneAPF");

                                    cart.RuleResults.Add(result);
                                    return(result);
                                }
                            }
                            if (item.SKU == HLConfigManager.Configurations.DOConfiguration.TodayMagazineSku ||
                                item.SKU == HLConfigManager.Configurations.DOConfiguration.TodayMagazineSecondarySku)
                            {
                                result.Result = RulesResult.Failure;
                                result.AddMessage(
                                    HttpContext.GetGlobalResourceObject(
                                        string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                        "NoTodayMagazineWithStandalonAPF") as string);
                                var sku = APFDueProvider.GetAPFSku();
                                SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                                   "NoTodayMagazineWithStandalonAPF");

                                cart.RuleResults.Add(result);
                                return(result);
                            }

                            //To the standalone APF, DS trying to add product then change the Freight code & warehouse code.
                            else if (item.ProductType == ProductType.Product ||
                                     item.ProductType == ProductType.Literature ||
                                     item.ProductType == ProductType.PromoAccessory)
                            {
                                SetNonStandAloneAPFDeliveryOption(cart as MyHLShoppingCart);
                            }
                        }
                    }
                }
            }

            //Can add
            if (APFDueProvider.IsAPFSku(cart.CurrentItems[0].SKU))
            {
                if (cart.CurrentItems[0].Quantity < 0)
                {
                    var originaItem =
                        (from c in cart.CartItems where c.SKU == cart.CurrentItems[0].SKU select c).ToList();
                    int previousQuantity = originaItem[0].Quantity;
                    if (APFDueProvider.IsAPFDueAndNotPaid(distributorId, Locale))
                    {
                        int requiredQuantity = APFDueProvider.APFQuantityDue(distributorId, Locale);
                        if (level == "SP" || !HLConfigManager.Configurations.APFConfiguration.AllowDSRemoveAPFWhenDue)
                        {
                            if (cart.CurrentItems[0].Quantity + previousQuantity < requiredQuantity)
                            {
                                cart.CurrentItems[0].Quantity = (previousQuantity - requiredQuantity) * -1;
                                result.Result = RulesResult.Recalc;
                                result.AddMessage(
                                    HttpContext.GetGlobalResourceObject(
                                        string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                        "RequiredAPFLeftInCart") as string);
                                var sku = APFDueProvider.GetAPFSku();
                                SetApfRuleResponse(result, ApfAction.None, sku, "ApfRule", TypeOfApf.StandaloneAPFOnlyAllowed,
                                                   "RequiredAPFLeftInCart");

                                cart.RuleResults.Add(result);
                                cart.APFEdited = false;
                                return(result);
                            }
                        }
                    }
                }
            }

            return(result);
        }
        protected override ShoppingCartRuleResult PerformRules(MyHLShoppingCart cart,
                                                               ShoppingCartRuleReason reason,
                                                               ShoppingCartRuleResult Result)
        {
            Result.Result = RulesResult.Success;

            if (cart == null)
            {
                return(Result);
            }

            Result = base.PerformRules(cart, reason, Result);
            if (Result.Result == RulesResult.Failure)
            {
                return(Result);
            }

            var manager = GetPurchaseRestrictionManager(cart.DistributorID);

            if (manager == null)
            {
                return(Result);
            }

            var currentLimits = manager.ApplicableLimits == null ? null : manager.ApplicableLimits.Where(x => (x as PurchasingLimits_V01).LimitsRestrictionType == LimitsRestrictionType.PurchasingLimits && (x as PurchasingLimits_V01).maxVolumeLimit > -1);

            if (currentLimits == null || currentLimits.Count() == 0)
            {
                return(Result);
            }
            var limits = currentLimits.First() as PurchasingLimits_V01;

            if (limits != null && limits.maxVolumeLimit > -1)
            {
                if (!cart.OnCheckout)
                {
                    if (limits.RemainingVolume > decimal.Zero)
                    {
                        Result.Result = RulesResult.Failure;
                        ///New Members are subject to a 7 day cooling off period.  During this time Members are limited to £163.92.  Your cooling off period began on <date1> and ends on <date2>
                        Result.AddMessage(
                            string.Format(
                                HttpContext.GetGlobalResourceObject(
                                    string.Format("{0}_Rules", HLConfigManager.Platform),
                                    "LimitsInfoWithinDays").ToString(), limits.maxVolumeLimit, getBeginDate(cart.DistributorID, cart.CountryCode), getEndDate(cart.DistributorID, cart.CountryCode)));
                    }
                    else
                    {
                        Result.Result = RulesResult.Failure;
                        /// Member is subject to 7 Day Cooling Off Purchase Limit of  £163.92 and has already reached the limit. Member can only purchase items after the Cooling Off Period has been completed. The Cooling Off Period will end on: <DATE>
                        Result.AddMessage(
                            string.Format(
                                HttpContext.GetGlobalResourceObject(
                                    string.Format("{0}_Rules", HLConfigManager.Platform),
                                    "LimitsExceededWithinDays").ToString(), limits.maxVolumeLimit, getEndDate(cart.DistributorID, cart.CountryCode)));
                        return(Result);
                    }
                }
                var calcTheseItems = new List <ShoppingCartItem_V01>();
                calcTheseItems.AddRange(from i in cart.CartItems
                                        where !APFDueProvider.IsAPFSku(i.SKU)
                                        select
                                        new ShoppingCartItem_V01(i.ID, i.SKU, i.Quantity, i.Updated,
                                                                 i.MinQuantity));

                foreach (var item in cart.ItemsBeingAdded)
                {
                    var existingItem =
                        calcTheseItems.Find(ci => ci.SKU == item.SKU);
                    if (null != existingItem)
                    {
                        existingItem.Quantity += item.Quantity;
                    }
                    else
                    {
                        calcTheseItems.Add(new ShoppingCartItem_V01(0, item.SKU, item.Quantity, DateTime.Now));
                    }
                }
                var totals = cart.Calculate(calcTheseItems, false) as OrderTotals_V01;
                if (null == totals)
                {
                    var message =
                        string.Format(
                            "Purchasing Limits DiscountedRetail calculation failed due to Order Totals returning a null for Distributor {0}",
                            cart.DistributorID);
                    LoggerHelper.Error(message);
                    throw new ApplicationException(message);
                }
                decimal discountedRetailInCart = totals.ItemTotalsList.Sum(x => (x as ItemTotal_V01).DiscountedPrice);
                if (limits.RemainingVolume - discountedRetailInCart < 0)
                {
                    Result = reportError(cart, Result, discountedRetailInCart - limits.RemainingVolume, limits.maxVolumeLimit);
                    cart.ItemsBeingAdded.Clear();
                }
            }

            return(Result);
        }
        public void CreateInvoiceView(string startYearMonthDay, string endYearMonthDay)
        {
            #region determine startDate and endDate
            DateTime?startDate;
            if (IsValidDate(startYearMonthDay))
            {
                startDate = DateTime.ParseExact(startYearMonthDay, YearMonthDayFormat, CultureInfo.InvariantCulture);
            }
            else
            {
                var proposedStartDate = DateTime.Now.AddDays(-30);
                startDate         = new DateTime(proposedStartDate.Year, proposedStartDate.Month, proposedStartDate.Day);
                txtStartDate.Text = startDate.Value.ToString(YearMonthDayFormat);
            }

            DateTime?endDate;
            if (IsValidDate(endYearMonthDay))
            {
                endDate = DateTime.ParseExact(endYearMonthDay, YearMonthDayFormat, CultureInfo.InvariantCulture).AddDays(1).AddMilliseconds(-1);
            }
            else
            {
                endDate         = DateTime.Now;
                txtEndDate.Text = endDate.Value.ToString(YearMonthDayFormat);
            }
            #endregion


            var htmlTable = new StringBuilder();
            htmlTable.Append("<div>");
            htmlTable.Append("<table id=\"TABLE-ID\" class=\"rgMasterTable order-list-view\" border=\"0\" >");
            htmlTable.Append("<thead>" +
                             "<tr>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("OrderNumberResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("OrderSourceResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("DCResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("OrderMonthResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("DeliveryMethodResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("OrderStatusResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("OrderDateResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("SubTotalResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("FreightResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("TotalAmountResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("VolumeTotalResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("InvoiceStatusResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("ActionResource.Text") + "</th>" +
                             "<th class=\"rgHeader\" scope=\"col\">" + GetLocalResourceObject("RegisteredNoResource.Text") + "</th>" +
                             "</tr>" +
                             "</thead>");
            htmlTable.Append("<tbody>");

            DateTime pStartDate = (DateTime)startDate;
            DateTime pEndDate   = (DateTime)endDate;

            var    pOrders     = new List <OnlineOrder>();
            string cacheKey    = string.Format(InvoiceOrderDetails, DistributorID);
            var    cacheResult = HttpRuntime.Cache[cacheKey] as List <OnlineOrder>;

            if (cacheResult != null)
            {
                pOrders = cacheResult;
            }
            else
            {
                pOrders = OrderProvider.GetOrdersWithDetail(DistributorID,
                                                            DistributorOrderingProfileProvider.GetProfile(DistributorID, CountryCode).CNCustomorProfileID,
                                                            CountryCode, pStartDate, pEndDate, Providers.China.OrderStatusFilterType.Complete, "", "", true);
                HttpRuntime.Cache.Insert(cacheKey, pOrders, null, DateTime.Now.AddMinutes(InvoiceStatusCacheMin),
                                         Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }

            // ensure that the order only belong to GDO
            var orders     = pOrders.OrderByDescending(x => x.ReceivedDate).ToList();
            var etoSkuList = Settings.GetRequiredAppSetting("ETOSkuList", string.Empty).Split('|');
            var pureOrders = (from items in orders from ordersItem in items.OrderItems where ordersItem.SKU == null || (ordersItem.SKU.Trim() == "9909" && items.OrderItems.Count == 1 || etoSkuList.Contains(ordersItem.SKU.Trim())) select items).ToList();
            foreach (var item in pureOrders)
            {
                orders.Remove(item);
            }
            string[] orderNumbers = orders.Select(o => o.OrderID).ToArray();
            var      orderStatus  = OrderProvider.GetOrderStatus(orderNumbers, DistributorID);

            if (orders != null)
            {
                int maximumRows = 5;
                int startIndex  = PagingControl1.FirstItemIndex;
                PagingControl1.TotalRecordsCount = orders.Count;


                //var maxRows = startIndex + maximumRows > orders.Count? orders.Count - startIndex: maximumRows;

                //orders = orders.GetRange(maxRows >= 0 ? startIndex : 0, maxRows >= 0 ? maxRows : 0);
                if (orders.Count > 0)
                {
                    if (orders.Count < 5)
                    {
                        PagingControl1.Visible = false;
                    }
                    if (InvoiceStatusddl.SelectedValue == "0" || InvoiceStatusddl.SelectedValue == "01")
                    {
                        if (orders.Count <= maximumRows)
                        {
                            orders = orders.GetRange(0, orders.Count);
                        }
                        else
                        {
                            if (startIndex > 0)
                            {
                                var maxrow = orders.Count - startIndex <= maximumRows ? orders.Count - startIndex : maximumRows;
                                orders = orders.GetRange(startIndex, maxrow);
                            }
                            else
                            {
                                orders = orders.GetRange(0, maximumRows);
                            }
                        }
                    }
                    //orders = orders.GetRange((startIndex == 0) ? 0 : startIndex + 1, orders.Count - 1 - startIndex > 5 ? 5 : orders.Count - 1 - startIndex);
                    PagingControl1.Visible = true;
                    lblNoRecords.Visible   = false;
                }
                else
                {
                    lblNoRecords.Text = GetLocalResourceString("GridNoRecordsMessage.Text");
                    TimeSpan span = _dtEndDate.Subtract(_dtStartDate);
                    if (span.TotalDays > 90)
                    {
                        lblNoRecords.Text = GetLocalResourceString("Error3MonthsRangeOnly.Text");
                    }


                    lblNoRecords.Visible   = true;
                    PagingControl1.Visible = false;
                }
                int i = 0;
                int y = 0;

                foreach (var order in orders)
                {
                    i++;

                    var invoiceDetailStatus = orderStatus.FirstOrDefault(z => z.OrderNumber == order.OrderID);
                    if (invoiceDetailStatus == null)
                    {
                        invoiceDetailStatus = new InvoiceInfoObject();
                        invoiceDetailStatus.InvoiceStatus = "01";
                    }
                    if (invoiceDetailStatus != null && (invoiceDetailStatus.InvoiceStatus == InvoiceStatusddl.SelectedValue) || (InvoiceStatusddl.SelectedValue == "0"))
                    {
                        y++;

                        decimal Apfprice = 0;
                        var     apfSku   = (from c in order.OrderItems where APFDueProvider.IsAPFSku((c.SKU != null ? c.SKU.Trim() : "")) select c).FirstOrDefault();

                        if (order.OrderItems[0].SKU != null && apfSku != null)
                        {
                            var APFSkuDetails = CatalogProvider.GetCatalogItem(apfSku.SKU.Trim(), CountryCode);
                            Apfprice = APFSkuDetails.ListPrice;
                        }

                        var invoiceStatus = invoiceDetailStatus != null?GetInvoiceStatus(invoiceDetailStatus.InvoiceStatus) : GetLocalResourceString("InvoiceStatusUnbilled.Text");

                        var priceInfo    = order.Pricing as ServiceProvider.OrderChinaSvc.OrderTotals_V01 ?? new ServiceProvider.OrderChinaSvc.OrderTotals_V01();
                        var priceInfoV02 = order.Pricing as ServiceProvider.OrderChinaSvc.OrderTotals_V02;
                        var shipInfo     = order.Shipment as ServiceProvider.OrderChinaSvc.ShippingInfo_V01;
                        //Mapping object issue
                        decimal freightCharges = priceInfoV02 != null && null != priceInfoV02.ChargeList && priceInfoV02.ChargeList.Any() ? GetFreightCharges(priceInfoV02.ChargeList as ServiceProvider.OrderChinaSvc.ChargeList) : decimal.Zero;
                        // decimal freightCharges = 0;
                        string carrier;
                        if (shipInfo != null && shipInfo.Carrier == "EXP")
                        {
                            carrier = GetLocalResourceString("InvoiceDeliveryMethod.Text");
                        }
                        else if (shipInfo != null && shipInfo.Carrier == "SD")
                        {
                            carrier = GetLocalResourceString("InvoicePickupFromStoreMethod.Text");
                        }
                        else
                        {
                            carrier = GetLocalResourceString("InvoiceSelftPickupMethod.Text");
                        }

                        htmlTable.Append("<tr class='" + ((i % 2 != 0) ? "rgRow" : "rgAltRow") + "'>");
                        //htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\" onclick='ShowOrHideDetail(" + order.OrderID + ",\"" + (order.InvoiceOrder == null?"":order.InvoiceOrder.Category) + "\")' >" + order.OrderID + "</span></td>");
                        if (order.InvoiceOrder != null && order.InvoiceOrder.InvoiceId < 1)
                        {
                            htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + order.OrderID + "</td>");
                        }
                        else
                        {
                            htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\"><a href=\"onlineinvoicedetail.aspx?type=view&orderid=" + order.OrderID + "&startDate=" + _startDate + "&endDate=" + _endDate + "\" >" + order.OrderID + "</td>");
                        }
                        //htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\"><a href=\"onlineinvoicedetail.aspx?type=view&orderid=" + order.OrderID + "\" >" + order.OrderID + "</td>");

                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + order.ChannelInfo + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + order.RDCName + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + order.OrderMonth + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + carrier + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + order.Status + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + order.ReceivedDate.ToString("yyyy-MM-dd") + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + (priceInfo.ItemsTotal - Apfprice).ToString("0.##") + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + freightCharges.ToString("0.##") + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + (priceInfo.ItemsTotal + freightCharges - Apfprice).ToString("0.##") + "</span></td>");
                        //htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + priceInfoV02.ItemsTotal.ToString("0.##") + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + priceInfo.VolumePoints.ToString("0.##") + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + invoiceStatus + "</span></td>");
                        htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\"><span>");
                        if (order.InvoiceOrder != null && order.InvoiceOrder.InvoiceId < 1)
                        {
                            if (invoiceDetailStatus.PostNumber == null)
                            {
                                htmlTable.Append("<a onclick=\"showModalPopUp('single','" + order.OrderID + "','" + _startDate + "','" + _endDate + "')\" runat=\"server\">" + GetLocalResourceString("OnlineInvoiceSingleBilling.Text") + "</asp:HyperLink>");
                                htmlTable.Append("<br/><br/><a onclick=\"showModalPopUp('split','" + order.OrderID + "','" + _startDate + "','" + _endDate + "')\" runat=\"server\">" + GetLocalResourceString("OnlineInvoiceSplitBilling.Text") + "</asp:HyperLink>");
                            }

                            //htmlTable.Append("<a href=\"onlineinvoicedetail.aspx?type=single&orderid=" + order.OrderID + "&startDate=" + _startDate + "&endDate=" + _endDate + "\">"  + "开票");
                            //htmlTable.Append("<br/><a href=\"onlineinvoicedetail.aspx?type=split&orderid=" + order.OrderID + "&startDate=" + _startDate + "&endDate=" + _endDate + "\">" + "拆票");
                        }
                        htmlTable.Append("</span></td>");

                        if (invoiceDetailStatus != null)
                        {
                            htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + invoiceDetailStatus.PostNumber + "</span></td>");
                        }
                        else
                        {
                            htmlTable.Append("<td class=\"olv-vpoints\" scope=\"col\"><span id=\"lblVolumeCoulmn\">" + "" + "</span></td>");
                        }
                        htmlTable.Append("</tr>");
                    }

                    if (invoiceDetailStatus != null && (invoiceDetailStatus.InvoiceStatus == InvoiceStatusddl.SelectedValue) || (InvoiceStatusddl.SelectedValue == "0"))
                    {
                        PagingControl1.Visible = true;
                        lblNoRecords.Visible   = false;
                    }
                    else if (y < 1)
                    {
                        lblNoRecords.Text      = GetLocalResourceString("GridNoRecordsMessage.Text");
                        lblNoRecords.Visible   = true;
                        PagingControl1.Visible = false;
                    }
                }
                htmlTable.Append("</tbody>");
                htmlTable.Append("</table>");
                htmlTable.Append("</div>");
                htmlTable.Append("<div align='right'>" + GetLocalResourceString("OnlineInvoiceDetailFooter.Text") + "</div>");
                var result = htmlTable.ToString();
                OrderViewPlaceHolder.Controls.Clear();
                OrderViewPlaceHolder.Controls.Add(new Literal {
                    Text = result
                });
            }
        }
 private ShoppingCartRuleResult CheckHonors2016Skus(ShoppingCart_V01 shoppingCart,
                                                    ShoppingCartRuleResult ruleResult)
 {
     if (shoppingCart != null)
     {
         var honors2016Skus = GetHonors2016Skus();
         var cart           = shoppingCart as MyHLShoppingCart;
         if (honors2016Skus.Contains(shoppingCart.CurrentItems[0].SKU))
         {
             if (!DistributorOrderingProfileProvider.IsEventQualified(Honors2016EventId, Locale))
             {
                 var message = "SKUNotAvailable";
                 var globalResourceObject =
                     HttpContext.GetGlobalResourceObject(string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                                         "SKUNotAvailable");
                 if (globalResourceObject != null)
                 {
                     message = string.Format(globalResourceObject.ToString(), shoppingCart.CurrentItems[0].SKU);
                 }
                 ruleResult.AddMessage(message);
                 ruleResult.Result = RulesResult.Failure;
             }
             else
             {
                 if (cart != null && cart.DeliveryInfo != null &&
                     cart.DeliveryInfo.Option != DeliveryOptionType.Pickup &&
                     cart.DeliveryInfo.WarehouseCode != HLConfigManager.Configurations.PickupOrDeliveryConfiguration.SpecialEventWareHouse)
                 {
                     var message = "SKUNotAvailable";
                     var globalResourceObject =
                         HttpContext.GetGlobalResourceObject(string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                                             "SKUNotAvailable");
                     if (globalResourceObject != null)
                     {
                         message = string.Format(globalResourceObject.ToString(), shoppingCart.CurrentItems[0].SKU);
                     }
                     ruleResult.AddMessage(message);
                     ruleResult.Result = RulesResult.Failure;
                 }
                 else if (cart != null && cart.DeliveryInfo != null &&
                          cart.DeliveryInfo.Option == DeliveryOptionType.Pickup &&
                          cart.DeliveryInfo.WarehouseCode == HLConfigManager.Configurations.PickupOrDeliveryConfiguration.SpecialEventWareHouse &&
                          shoppingCart.CartItems != null &&
                          shoppingCart.CartItems.Any(i => !honors2016Skus.Contains(i.SKU) && !APFDueProvider.IsAPFSku(i.SKU)))
                 {
                     var message = "StandaloneSku";
                     var globalResourceObject =
                         HttpContext.GetGlobalResourceObject(
                             string.Format("{0}_Rules", HLConfigManager.Platform),
                             "StandaloneSku");
                     if (globalResourceObject != null)
                     {
                         message = string.Format(globalResourceObject.ToString(),
                                                 shoppingCart.CurrentItems[0].SKU);
                     }
                     ruleResult.AddMessage(message);
                     ruleResult.Result = RulesResult.Failure;
                 }
                 else if (cart != null && cart.DeliveryInfo != null &&
                          cart.DeliveryInfo.Option == DeliveryOptionType.Pickup &&
                          cart.DeliveryInfo.WarehouseCode != HLConfigManager.Configurations.PickupOrDeliveryConfiguration.SpecialEventWareHouse &&
                          shoppingCart.CurrentItems != null &&
                          shoppingCart.CurrentItems.Any(i => honors2016Skus.Contains(i.SKU)))
                 {
                     var message = "SKUNotAvailable";
                     var globalResourceObject =
                         HttpContext.GetGlobalResourceObject(string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                                             "SKUNotAvailable");
                     if (globalResourceObject != null)
                     {
                         message = string.Format(globalResourceObject.ToString(), shoppingCart.CurrentItems[0].SKU);
                     }
                     ruleResult.AddMessage(message);
                     ruleResult.Result = RulesResult.Failure;
                 }
             }
         }
         else
         {
             if (cart != null && cart.DeliveryInfo != null &&
                 cart.DeliveryInfo.Option == DeliveryOptionType.Pickup &&
                 cart.DeliveryInfo.WarehouseCode == HLConfigManager.Configurations.PickupOrDeliveryConfiguration.SpecialEventWareHouse)
             {
                 var message = "SKUNotAvailable";
                 var globalResourceObject =
                     HttpContext.GetGlobalResourceObject(string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                                         "SKUNotAvailable");
                 if (globalResourceObject != null)
                 {
                     message = string.Format(globalResourceObject.ToString(), shoppingCart.CurrentItems[0].SKU);
                 }
                 ruleResult.AddMessage(message);
                 ruleResult.Result = RulesResult.Failure;
             }
         }
     }
     return(ruleResult);
 }
        /// <summary>
        /// The get all input.
        /// </summary>
        /// <returns>
        /// </returns>
        ///
        private List <ShoppingCartItem_V01> getAllInput(List <string> friendlyMessages)
        {
            Dictionary <string, SKU_V01> allSKUs = CatalogProvider.GetAllSKU(Locale, base.CurrentWarehouse);
            SKU_V01 skuV01 = null;

            friendlyMessages.Clear();
            errSKU.Clear();

            var      products         = new List <ShoppingCartItem_V01>();
            setError setErrorDelegate = delegate(SkuQty sku, string error, List <string> errors)
            {
                sku.Image.Visible = true;
                sku.HasError      = true;
                if (!errors.Contains(error))
                {
                    errors.Add(error);
                }
            };

            bool bNoItemSelected = true;

            for (int i = 1; i < NUMITEMS + 1; i++)
            {
                string controlID = "SKUBox" + i;
                var    ctrlSKU   = tblSKU.FindControl(controlID) as TextBox;
                var    ctrlQty   = tblSKU.FindControl("QuantityBox" + i) as TextBox;
                var    ctrlError = tblSKU.FindControl("imgError" + i) as Image;

                string strSKU = ctrlSKU.Text.Trim();
                string strQty = ctrlQty.Text;
                int    qty;
                int.TryParse(strQty, out qty);

                if (!string.IsNullOrEmpty(strSKU) && qty != 0)
                {
                    strSKU = strSKU.ToUpper();

                    // If the str has a product.
                    strSKU = strSKU.Split(new char[] { ' ' })[0];

                    AllSKUS.TryGetValue(strSKU, out skuV01);
                    if (skuV01 == null)
                    {
                        // if not valid setup error
                        setErrorDelegate(new SkuQty(controlID, strSKU, qty, ctrlError, true, true), string.Format((GetLocalResourceObject("NoSKUFound") as string), strSKU), errSKU);
                    }
                    else
                    {
                        if (CheckMaxQuantity(ShoppingCart.CartItems, qty, skuV01, errSKU))
                        {
                            if (skuList.Any(s => s.SKU == strSKU))
                            {
                                var skuQty = new SkuQty(controlID, strSKU, qty, ctrlError, true, true);
                                skuList.Add(skuQty);
                                setErrorDelegate(skuQty, string.Format((GetLocalResourceObject("DuplicateSKU") as string), strSKU), errSKU);
                                SkuQty skuToFind = skuList.Find(s => s.SKU == strSKU);
                                if (skuToFind != null)
                                {
                                    // this is to prevent dupe one to NOT be added to cart
                                    skuToFind.HasError      = true;
                                    skuToFind.Image.Visible = true;
                                }
                            }
                            else
                            {
                                skuList.Add(new SkuQty(controlID, strSKU, qty, ctrlError, false, false));
                            }
                        }
                        else
                        {
                            ctrlError.CssClass = ctrlError.CssClass.Replace("hide", string.Empty);
                        }
                    }
                }
                else if (!string.IsNullOrEmpty(strSKU) && qty <= 0)
                {
                    setErrorDelegate(new SkuQty(controlID, strSKU, qty, ctrlError, true, false), String.Format(PlatformResources.GetGlobalResourceString("ErrorMessage", "QuantityIncorrect"), strSKU), errSKU);
                }
                else
                {
                    if (strSKU.Length + strQty.Length != 0)
                    {
                        setErrorDelegate(new SkuQty(controlID, strSKU, qty, ctrlError, true, false), GetLocalResourceObject("SKUOrQtyMissing") as string, errSKU);
                    }
                }

                if (!string.IsNullOrEmpty(strSKU) || !string.IsNullOrEmpty(strQty))
                {
                    bNoItemSelected = false;
                }
            }

            if (bNoItemSelected)
            {
                errSKU.Add(PlatformResources.GetGlobalResourceString("ErrorMessage", "NoItemsSelected"));
            }
            else
            {
                try
                {
                    foreach (SkuQty s in skuList)
                    {
                        // do not need to check at this point
                        if (APFDueProvider.IsAPFSku(s.SKU))
                        {
                            setErrorDelegate(s, string.Format(PlatformResources.GetGlobalResourceString("ErrorMessage", "SKUNotAvailable"), s.SKU), errSKU);
                            continue;
                        }

                        AllSKUS.TryGetValue(s.SKU, out skuV01);
                        if (skuV01 != null)
                        {
                            HLRulesManager.Manager.ProcessCatalogItemsForInventory(Locale, this.ShoppingCart, new List <SKU_V01> {
                                skuV01
                            });
                            CatalogProvider.GetProductAvailability(skuV01, CurrentWarehouse);

                            int availQty;

                            // check isBlocked first
                            if (IsBlocked(skuV01))
                            {
                                setErrorDelegate(s, string.Format(PlatformResources.GetGlobalResourceString("ErrorMessage", "SKUNotAvailable"), s.SKU), errSKU);
                            }
                            else if (!skuV01.IsPurchasable)
                            {
                                setErrorDelegate(s, string.Format(GetLocalResourceObject("SKUCantBePurchased") as string, s.SKU), errSKU);
                            }
                            else if (skuV01.ProductAvailability == ProductAvailabilityType.Unavailable)
                            {
                                setErrorDelegate(s, string.Format(PlatformResources.GetGlobalResourceString("ErrorMessage", "SKUNotAvailable"), s.SKU), errSKU);
                            }
                            else if (HLConfigManager.Configurations.DOConfiguration.IsChina && ChinaPromotionProvider.GetPCPromoSkus(skuV01.SKU))
                            {
                                setErrorDelegate(s, string.Format(GetLocalResourceObject("SKUCantBePurchased") as string, s.SKU), errSKU);
                            }
                            else
                            {
                                int backorderCoverage = CheckBackorderCoverage(s.Qty, skuV01, friendlyMessages);
                                if (backorderCoverage == 0)
                                {
                                    // out of stock
                                    if ((availQty = ShoppingCartProvider.CheckInventory(skuV01.CatalogItem, GetAllQuantities(ShoppingCart.CartItems, s.Qty, s.SKU), CurrentWarehouse)) == 0)
                                    {
                                        setErrorDelegate(s, string.Format(MyHL_ErrorMessage.OutOfInventory, s.SKU), errSKU);
                                    }
                                    else if (availQty < GetAllQuantities(ShoppingCart.CartItems, s.Qty, s.SKU))
                                    {
                                        setErrorDelegate(s, string.Format(PlatformResources.GetGlobalResourceString("ErrorMessage", "LessInventory"), s.SKU, availQty), errSKU);
                                        HLRulesManager.Manager.PerformBackorderRules(ShoppingCart, skuV01.CatalogItem);
                                        IEnumerable <string> ruleResultMessages =
                                            from r in ShoppingCart.RuleResults
                                            where r.Result == RulesResult.Failure && r.RuleName == "Back Order"
                                            select r.Messages[0];
                                        if (null != ruleResultMessages && ruleResultMessages.Count() > 0)
                                        {
                                            errSKU.Add(ruleResultMessages.First());
                                            ShoppingCart.RuleResults.Clear();
                                        }
                                    }
                                }
                            }
                        }
                    }

                    //if (errSKU.Count == 0)
                    {
                        products.AddRange((from c in skuList
                                           where c.HasError == false
                                           select new ShoppingCartItem_V01(0, c.SKU, c.Qty, DateTime.Now)).ToList());
                    }
                }
                catch (Exception ex)
                {
                    LoggerHelper.Error(string.Format("getAllInput error:" + ex));
                }
            }

            return(products);
        }
        protected override ShoppingCartRuleResult PerformRules(MyHLShoppingCart cart, ShoppingCartRuleReason reason, ShoppingCartRuleResult Result)
        {
            //if (!GetPurchaseRestrictionManager(cart.DistributorID).CanPurchase)
            //{
            //    cart.ItemsBeingAdded.Clear();
            //    Result.AddMessage(
            //        string.Format(
            //            HttpContext.GetGlobalResourceObject(
            //                string.Format("{0}_ErrorMessage", HLConfigManager.Platform), "CantBuy").ToString()));
            //    Result.Result = RulesResult.Failure;
            //    return Result;
            //}

            var currentlimits = GetCurrentPurchasingLimits(cart.DistributorID, GetCurrentOrderMonth());

            if (cart == null || currentlimits == null)
            {
                return(Result);
            }

            if (cart.ItemsBeingAdded == null || cart.ItemsBeingAdded.Count == 0)
            {
                return(Result);
            }

            string processingCountryCode = DistributorProfileModel.ProcessingCountryCode;

            bool          bCanPurchase      = CanPurchase(cart.DistributorID);
            bool          bCanPurchasePType = CanPurchasePType(cart.DistributorID);
            var           errors            = new List <string>();
            decimal       NewVolumePoints   = decimal.Zero;
            decimal       cartVolume        = cart.VolumeInCart;
            bool          bLimitExceeded    = false;
            List <string> skuToAdd          = new List <string>();

            foreach (var item in cart.ItemsBeingAdded)
            {
                var currentItem = CatalogProvider.GetCatalogItem(item.SKU, Country);
                if (currentItem == null)
                {
                    continue;
                }

                if (APFDueProvider.IsAPFSku(item.SKU) || cart.OrderCategory == ServiceProvider.CatalogSvc.OrderCategoryType.ETO)
                {
                    skuToAdd.Add(item.SKU);
                }
                else
                {
                    if (bCanPurchase)
                    {
                        if (!bCanPurchasePType)
                        {
                            if (currentItem.ProductType == ServiceProvider.CatalogSvc.ProductType.Product)
                            {
                                Result.Result = RulesResult.Failure;
                                errors.Add(
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform),
                                            "PurchaseLimitTypeProductCategory").ToString(), item.SKU));
                                continue;
                            }
                        }
                    }
                    else
                    {
                        Result.Result = RulesResult.Failure;
                        errors.Add(
                            string.Format(
                                HttpContext.GetGlobalResourceObject(
                                    string.Format("{0}_ErrorMessage", HLConfigManager.Platform),
                                    "CantBuy").ToString()));
                        continue;
                    }

                    if (currentlimits.PurchaseLimitType == PurchaseLimitType.Volume || currentlimits.RestrictionPeriod == PurchasingLimitRestrictionPeriod.PerOrder)
                    {
                        if (currentlimits.maxVolumeLimit == -1)
                        {
                            skuToAdd.Add(item.SKU);
                            continue;
                        }
                        NewVolumePoints += currentItem.VolumePoints * item.Quantity;

                        //verifying VP limits didn't exceed
                        if (currentlimits.RemainingVolume - (cartVolume + NewVolumePoints) < 0)
                        {
                            if (currentlimits.LimitsRestrictionType == LimitsRestrictionType.FOP || currentlimits.LimitsRestrictionType == LimitsRestrictionType.OrderThreshold)
                            //MPE FOP
                            {
                                Result.Result = RulesResult.Failure;
                                ///Order exceeds the allowable volume for First Order Program. The Volume on the order needs to be reduced by {0:F2} VPs. The following SKU(s) have not been added to the cart.
                                if (!bLimitExceeded) //  to add this message only once
                                {
                                    errors.Add(
                                        string.Format(
                                            HttpContext.GetGlobalResourceObject(
                                                string.Format("{0}_Rules", HLConfigManager.Platform),
                                                "FOPVolumePointExceeds").ToString(), 1100,
                                            PurchaseRestrictionProvider.GetVolumeLimitsAfterFirstOrderFOP(
                                                processingCountryCode),
                                            PurchaseRestrictionProvider.GetThresholdPeriod(processingCountryCode), -999));
                                    // -999 should be replaced with caluclated value.
                                    bLimitExceeded = true;
                                }
                                /// Item SKU:{0}.
                                errors.Add(
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform),
                                            "VolumePointExceedsThreshold").ToString(), item.SKU));
                            }
                            else  //it exceeded VP but it's not FOP
                            {
                                var itemExists = cart.CartItems.Find(i => i.SKU == item.SKU);
                                if (itemExists != null)  //item already exists in cart
                                {
                                    Result.Result = RulesResult.Failure;
                                    errors.Add(
                                        string.Format(
                                            HttpContext.GetGlobalResourceObject(
                                                string.Format("{0}_Rules", HLConfigManager.Platform),
                                                "VolumePointExceedsByIncreasingQuantity").ToString(), item.SKU, item.Quantity));
                                }
                                else
                                {
                                    Result.Result = RulesResult.Failure;
                                    errors.Add(
                                        string.Format(
                                            HttpContext.GetGlobalResourceObject(
                                                string.Format("{0}_Rules", HLConfigManager.Platform),
                                                "VolumePointExceeds").ToString(), item.SKU));
                                }
                            }
                        }
                        else // // VP limits didn't exceeded, add item
                        {
                            skuToAdd.Add(item.SKU);
                        }
                    }
                    else  //purchasing limits are not per VP nor per order: add item
                    {
                        skuToAdd.Add(item.SKU);
                    }
                }
            }
            if (Result.Result == RulesResult.Failure && errors.Count > 0)
            {
                if (cart.OnCheckout && (currentlimits.LimitsRestrictionType == LimitsRestrictionType.FOP || currentlimits.LimitsRestrictionType == LimitsRestrictionType.OrderThreshold))
                {
                    Result.AddMessage(string.Format(HttpContext.GetGlobalResourceObject(
                                                        string.Format("{0}_Rules", HLConfigManager.Platform),
                                                        "FOPVolumePointExceedsOnCheckout").ToString(), 1100, PurchaseRestrictionProvider.GetVolumeLimitsAfterFirstOrderFOP(processingCountryCode), PurchaseRestrictionProvider.GetThresholdPeriod(processingCountryCode), (cartVolume + NewVolumePoints) - currentlimits.RemainingVolume));
                }
                else
                {
                    errors = errors.Select(x => x.Replace("-999", ((cartVolume + NewVolumePoints) - currentlimits.RemainingVolume).ToString())).ToList <string>();
                    Array.ForEach(errors.ToArray(), a => Result.AddMessage(a));
                }
            }
            cart.ItemsBeingAdded.RemoveAll(s => !skuToAdd.Contains(s.SKU));

            return(Result);
        }
Beispiel #18
0
        /// <summary>
        ///     The IShoppingCart Rule Interface implementation
        /// </summary>
        /// <param name="cart">The current Shopping Cart</param>
        /// <param name="reason">The Rule invoke Reason</param>
        /// <param name="Result">The Rule Results collection</param>
        /// <returns>The cumulative rule results - including the results of this iteration</returns>
        protected override ShoppingCartRuleResult PerformRules(ShoppingCart_V02 cart,
                                                               ShoppingCartRuleReason reason,
                                                               ShoppingCartRuleResult Result)
        {
            var dpm = DistributorProfileModel;

            CurrentSession = (dpm != null)
                ? SessionInfo.GetSessionInfo(dpm.Id, Locale)
                : SessionInfo.GetSessionInfo(cart.DistributorID, Locale);
            string dsid = string.Empty;

            if (CurrentSession.IsReplacedPcOrder)
            {
                dsid = CurrentSession.ReplacedPcDistributorOrderingProfile != null && CurrentSession.ReplacedPcDistributorOrderingProfile.Id != null ? CurrentSession.ReplacedPcDistributorOrderingProfile.Id : cart.DistributorID;
            }
            else
            {
                dsid = cart.DistributorID;
            }
            //   OrderTotals_V01 totals = (OrderTotals_V01)(cart as MyHLShoppingCart).Totals;
            if (reason == ShoppingCartRuleReason.CartItemsBeingAdded || reason == ShoppingCartRuleReason.CartRetrieved)
            {
                var Cart           = cart as MyHLShoppingCart;
                var calcTheseItems = new List <ShoppingCartItem_V01>();

                var purchasingLimitManager = PurchasingLimitManager(dsid);
                var myhlCart = cart as MyHLShoppingCart;

                if (null == myhlCart)
                {
                    LoggerHelper.Error(
                        string.Format("{0} myhlCart is null {1}", Locale, dsid));
                    Result.Result = RulesResult.Failure;
                    return(Result);
                }

                PurchasingLimits_V01 PurchasingLimits =
                    PurchasingLimitProvider.GetCurrentPurchasingLimits(dsid);

                purchasingLimitManager.SetPurchasingLimits(PurchasingLimits);


                if (null == PurchasingLimits)
                {
                    LoggerHelper.Error(
                        string.Format("{0} PurchasingLimits could not be retrieved for distributor {1}", Locale,
                                      dsid));
                    Result.Result = RulesResult.Failure;
                    return(Result);
                }

                var shoppingCart = cart as MyHLShoppingCart;
                if (shoppingCart == null)
                {
                    return(Result);
                }

                if (PurchasingLimits.MaxPCEarningsLimit == -1)
                {
                    return(Result);
                }
                DistributorOrderingProfile distributorOrderingProfile = DistributorOrderingProfileProvider.GetProfile(cart.DistributorID, "CN");
                if ((CurrentSession.ReplacedPcDistributorOrderingProfile != null && CurrentSession.ReplacedPcDistributorOrderingProfile.IsPC) || (distributorOrderingProfile != null && distributorOrderingProfile.IsPC))
                {
                    if (cart.CurrentItems != null)
                    {
                        calcTheseItems.AddRange(from i in cart.CurrentItems
                                                where !APFDueProvider.IsAPFSku(i.SKU)
                                                select
                                                new ShoppingCartItem_V01(i.ID, i.SKU, i.Quantity, i.Updated,
                                                                         i.MinQuantity));
                    }
                    if (cart.CartItems != null)
                    {
                        calcTheseItems.AddRange(from i in cart.CartItems
                                                where !APFDueProvider.IsAPFSku(i.SKU)
                                                select
                                                new ShoppingCartItem_V01(i.ID, i.SKU, i.Quantity, i.Updated,
                                                                         i.MinQuantity));
                    }
                    var totals = Cart.Calculate(calcTheseItems, false) as OrderTotals_V01;

                    //OrderTotals_V01 totals = (OrderTotals_V01)(cart as MyHLShoppingCart).Totals;
                    if (totals != null && totals.DiscountedItemsTotal > purchasingLimitManager.MaxPersonalPCConsumptionLimit)
                    {
                        if (cart.CurrentItems.Count > 0)
                        {
                            var sessionInfo = SessionInfo.GetSessionInfo(cart.DistributorID, Locale);
                            if (sessionInfo != null && sessionInfo.ShoppingCart != null && sessionInfo.ShoppingCart.CurrentItems != null)
                            {
                                sessionInfo.ShoppingCart.CurrentItems.RemoveAll(x => x.SKU != null);
                            }
                            cart.CurrentItems.RemoveAll(s => s.SKU != null);
                        }
                        Result.Result = RulesResult.Failure;
                        Result.AddMessage(
                            string.Format(
                                HttpContext.GetGlobalResourceObject(
                                    string.Format("{0}_Rules", HLConfigManager.Platform),
                                    "ErrorMessageToPCWhenhittheFOPLimits").ToString(),
                                purchasingLimitManager.MaxPersonalPCConsumptionLimit));
                    }
                    else
                    {
                        var ruleMessage = cart.RuleResults.FirstOrDefault(x => x.Messages != null && x.Messages.Count > 0 && x.RuleName == "PurchasingLimits Rules");
                        if (ruleMessage != null)
                        {
                            cart.RuleResults.Remove(ruleMessage);
                        }
                    }

                    cart.RuleResults.Add(Result);
                }
                else
                {
                    decimal DistributorRemainingVolumePoints = 0;
                    decimal NewVolumePoints = 0;


                    if (null == myhlCart)
                    {
                        LoggerHelper.Error(
                            string.Format("{0} myhlCart is null {1}", Locale, cart.DistributorID));
                        Result.Result = RulesResult.Failure;
                        return(Result);
                    }

                    DistributorRemainingVolumePoints = PurchasingLimits.RemainingVolume;
                    if (cart.CurrentItems != null && cart.CurrentItems.Count > 0)
                    {
                        var currentItem = CatalogProvider.GetCatalogItem(cart.CurrentItems[0].SKU, Country);
                        if (currentItem != null)
                        {
                            NewVolumePoints = currentItem.VolumePoints * cart.CurrentItems[0].Quantity;
                        }
                    }

                    if (NewVolumePoints > 0 || purchasingLimitManager.PurchasingLimitsRestriction == PurchasingLimitRestrictionType.MarketingPlan)
                    {
                        //if (PurchasingLimits.PurchaseLimitType == PurchaseLimitType.Volume)
                        {
                            if (PurchasingLimits.maxVolumeLimit == -1)
                            {
                                return(Result);
                            }
                            decimal cartVolume = (cart as MyHLShoppingCart).VolumeInCart;

                            if (DistributorRemainingVolumePoints - (cartVolume + NewVolumePoints) < 0)
                            {
                                Result.Result = RulesResult.Failure;
                                Result.AddMessage(
                                    string.Format(
                                        HttpContext.GetGlobalResourceObject(
                                            string.Format("{0}_Rules", HLConfigManager.Platform),
                                            "VolumePointExceedsThresholdByIncreasingQuantity").ToString(),
                                        purchasingLimitManager.MaxPersonalPCConsumptionLimit));
                                cart.RuleResults.Add(Result);
                                //if (purchasingLimitManager.PurchasingLimitsRestriction ==
                                //    PurchasingLimitRestrictionType.MarketingPlan)
                                //    //MPE Thresholds
                                //{
                                //    if (cart.CartItems.Exists(item => item.SKU == cart.CurrentItems[0].SKU))
                                //    {
                                //        Result.AddMessage(
                                //            string.Format(
                                //                HttpContext.GetGlobalResourceObject(
                                //                    string.Format("{0}_Rules", HLConfigManager.Platform),
                                //                    "VolumePointExceedsThresholdByIncreasingQuantity").ToString(),
                                //                cart.CurrentItems[0].SKU, cart.CurrentItems[0].Quantity));
                                //    }
                                //else
                                //{
                                //    Result.AddMessage(
                                //        string.Format(
                                //            HttpContext.GetGlobalResourceObject(
                                //                string.Format("{0}_Rules", HLConfigManager.Platform),
                                //                "VolumePointExceedsThreshold").ToString(), cart.CurrentItems[0].SKU));
                                //}
                                //}
                                //else
                                //{
                                //    if (cart.CartItems.Exists(item => item.SKU == cart.CurrentItems[0].SKU))
                                //    {
                                //        Result.AddMessage(
                                //            string.Format(
                                //                HttpContext.GetGlobalResourceObject(
                                //                    string.Format("{0}_Rules", HLConfigManager.Platform),
                                //                    "VolumePointExceedsByIncreasingQuantity").ToString(),
                                //                cart.CurrentItems[0].SKU, cart.CurrentItems[0].Quantity));
                                //    }
                                //    else
                                //    {
                                //        Result.AddMessage(
                                //            string.Format(
                                //                HttpContext.GetGlobalResourceObject(
                                //                    string.Format("{0}_Rules", HLConfigManager.Platform),
                                //                    "VolumePointExceeds").ToString(), cart.CurrentItems[0].SKU));
                                //    }
                                //}
                            }
                        }
                    }
                }
            }
            return(Result);
        }