Example #1
0
        public PromoModels.PromofiedCart ApplyPromo(string id)
        {
            if (string.IsNullOrEmpty(id))
            {
                throw new Exception("Not a valid cart id");
            }

            CartModels.Cart cart = GetCart(id);

            // assuming that promo code ids are sent in the controller request
            var promoCodes = new List <string>();

            var promoCollection = new List <PromoModels.Promo>();

            foreach (var pc in promoCodes)
            {
                var promo = _promoRepo.Get(pc);
                if (promo != null)
                {
                    promoCollection.Add(promo);
                }
            }
            // process promo code and get total price
            PromoModels.PromofiedCart promofiedCart = _promoEngine.Process(promoCollection, cart);

            return(promofiedCart);
        }
        // Implement the calculation process for promo engine
        PromoModels.PromofiedCart IPromoEngine.Process(List <PromoModels.Promo> promos, CartModels.Cart cart)
        {
            var groupedItems = new Dictionary <string, List <PromoModels.MarkedItem> >();

            foreach (var item in cart.Items)
            {
                if (!groupedItems.ContainsKey(item.Category))
                {
                    groupedItems.Add(item.Category, new List <PromoModels.MarkedItem> {
                        new PromoModels.MarkedItem {
                            Item = item, MarkedBuys = new Dictionary <string, bool>(), MarkedGets = new Dictionary <string, float>()
                        }
                    });
                }
                else
                {
                    groupedItems[item.Category].Add(new PromoModels.MarkedItem {
                        Item = item, MarkedBuys = new Dictionary <string, bool>(), MarkedGets = new Dictionary <string, float>()
                    });
                }
            }

            foreach (var promo in promos)
            {
                groupedItems = ApplyPromo(promo, groupedItems);
            }

            var items = new List <PromoModels.MarkedItem>();

            foreach (var item in groupedItems)
            {
                items.AddRange(item.Value);
            }

            var prices = ComputePrices(items);

            var totalPrice    = prices[0];
            var totalOffPrice = prices[1];

            PromoModels.PromofiedCart promofiedCart = new PromoModels.PromofiedCart {
                Items = items, TotalPrice = totalPrice, TotalOffPrice = totalOffPrice
            };
            return(promofiedCart);
        }