public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule  = (PercentFixedDicountConfig)DiscountConfigItem;
            var items = model.Items.Where(x => rule.ProductShopIDs.Contains("," + x.ProductShopID + ",")).ToList();

            if (items.Count > 0)
            {
                foreach (var item in items)
                {
                    if (!DiscountService.LimitCheck(lim, curdiscount.Limit, curdiscount.LimitType))
                    {
                        break;
                    }
                    if (curdiscount.IsPercent)
                    {
                        item.Price = item.Price - (item.Price * curdiscount.Percent / 100);
                    }
                    else
                    {
                        item.Price = item.Price - curdiscount.Amount;
                    }
                    if (item.Price < 0)
                    {
                        item.Price = 0;
                    }
                    lim++;
                }

                return(true);
            }

            return(false);
        }
Exemple #2
0
        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule = (MustHaveAllOfThisDiscountConfig)DiscountConfigItem;

            var musthave = new List <string>();

            if (rule.ProductShopIDs != null)
            {
                musthave = rule.ProductShopIDs.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                           .Select(x => x.Trim())
                           .ToList();
            }


            foreach (var item in model.Items)
            {
                if (musthave.Contains(item.ProductShopID.ToString()))
                {
                    musthave.Remove(item.ProductShopID.ToString());
                }
                if (musthave.Count == 0)
                {
                    return(true);
                }
            }
            if (musthave.Count == 0)
            {
                return(true);
            }

            return(false);
        }
Exemple #3
0
        // its can be from child action and ajax loaded
        public ActionResult FooterCart(int ID = 0, bool tableonly = false)
        {
            var model = new ShoppingCartOverviewModel();

            if (LS.isHaveID())
            {
                if (ID == 0)
                {
                    if (LS.CurrentHttpContext.Session["ShopID"] != null)
                    {
                        ID = (int)LS.CurrentHttpContext.Session["ShopID"];
                    }
                    else
                    {
                        ID = ShoppingCartService.GetFirstShopID();
                    }
                }
                model = _shoppingCartService.GetShoppingCartModel(ID, withship: true);

                //_db.ShoppingCartItems.Where(x => x.UserID == LS.CurrentUser.ID).ToList();
            }

            if (!string.IsNullOrEmpty(model.Shop.Theme))
            {
                this.HttpContext.Items["ShopTheme"] = model.Shop.Theme;
            }

            if (tableonly)
            {
                return(PartialView("_CartTable", model));
            }
            return(PartialView(model));
        }
        public ActionResult ChangeShop(int ID, int ToShopID)
        {
            //if (!LS.isLogined())
            //{
            //    return RedirectToAction("Index","Main");
            //}
            var curShopModel = new ShoppingCartOverviewModel();

            curShopModel.Items = _shoppingCartService.GetShoppingCartItems(ID, true);

            var model = new ShoppingCartOverviewModel();

            model.Items = ShoppingCartService.GetShoppingCartItemsByList(ToShopID, curShopModel.Items);
            var items = model.Items.Where(x => !x.IsNotAvaliable &&
                                          !x.SelectedAttributeNotAvaliable &&
                                          !x.IsHaveNotQuantity).ToList();

            foreach (var oi in items)
            {
                if (oi.Quantity > 0)
                {
                    ShoppingCartService.AddToCart(LS.CurrentUser.ID, new ShoppingCartItem()
                    {
                        ProductAttributeOptionID = oi.ProductAttributeOptionID,
                        ProductShopID            = oi.ProductShopID,
                        Quantity = oi.Quantity,
                        ShopID   = oi.ShopID,
                    });
                }
            }
            Shop shop = _db.Shops.FirstOrDefault(r => r.ID == ToShopID);

            return(Redirect("/" + shop.SeoUrl));
        }
Exemple #5
0
        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule = (BuyXProductsForYConfig)DiscountConfigItem;

            var cartItemsForDiscount = model.Items.Where(x => !String.IsNullOrEmpty(rule.ProductShopsIds) && rule.ProductShopsIds.Contains(x.ProductShopID.ToString()));

            if (cartItemsForDiscount.Count() == 0)
            {
                return(false);
            }

            var totalQuantity = (int)Math.Truncate(cartItemsForDiscount.Select(x => x.Quantity).DefaultIfEmpty(0).Sum());

            if (totalQuantity < rule.MinTotalOfRequiredQuantity)
            {
                return(false);
            }

            int     multiplicator        = totalQuantity / rule.MinTotalOfRequiredQuantity;
            decimal newSoldPrice         = multiplicator * rule.PayAmount;
            var     quuantityForDiscount = multiplicator * rule.MinTotalOfRequiredQuantity;

            var cartItemProducts = GetFlattenCartItem(cartItemsForDiscount, quuantityForDiscount);

            decimal oldSoldPrice = cartItemProducts.Sum(x => x.Price);

            if (oldSoldPrice <= newSoldPrice)
            {
                return(false);
            }

            var discountTotal = oldSoldPrice - newSoldPrice;

            var discountByProductId = CalculateDiscountByProductId(discountTotal, cartItemProducts);

            foreach (var item in model.Items)
            {
                if (!discountByProductId.ContainsKey(item.ProductID))
                {
                    continue;
                }
                item.TotalDiscountAmount  = discountByProductId[item.ProductID];
                item.DiscountDescription += String.IsNullOrEmpty(item.DiscountDescription) ?
                                            curdiscount.Name
                                            : item.DiscountDescription + "," + curdiscount.Name;
                item.DiscountIDs.Add(curdiscount.ID);
            }

            var userdata = ShoppingCartService.GetCheckoutData();

            if (curdiscount.IsCodeRequired && curdiscount.DiscountCode == userdata.CouponCode)
            {
                model.DiscountByCouponeCodeText = curdiscount.Name;
            }

            //we must return true, but discountservice change all item for all products for discount,
            //so we return false
            return(false);
        }
Exemple #6
0
        //  public string Title = "Percent or fixed amount discount";
        //public DiscountType Type
        //{
        //    get
        //    {
        //        return DiscountType.ForCartTotal;
        //    }
        //}
        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule = (BuyOneGetOtherFreeDicountConfig)DiscountConfigItem;
            var productsList = curdiscount.GetProductsList();
            var totalQuantity = model.Items.Where(x => productsList.Contains(x.ProductShopID.ToString())).Select(x => x.Quantity)
                .DefaultIfEmpty(0).Sum();

            if (totalQuantity >= rule.QuantityFrom)
            {
                var items = model.Items.Where(x => rule.FreeProductShopID == x.ProductShopID)
                .ToList();
                if (items.Count == 0)
                {
                    if (rule.AutoAddToCart)
                    {
                        var cartItem = new ShoppingCartItem()
                        {
                            ProductShopID = rule.FreeProductShopID,
                            Quantity = 1,
                            ShopID = model.ShopID
                        };
                        ShoppingCartService.AddToCart(user.ID, cartItem);
                        var cartItemModel = ShoppingCartService.GetShoppingCartItemByID(cartItem.ID);
                        model.Items.Add(cartItemModel);
                        items.Add(cartItemModel);
                    }
                }
                if (items.Count > 0)
                {

                    foreach (var item in items)
                    {
                        if (!DiscountService.LimitCheck(lim, curdiscount.Limit, curdiscount.LimitType))
                        {
                            break;
                        }
                        if (item.Quantity <= rule.MaxFreeQuantity)
                        {
                            item.Price = 0;// show that price is zero
                        }
                        else
                        {
                            item.TotalDiscountAmount += item.Price * rule.MaxFreeQuantity;// can be only one free, so we change unit price
                        }
                        lim++;

                    }

                    return true;
                }
            }

            return false;
        }
        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule = (CartSubTotalDicountConfig)DiscountConfigItem;


            if (model.Items.Select(x => x.Price * x.Quantity).DefaultIfEmpty(0).Sum() >= rule.MinAmount)
            {
                return(true);
            }

            return(false);
        }
        //  public string Title = "Percent or fixed amount discount";
        //public DiscountType Type {
        //    get{
        //return DiscountType.ForCartItem;
        //}
        //}



        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule  = (QuantityDicountConfig)DiscountConfigItem;
            var items = model.Items.Where(x => x.ProductShopID == rule.ProductShopID && x.Quantity >= rule.QuantityFrom).ToList();

            if (items.Count > 0)
            {
                return(true);
            }

            return(false);
        }
        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule = (HasRoleDiscountConfig)DiscountConfigItem;


            if (LS.CurrentUser.Roles != null && LS.CurrentUser.Roles.Contains(rule.Role))
            {
                return(true);
            }

            return(false);
        }
Exemple #10
0
        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule = (CartWeigthDiscountConfig)DiscountConfigItem;


            if (model.Items.Where(x => x.SoldByWeight && x.MeasureUnit != null)
                .Select(x => ExtractDecimal(x.Capacity) * x.Quantity).DefaultIfEmpty(0).Sum() >= rule.MinWeigthKg)
            {
                //  קג - Kg
                //  ALL in Kg
                return(true);
            }

            return(false);
        }
Exemple #11
0
        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule  = (CategoryDiscountConfig)DiscountConfigItem;
            var items = model.Items.Where(x => x.CategoryID == rule.CategoryID).ToList();

            if (items.Count > 0 && items.Sum(x => x.Quantity) >= rule.MinQuantity)
            {
                //foreach (var item in items)
                //{
                //    if (!DiscountService.LimitCheck(lim, curdiscount.Limit, curdiscount.LimitType))
                //    {
                //        break;
                //    }
                //    if (rule.DiscountType == CategoryDiscountConfigType.ForItemPrice)
                //    {
                //        if (rule.IsPercent)
                //        {
                //            item.Price = item.Price - (item.Price * rule.Percent / 100);
                //        }
                //        else
                //        {
                //            item.Price = item.Price - rule.Amount;
                //        }
                //        if (item.Price < 0) { item.Price = 0; }
                //    }
                //    else
                //    {
                //        if (rule.IsPercent)
                //        {
                //            item.TotalDiscountAmount =  item.Price * rule.Percent * item.Quantity / 100;
                //        }
                //        else
                //        {
                //            item.TotalDiscountAmount = rule.Amount;
                //        }

                //    }
                //    lim++;

                //}

                return(true);
            }

            return(false);
        }
        public DiscountDescriptor CalculateDiscountByCode(string code, ShoppingCartOverviewModel overview)
        {
            Discount discount       = _db.Discounts.FirstOrDefault(_ => _.Active && _.DiscountCode == code);
            decimal  itemsCount     = overview.Items.Select(_ => _.Quantity).Sum();
            bool     isPercent      = discount.IsPercent;
            decimal  discountAmount = discount.Amount;
            decimal  discountValue  = 0m;
            var      diff           = (isPercent ? overview.Total * (discountAmount / 100) : discountAmount);

            if (discount.DiscountCartItemType == DiscountCartItemType.ForItemPrice)
            {
                diff *= itemsCount;
            }

            discountValue = overview.Total - diff;

            return(new DiscountDescriptor
            {
                Amount = discountValue,
                InPercents = isPercent
            });
        }
        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule = (BuyXProductsGetDiscountForCheapestConfig)DiscountConfigItem;

            var cartItemsForDiscount = model.Items.Where(x => rule.ProductShopsIds.Contains(x.ProductShopID.ToString()));

            if (cartItemsForDiscount.Count() == 0)
            {
                return(false);
            }

            var totalQuantity = (int)Math.Truncate(cartItemsForDiscount.Select(x => x.Quantity).DefaultIfEmpty(0).Sum());

            if (totalQuantity < rule.MinTotalOfRequiredQuantity)
            {
                return(false);
            }

            var cheapest = cartItemsForDiscount.OrderBy(x => x.Price).First();
            var newPrice = Math.Truncate((cheapest.Price - (cheapest.Price * rule.Percent / 100)) * 100) / 100;
            var discount = cheapest.Price - newPrice;

            cheapest.TotalDiscountAmount  = discount;
            cheapest.DiscountDescription += String.IsNullOrEmpty(cheapest.DiscountDescription) ?
                                            curdiscount.Name
                                        : cheapest.DiscountDescription + "," + curdiscount.Name;
            cheapest.DiscountIDs.Add(curdiscount.ID);
            var userdata = ShoppingCartService.GetCheckoutData();

            if (curdiscount.IsCodeRequired && curdiscount.DiscountCode == userdata.CouponCode)
            {
                model.DiscountByCouponeCodeText = curdiscount.Name;
            }

            //we must return true, but discountservice change all item for all products for discount,
            //so we return false
            return(false);
        }
        //  public string Title = "Percent or fixed amount discount";
        //public DiscountType Type {
        //    get{
        //return DiscountType.ForCartItem;
        //}
        //}
        public bool Process(ShoppingCartOverviewModel model, Discount curdiscount, object DiscountConfigItem, User user, int lim)
        {
            var rule          = (BuyOneOfThisGetOtherFreeDiscountConfig)DiscountConfigItem;
            var productsList  = curdiscount.GetProductsList();
            var totalQuantity = model.Items.Where(x => productsList.Contains(x.ProductShopID.ToString())).Select(x => x.Quantity)
                                .DefaultIfEmpty(0).Sum();

            if (totalQuantity >= rule.MinTotalOfRequiredQuantity)
            {
                var items = model.Items.Where(x => rule.ProductShopForFreeIDs.Contains(x.ProductShopID.ToString()))
                            .ToList();
                decimal restQuantity = rule.MaxFreeQuantity;
                if (items.Count > 0)
                {
                    foreach (var item in items)
                    {
                        if (!DiscountService.LimitCheck(lim, curdiscount.Limit, curdiscount.LimitType))
                        {
                            break;
                        }
                        if (item.Quantity <= restQuantity)
                        {
                            item.Price = 0;// show that price is zero
                        }
                        else
                        {
                            item.TotalDiscountAmount += item.Price * restQuantity;// can be only one free, so we change unit price
                        }
                        restQuantity -= item.Quantity;
                        lim++;
                    }

                    return(true);
                }
            }

            return(false);
        }
        public void ProcessTotals(ShoppingCartOverviewModel model, User user)
        {
            if (model.Items.Count > 0)
            {
                var userdata = ShoppingCartService.GetCheckoutData();
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();


                foreach (var typDisc in _TotalProcessKeys)
                {
                    var discounts = LS.Get <Discount>(model.ShopID.ToString() + "_" + typDisc)

                    ;     // search discounts for shop and type
                    discounts.AddRange(LS.Get <Discount>("0_" + typDisc));
                    bool success = false;


                    if (typDisc == DiscountType.ForCartTotal.ToString())
                    {
                        //fix total after previous discounts
                        model.TotalWithoutShip = model.SubTotal + model.Fee;
                        model.Total            = model.SubTotal + model.ShippingCost + model.Fee;
                    }
                    if (discounts.Count > 0)
                    {
                        foreach (var curdiscount in discounts)
                        {
                            #region process discount for cart totals
                            bool breakmain = false;
                            if (curdiscount.IsCodeRequired)
                            {
                                if (string.IsNullOrEmpty(userdata.CouponCode) || userdata.CouponCode != curdiscount.DiscountCode)
                                {
                                    continue; // code doesn`t match
                                }
                            }
                            if (!DiscountService.ExpiriedCheck(curdiscount))
                            {
                                continue;
                            }
                            int curUsesNumber = GetCurrentLimitPosition(curdiscount, user, _UseCache);
                            if (LimitCheck(curUsesNumber, curdiscount.Limit, curdiscount.LimitType))
                            {
                                success = true;
                                foreach (var d in GetRules().Where(x =>
                                                                   // x.Value.Type == DiscountType.ForCartItem &&
                                                                   curdiscount.RuleList.Select(y => y.Name).Contains(x.Key)
                                                                   ))
                                {
                                    var confitem = d.Value.GetConfigItem();

                                    int i = 0;
                                    foreach (var r in curdiscount.RuleList.Where(x => x.Name == d.Key))
                                    {
                                        i++;

                                        //from cache :)
                                        var o = curdiscount.GetRuleConfigObject(i.ToString() + r.Name, () =>
                                        {
                                            return(js.Deserialize(r.Value, confitem.GetType()));
                                        });


                                        success = success && d.Value.Process(model, curdiscount, o, user, curUsesNumber);
                                    }
                                }
                                if (success)
                                {
                                    bool actual = false;
                                    #region subtotal
                                    if (curdiscount.DiscountType == DiscountType.ForCartSubTotal)
                                    {
                                        if (model.SubTotal > 0)
                                        {
                                            decimal minus = 0;
                                            if (curdiscount.IsPercent)
                                            {
                                                minus          = (model.SubTotal * curdiscount.Percent / 100);
                                                model.SubTotal = model.SubTotal - minus;
                                            }
                                            else
                                            {
                                                minus          = curdiscount.Amount;
                                                model.SubTotal = model.SubTotal - curdiscount.Amount;
                                            }
                                            if (model.SubTotal < 0)
                                            {
                                                model.SubTotal = 0;
                                            }
                                            model.TotalDiscount += minus;
                                            actual = true;
                                        }
                                    }
                                    #endregion
                                    #region ship
                                    else if (curdiscount.DiscountType == DiscountType.ForCartShip)
                                    {
                                        if (model.SubTotal < model.FreeShipFrom)
                                        {
                                            model.ShippingCost = model.ShopShipCost;
                                        }
                                        if (model.ShippingCost > 0)
                                        {
                                            decimal minus = 0;
                                            if (curdiscount.IsPercent)
                                            {
                                                minus = (model.ShippingCost * curdiscount.Percent / 100);
                                                model.ShippingCost = model.ShippingCost - minus;
                                            }
                                            else
                                            {
                                                minus = curdiscount.Amount;
                                                model.ShippingCost = model.ShippingCost - curdiscount.Amount;
                                            }
                                            if (model.ShippingCost < 0)
                                            {
                                                model.ShippingCost = 0;
                                            }
                                            model.TotalDiscount += minus;
                                            actual = true;
                                        }
                                    }
                                    #endregion
                                    #region payment fee
                                    //else if (curdiscount.DiscountType == DiscountType.ForCartFee)
                                    //{
                                    //    if (model.Fee > 0)
                                    //    {
                                    //        decimal minus = 0;
                                    //        if (curdiscount.IsPercent)
                                    //        {
                                    //            minus = (model.Fee * curdiscount.Percent / 100);
                                    //            model.Fee = model.Fee - minus;
                                    //        }
                                    //        else
                                    //        {
                                    //            minus = curdiscount.Amount;
                                    //            model.Fee = model.Fee - curdiscount.Amount;
                                    //        }
                                    //        if (model.Fee < 0) { model.Fee = 0; }
                                    //        model.TotalDiscount += minus;
                                    //        actual = true;
                                    //    }
                                    //}
                                    #endregion
                                    #region total
                                    else if (curdiscount.DiscountType == DiscountType.ForCartTotal)
                                    {
                                        if (model.Total > 0)
                                        {
                                            decimal minus = 0;
                                            if (curdiscount.IsPercent)
                                            {
                                                minus       = (model.Total * curdiscount.Percent / 100);
                                                model.Total = model.Total - minus;
                                            }
                                            else
                                            {
                                                minus       = curdiscount.Amount;
                                                model.Total = model.Total - curdiscount.Amount;
                                            }
                                            if (model.Total < 0)
                                            {
                                                model.Total = 0;
                                            }
                                            model.TotalDiscount += minus;
                                            actual = true;
                                        }
                                    }
                                    #endregion
                                    if (actual)//if actual
                                    {
                                        if (curdiscount.IsCodeRequired && curdiscount.DiscountCode == userdata.CouponCode)
                                        {
                                            model.DiscountByCouponeCodeText = curdiscount.Name;
                                        }
                                        curUsesNumber++;

                                        if (!string.IsNullOrEmpty(model.DiscountDescription))
                                        {
                                            model.DiscountDescription += ", " + curdiscount.Name;
                                        }
                                        else
                                        {
                                            model.DiscountDescription = curdiscount.Name;
                                        }
                                        if (curdiscount.LessShopFee)
                                        {
                                            model.IsLessMemberFee = true;
                                        }
                                        model.DiscountIDs.Add(curdiscount.ID);//for history save
                                        if (curdiscount.PreventNext)
                                        {
                                            breakmain = true;
                                        }
                                    }
                                }
                            }

                            if (breakmain)
                            {
                                break;
                            }
                            #endregion
                        }
                    }
                }
            }
        }
        public void ProcessItems(ShoppingCartOverviewModel model, User user)
        {
            //discounts

            if (model.Items.Count > 0)
            {
                var userdata = ShoppingCartService.GetCheckoutData();
                System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();



                var  discounts = LS.Get <Discount>(model.ShopID.ToString() + "_" + DiscountType.ForCartItem.ToString()); // search discounts for shop and type
                bool success   = false;
                foreach (var curdiscount in discounts)
                {
                    #region process discount for cart items
                    bool breakmain = false;
                    if (curdiscount.IsCodeRequired)
                    {
                        if (string.IsNullOrEmpty(userdata.CouponCode) || userdata.CouponCode != curdiscount.DiscountCode)
                        {
                            continue; // code doesn`t match
                        }
                    }
                    if (!DiscountService.ExpiriedCheck(curdiscount))
                    {
                        continue;
                    }
                    int curUsesNumber = GetCurrentLimitPosition(curdiscount, user, _UseCache, userdata.FullName, userdata.Phone, userdata.Address, user.Email);
                    if (LimitCheck(curUsesNumber, curdiscount.Limit, curdiscount.LimitType))
                    {
                        success = true;
                        foreach (var d in GetRules().Where(x =>
                                                           // x.Value.Type == DiscountType.ForCartItem &&
                                                           curdiscount.RuleList.Select(y => y.Name).Contains(x.Key)
                                                           ))
                        {
                            var confitem = d.Value.GetConfigItem();

                            int i = 0;
                            foreach (var r in curdiscount.RuleList.Where(x => x.Name == d.Key))
                            {
                                i++;

                                //from cache :)
                                var o = curdiscount.GetRuleConfigObject(i.ToString() + r.Name, () =>
                                {
                                    return(js.Deserialize(r.Value, confitem.GetType()));
                                });


                                success = success && d.Value.Process(model, curdiscount, o, user, curUsesNumber);
                            }
                        }
                        if (success)
                        {
                            var productsList = curdiscount.GetProductsList();
                            if (curdiscount.IsCodeRequired && curdiscount.DiscountCode == userdata.CouponCode)
                            {
                                model.DiscountByCouponeCodeText = curdiscount.Name;
                            }
                            foreach (var item in model.Items.Where(x => productsList.Contains(x.ProductShopID.ToString())))
                            {
                                if (!DiscountService.LimitCheck(curUsesNumber, curdiscount.Limit, curdiscount.LimitType))
                                {
                                    break;
                                }
                                if (item.Price > 0 && item.TotalDiscountAmount < item.Price * item.Quantity)//only if actual
                                {
                                    if (curdiscount.DiscountCartItemType == DiscountCartItemType.ForItemPrice)
                                    {
                                        if (curdiscount.IsPercent)
                                        {
                                            item.Price = item.Price - (item.Price * curdiscount.Percent / 100);
                                        }
                                        else
                                        {
                                            item.Price = item.Price - curdiscount.Amount;
                                        }
                                        if (item.Price < 0)
                                        {
                                            item.Price = 0;
                                        }
                                    }
                                    else
                                    {
                                        if (curdiscount.IsPercent)
                                        {
                                            item.TotalDiscountAmount = item.Price * curdiscount.Percent * item.Quantity / 100;
                                        }
                                        else
                                        {
                                            item.TotalDiscountAmount = curdiscount.Amount;
                                        }
                                    }
                                    if (!string.IsNullOrEmpty(item.DiscountDescription))
                                    {
                                        item.DiscountDescription += ", " + curdiscount.Name;
                                    }
                                    else
                                    {
                                        item.DiscountDescription = curdiscount.Name;
                                    }
                                    item.DiscountIDs.Add(curdiscount.ID);
                                    if (curdiscount.LessShopFee)
                                    {
                                        model.IsLessMemberFee = true;
                                    }
                                    curUsesNumber++;
                                }
                            }

                            if (curdiscount.PreventNext)
                            {
                                breakmain = true;
                            }
                        }

                        if (breakmain)
                        {
                            break;
                        }
                    }
                    #endregion
                }
            }
        }
        public ActionResult _ChangeShopPopup(int shopID)
        {
            var data     = new List <ShoppingCartOverviewModel>();
            var curdate  = DateTime.Now.Date;
            var lastdate = curdate.AddDays(7);
            var culture  = new System.Globalization.CultureInfo("he-IL");

            ViewBag.CurrentShopID = shopID;
            var curShop      = ShoppingService.GetShopByID(shopID);
            var curShopModel = new ShoppingCartOverviewModel();

            curShopModel.Items    = _shoppingCartService.GetShoppingCartItems(shopID, true);
            curShopModel.ShopID   = shopID;
            curShopModel.Shop     = curShop;
            curShopModel.Total    = curShopModel.Items.Count > 0 ? curShopModel.Items.Sum(x => x.UnitPrice) : 0;
            curShopModel.TotalStr = ShoppingService.FormatPrice(curShopModel.Total);
            curShopModel.Count    = curShopModel.Items.Count;
            //work times
            curShopModel.WorkTimes = _db.ShopWorkTimes.Where(x => x.ShopID == shopID && x.Active &&
                                                             (!x.IsSpecial || (x.Date >= curdate && x.Date <= lastdate))
                                                             ).OrderBy(x => x.IsSpecial).ThenBy(x => x.Day).ThenBy(x => x.Date)
                                     .Select(x => new ShipTimeModel()
            {
                Date        = x.Date,
                Day         = x.Day,
                TimeFromInt = x.TimeFrom,
                TimeToInt   = x.TimeTo,
                IsSpecial   = x.IsSpecial,
            })
                                     .ToList();
            foreach (var t in curShopModel.WorkTimes)
            {
                t.DayStr       = culture.DateTimeFormat.GetDayName(t.Day);
                t.TimeFromeStr = TimeSpan.FromMinutes(t.TimeFromInt).ToString("hh':'mm");
                t.TimeToStr    = TimeSpan.FromMinutes(t.TimeToInt).ToString("hh':'mm");
                t.DateStr      = t.Date.ToString("dd/MM");
            }
            data.Add(curShopModel);
            //missing products


            // find by address
            decimal longitude = 0;
            decimal latitude  = 0;

            if (LS.isLogined())
            {
                if (LS.CurrentUser.Latitude != 0)
                {
                    latitude = LS.CurrentUser.Latitude;
                }
                if (LS.CurrentUser.Longitude != 0)
                {
                    longitude = LS.CurrentUser.Longitude;
                }
            }


            //if not regognized
            if (longitude == 0)
            {
                if (Session["longitude"] != null)
                {
                    longitude = (decimal)Session["longitude"];
                }
            }
            if (latitude == 0)
            {
                if (Session["latitude"] != null)
                {
                    latitude = (decimal)Session["latitude"];
                }
            }
            string address = "";

            if (Session["address"] != null)
            {
                address = (string)Session["address"];
            }
            var shops = new List <Shop>();

            if (latitude == 0 || longitude == 0)
            {
                shops = ShoppingService.GetNearestShop(0, latitude, longitude, address, true).ToList();
            }
            else
            {
                shops = ShoppingService.GetNearestShop(0, latitude, longitude, address).ToList();
            }
            string[] ids = new string[] { };
            if (!string.IsNullOrEmpty(curShop.ShopTypeIDs))
            {
                ids = curShop.ShopTypeIDs.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }
            Expression <Func <Shop, bool> > predicate = null;

            foreach (var s in ids)
            {
                if (predicate != null)
                {
                    predicate = predicate.MultiSearchOr(x => x.ShopTypeIDs != null &&
                                                        (x.ShopTypeIDs.Contains("," + s + ",") ||
                                                         x.ShopTypeIDs == s ||
                                                         x.ShopTypeIDs.StartsWith(s + ",") ||
                                                         x.ShopTypeIDs.EndsWith("," + s)
                                                        )
                                                        );
                }
                else
                {
                    predicate = x => x.ShopTypeIDs != null && (x.ShopTypeIDs.Contains("," + s + ",") ||
                                                               x.ShopTypeIDs == s ||
                                                               x.ShopTypeIDs.StartsWith(s + ",") ||
                                                               x.ShopTypeIDs.EndsWith("," + s)
                                                               );
                }
            }
            if (predicate != null)
            {
                shops = shops.Where(predicate.Compile()).ToList();
            }

            foreach (var shop in shops)
            {
                if (shop.ID != curShopModel.ShopID)
                {
                    var model = new ShoppingCartOverviewModel();
                    // model.Items = ShoppingCartService.GetShoppingCartItems(shop.ID, true);
                    model.Items  = ShoppingCartService.GetShoppingCartItemsByList(shop.ID, curShopModel.Items);
                    model.ShopID = shop.ID;
                    model.Shop   = shop;
                    var items = model.Items.Where(x => !x.IsNotAvaliable &&
                                                  !x.SelectedAttributeNotAvaliable &&
                                                  !x.IsHaveNotQuantity).ToList();
                    model.NotAvaliableItems = model.Items.Where(x => x.IsNotAvaliable ||
                                                                x.SelectedAttributeNotAvaliable ||
                                                                x.IsHaveNotQuantity).ToList();
                    model.Total    = items.Count > 0 ? items.Sum(x => x.UnitPrice) : 0;
                    model.TotalStr = ShoppingService.FormatPrice(model.Total);
                    model.Count    = model.Items.Count;
                    //work times

                    model.WorkTimes = _db.ShopWorkTimes.Where(x => x.ShopID == shopID && x.Active &&
                                                              (!x.IsSpecial || (x.Date >= curdate && x.Date <= lastdate))
                                                              ).OrderBy(x => x.IsSpecial).ThenBy(x => x.Day).ThenBy(x => x.Date)
                                      .Select(x => new ShipTimeModel()
                    {
                        Date        = x.Date,
                        Day         = x.Day,
                        TimeFromInt = x.TimeFrom,
                        TimeToInt   = x.TimeTo,
                        IsSpecial   = x.IsSpecial,
                    })
                                      .ToList();
                    foreach (var t in model.WorkTimes)
                    {
                        t.DayStr       = culture.DateTimeFormat.GetDayName(t.Day);
                        t.TimeFromeStr = TimeSpan.FromMinutes(t.TimeFromInt).ToString("hh':'mm");
                        t.TimeToStr    = TimeSpan.FromMinutes(t.TimeToInt).ToString("hh':'mm");
                        t.DateStr      = t.Date.ToString("dd/MM");
                    }

                    data.Add(model);
                }
            }

            if (!string.IsNullOrEmpty(curShop.Theme))
            {
                this.HttpContext.Items["ShopTheme"] = curShop.Theme;
            }

            return(PartialView(data));
        }
        public ShoppingCartOverviewModel GetShoppingCartModel(int ShopID
                                                              , bool loadattributes = true
                                                              , bool withship       = false
                                                              , bool withdiscount   = true
                                                              , bool feutured       = false
                                                              , bool loadworktimes  = false
                                                              , bool nocache        = false
                                                              , bool checkQuantity  = false
                                                              , bool loadComments   = false
                                                              , Guid UserID         = new Guid())
        {
            if (UserID == Guid.Empty && LS.isHaveID())
            {
                UserID = LS.CurrentUser.ID;
            }
            var model = new ShoppingCartOverviewModel();
            List <SpecificationOptionModel> specifications = null;

            model.ShopID = ShopID;
            var shop = LS.Get <Shop>().FirstOrDefault(x => x.ID == ShopID);

            if (shop == null)
            {
                return(model);
            }
            model.Shop                 = shop;
            model.IsShipEnabled        = shop.IsShipEnabled;
            model.InStorePickUpEnabled = shop.InStorePickUpEnabled;
            if (LS.isHaveID())
            {
                model.Items = this.GetShoppingCartItems(ShopID, loadattributes, withdiscount: withdiscount, checkQuantity: checkQuantity, UserID: UserID);

                model.IsLogined = true;
                if (withdiscount)
                {
                    // process discounts

                    var discountService = new DiscountService(_db, nocache);
                    discountService.ProcessItems(model, LS.CurrentUser);
                }
                //fix and format prices
                foreach (var item in model.Items)
                {
                    item.UnitPrice = item.Price * item.Quantity - item.TotalDiscountAmount;
                    if (item.UnitPrice < 0)
                    {
                        item.UnitPrice = 0;
                    }
                    string ustep = "1";
                    if (item.MeasureUnitStep.HasValue)
                    {
                        //item.UnitPrice = item.UnitPrice / item.MeasureUnitStep.Value;
                        // ustep = item.MeasureUnitStep.Value.ToString();
                    }

                    item.PriceStr     = ShoppingService.FormatPrice(item.Price) + (item.MeasureUnit != null ? " / " + item.MeasureUnit : "");
                    item.UnitPriceStr = ShoppingService.FormatPrice(item.UnitPrice);
                    //+ ( item.TotalDiscountAmount > 0
                    //   ? " (-" + ShoppingService.FormatPrice(item.TotalDiscountAmount) + ")"
                    // : "");
                    if (false && loadComments)
                    {
                        item.Comments = ShoppingService.GetUserNoteForProduct(item.ProductID, LS.CurrentUser.ID);
                    }
                }

                model.FreeShipFrom = shop.FreeShipFrom;
                model.ShopShipCost = shop.ShipCost;

                var deliveryZones = LS.Get <ShopDeliveryZone>().Where(x => x.ShopID == ShopID && x.Active).ToList();
                if (deliveryZones.Count > 0)
                {
                    //searching by couples zones
                    var     checkoutData = ShoppingCartService.GetCheckoutData(UserID);
                    var     address      = "";
                    decimal longitude    = 0;
                    decimal latitude     = 0;
                    if (LS.CurrentUser.Latitude != 0)
                    {
                        latitude = LS.CurrentUser.Latitude;
                    }
                    if (LS.CurrentUser.Longitude != 0)
                    {
                        longitude = LS.CurrentUser.Longitude;
                    }
                    if (LS.CurrentHttpContext != null)
                    {
                        //if not regognized
                        if (longitude == 0)
                        {
                            if (LS.CurrentHttpContext.Session["longitude"] != null)
                            {
                                longitude = (decimal)LS.CurrentHttpContext.Session["longitude"];
                            }
                        }
                        if (latitude == 0)
                        {
                            if (LS.CurrentHttpContext.Session["latitude"] != null)
                            {
                                latitude = (decimal)LS.CurrentHttpContext.Session["latitude"];
                            }
                        }
                    }
                    if (LS.CurrentHttpContext != null && LS.CurrentHttpContext.Session["address"] != null)
                    {
                        address = (string)LS.CurrentHttpContext.Session["address"];
                    }
                    else
                    {
                        address = checkoutData.Address;
                    }
                    if (address == null)
                    {
                        address = "";
                    }
                    // find by address



                    var lowerCaseAddress = address.ToLower();

                    List <DeliveryZoneSmall> allPossible = new List <DeliveryZoneSmall>();
                    //add default shop zone
                    var clientDefaultradius = ShoppingService.distance((double)shop.RadiusLatitude, (double)shop.RadiusLongitude
                                                                       , (double)latitude, (double)longitude, 'K');
                    if (clientDefaultradius <= (double)shop.ShipRadius)
                    {
                        allPossible.Add(new DeliveryZoneSmall()
                        {
                            ShipCost = shop.ShipCost
                            ,
                            FreeShipFrom = shop.FreeShipFrom,
                            Distance     = clientDefaultradius
                        });
                    }
                    foreach (var dz in deliveryZones)
                    {
                        if (dz.DeliveryFroAllCity && !string.IsNullOrEmpty(dz.City) &&
                            (
                                lowerCaseAddress.Contains(", " + dz.City.ToLower() + ", ") ||
                                lowerCaseAddress.StartsWith(dz.City.ToLower() + ", ")
                                // || lowerCaseAddress.EndsWith(", " + s.City.ToLower())
                                // || lowerCaseAddress.StartsWith(s.City.ToLower() + " ")
                                || lowerCaseAddress.EndsWith(", " + dz.City.ToLower())
                            )
                            )
                        {
                            allPossible.Add(new DeliveryZoneSmall()
                            {
                                ShipCost = dz.ShipCost, FreeShipFrom = dz.FreeShipFrom, Distance = 1
                            });
                        }
                        else if (!dz.DeliveryFroAllCity)
                        {
                            var clientradius = ShoppingService.distance((double)dz.RadiusLatitude, (double)dz.RadiusLongitude, (double)latitude, (double)longitude, 'K');
                            if (clientradius <= (double)dz.ShipRadius)
                            {
                                allPossible.Add(new DeliveryZoneSmall()
                                {
                                    ShipCost = dz.ShipCost
                                    ,
                                    FreeShipFrom = dz.FreeShipFrom,
                                    Distance     = clientradius
                                });
                            }
                        }
                    }
                    if (allPossible.Count > 0)
                    {
                        var firstBetter = allPossible.OrderBy(x => x.Distance).FirstOrDefault();
                        model.FreeShipFrom = firstBetter.FreeShipFrom;
                        model.ShopShipCost = firstBetter.ShipCost;
                    }
                }

                if (model.Items.Count > 0)
                {
                    model.SubTotal         = model.Items.Count > 0 ? model.Items.Sum(x => x.UnitPrice) : 0;
                    model.TotalWithoutShip = model.SubTotal;
                    if (withship && model.SubTotal < model.FreeShipFrom)
                    {
                        model.ShippingCost = model.ShopShipCost;
                    }
                    model.Total = model.SubTotal + model.ShippingCost + model.Fee;
                    model.Count = model.Items.Count;
                }
            }



            if (withdiscount)
            {
                // process total discounts

                var discountService = new DiscountService(_db, nocache);
                discountService.ProcessTotals(model, LS.CurrentUser);
            }
            //if (LS.isLogined())
            //{
            //    if (model.Items.Count > 0)
            //    {
            //        model.TotalWithoutShip = model.SubTotal;
            //        if (withship && model.SubTotal < shop.FreeShipFrom)
            //        {
            //            if (model.ShippingCost > 0)
            //            {
            //                model.ShippingCost = shop.ShipCost;
            //            }
            //        }


            //    }
            //}
            model.SubTotalStr         = ShoppingService.FormatPrice(model.SubTotal);
            model.ShippingCostStr     = ShoppingService.FormatPrice(model.ShippingCost);
            model.TotalWithoutShipStr = ShoppingService.FormatPrice(model.TotalWithoutShip);

            model.FeeStr           = ShoppingService.FormatPrice(model.Fee);
            model.TotalStr         = ShoppingService.FormatPrice(model.Total);
            model.TotalDiscountStr = ShoppingService.FormatPrice(model.TotalDiscount);
            //work and ship times
            if (loadworktimes)
            {
                var curdate  = DateTime.Now.Date;
                var lastdate = curdate.AddDays(7);
                model.ShipTimes = _db.ShopShipTimes.Where(x => x.ShopID == ShopID && x.Active &&
                                                          (!x.IsSpecial || (x.Date >= curdate && x.Date <= lastdate)
                                                          )
                                                          )
                                  .OrderBy(x => x.IsSpecial).ThenBy(x => x.Day).ThenBy(x => x.Date)
                                  .Select(x => new ShipTimeModel()
                {
                    Date        = x.Date,
                    Day         = x.Day,
                    TimeFromInt = x.TimeFrom,
                    TimeToInt   = x.TimeTo,
                    IsSpecial   = x.IsSpecial
                })
                                  .ToList();
                var culture = new System.Globalization.CultureInfo("he-IL");
                foreach (var t in model.ShipTimes)
                {
                    t.DayStr       = t.DayStr = culture.DateTimeFormat.GetDayName(t.Day);
                    t.TimeFromeStr = TimeSpan.FromMinutes(t.TimeFromInt).ToString("hh':'mm");
                    t.TimeToStr    = TimeSpan.FromMinutes(t.TimeToInt).ToString("hh':'mm");
                }

                model.WorkTimes = _db.ShopWorkTimes.Where(x => x.ShopID == ShopID && x.Active &&
                                                          (!x.IsSpecial || (x.Date >= curdate && x.Date <= lastdate))
                                                          ).OrderBy(x => x.IsSpecial).ThenBy(x => x.Day).ThenBy(x => x.Date)
                                  .Select(x => new ShipTimeModel()
                {
                    Date        = x.Date,
                    Day         = x.Day,
                    TimeFromInt = x.TimeFrom,
                    TimeToInt   = x.TimeTo,
                    IsSpecial   = x.IsSpecial,
                })
                                  .ToList();
                foreach (var t in model.WorkTimes)
                {
                    //t.DayStr = t.Day.ToString();
                    //t.TimeFromeStr = IntToTime(t.TimeFromInt);
                    //t.TimeToStr = IntToTime(t.TimeToInt);
                    //t.DateStr = t.Date.ToString("dd/MM");
                    t.DayStr       = culture.DateTimeFormat.GetDayName(t.Day);
                    t.TimeFromeStr = TimeSpan.FromMinutes(t.TimeFromInt).ToString("hh':'mm");
                    t.TimeToStr    = TimeSpan.FromMinutes(t.TimeToInt).ToString("hh':'mm");
                    t.DateStr      = t.Date.ToString("dd/MM");
                }
            }

            if (feutured)
            {
                var exceptProductShopIds = model.Items.Select(x => x.ProductShopID).ToList();
                model.FeaturedProducts = LS.SearchProducts(ShopID, out specifications, featuredLeft: true, excludeProductShopList: exceptProductShopIds, limit: 10).ToList();
                if (model.FeaturedProducts.Count < 10)
                {
                    int limitLeft = 10 - model.FeaturedProducts.Count;
                    var ordered   = LS.SearchProducts(ShopID, out specifications, allOrderedProducts: true, excludeProductShopList: exceptProductShopIds, limit: limitLeft).ToList();
                    foreach (var p in ordered)
                    {
                        if (!model.FeaturedProducts.Any(x => x.ProductShopID == p.ProductShopID))
                        {
                            model.FeaturedProducts.Add(p);
                        }
                    }
                }
                if (model.FeaturedProducts.Count < 10)
                {
                    int limitLeft = 10 - model.FeaturedProducts.Count;
                    var catId     = model.Items.Select(x => x.CategoryID).ToList();
                    if (catId.Count > 0)
                    {
                        var ordered = LS.SearchProducts(ShopID, out specifications, inCategories: catId, excludeProductShopList: exceptProductShopIds, limit: limitLeft).ToList();
                        foreach (var p in ordered)
                        {
                            if (!model.FeaturedProducts.Any(x => x.ProductShopID == p.ProductShopID))
                            {
                                model.FeaturedProducts.Add(p);
                            }
                        }
                    }
                }
            }
            return(model);
        }