Example #1
0
        public ActionResult _AjaxIndex([DataSourceRequest] DataSourceRequest request)
        {
            IQueryable <Category> items  = _db.Categories.AsQueryable();
            DataSourceResult      result = items.ToDataSourceResult(request);

            var allCategories = LS.Get <Category>();

            foreach (var c in (IEnumerable <Category>)result.Data)
            {
                if (c.ParentCategoryID > 0)
                {
                    var pc = allCategories.FirstOrDefault(x => x.ID == c.ParentCategoryID);
                    if (pc != null)
                    {
                        c.ParentCategory = pc;
                    }
                }
                //cached product count
                c.CachedProductCount = LS.GetCachedFunc(() =>
                {
                    var cid = c.ID;
                    return(_db.Products.Where(x => x.Deleted == false && x.CategoryID == cid).Count());
                }, string.Format("productsInCategory-{0}.", c.ID), 60);
            }
            return(Json(result));
        }
        public int SendOrderUserCantPayToAdmin(Order order)
        {
            MethodBase            method = MethodBase.GetCurrentMethod();
            MailTemplateAttribute attr   = (MailTemplateAttribute)method.GetCustomAttributes(typeof(MailTemplateAttribute), true)[0];
            string templateSystemName    = attr.TemplateSystemName;

            var domain = _Context.EntityContext.SettingsAll.Select(x => x.AdminEmail).FirstOrDefault();
            var shop   = LS.Get <Shop>().FirstOrDefault(x => x.ID == order.ShopID);

            if (shop == null)
            {
                shop = new Shop();
            }
            var virtualUser = new User()
            {
                Email     = order.Email,
                FirstName = order.FullName != null ? order.FullName : "",
                ID        = order.UserID,
                Phone     = order.Phone,
                UserName  = order.Email
            };
            var res = Tokenize(templateSystemName, domain, new List <object>()
            {
                order, shop
                , virtualUser
            });

            return(res);
        }
Example #3
0
        public ActionResult _GetCategoriesAjax(int shopID)
        {
            var allCategories = LS.Get <Category>();//.Select(x => new { x.ID, x.Name, x.ParentCategoryID })
            var model         = allCategories.Where(x => x.ParentCategoryID == 0).Select(x => new TreeModel()
            {
                ID       = x.ID,
                Name     = x.Name,
                ParentID = x.ParentCategoryID
            }).ToList();

            foreach (var ctree in model)
            {
                ctree.Childrens = allCategories.Where(x => x.ParentCategoryID == ctree.ID).Select(x => new TreeModel()
                {
                    ID       = x.ID,
                    Name     = x.Name,
                    Path     = "  " + ctree.Name + " >> ",
                    ParentID = x.ParentCategoryID
                }).ToList();
            }
            var sid = shopID;
            var currentShopModel = _db.ShopCategoryMenus.Where(x => x.ShopID == sid).ToList();

            return(Json(new { categoryTree = model, menu = currentShopModel }));
        }
Example #4
0
        public ActionResult _AjaxDetailAutoComplete([DataSourceRequest] DataSourceRequest request, string text)
        {
            var items = LS.Get <ProductSmall>(
                "ProductSmall", false, () =>
            {
                return(_db.Products.AsNoTracking()
                       .Select(x => new ProductSmall()
                {
                    ID = x.ID,
                    Image = x.Image,
                    Name = x.Name,
                    SKU = x.SKU
                })
                       .ToList());
            },
                "Product"
                ).AsQueryable();


            if (!string.IsNullOrEmpty(text))
            {
                items = items.Where(x => (x.SKU != null && x.SKU.Contains(text)) ||
                                    (x.Name != null && x.Name.Contains(text))
                                    );
            }
            request.PageSize = 100;
            DataSourceResult result = items.ToDataSourceResult(request);

            return(Json(result));
        }
        public int SendOrderChangedEmailToUser(Order order, List <OrderItem> changed, List <OrderItem> outOfStock)
        {
            MethodBase            method = MethodBase.GetCurrentMethod();
            MailTemplateAttribute attr   = (MailTemplateAttribute)method.GetCustomAttributes(typeof(MailTemplateAttribute), true)[0];
            string templateSystemName    = attr.TemplateSystemName;

            var productChangeds = new OrderChangedProductTable(changed);
            var productRemoved  = new OrderRemovedProductTable(outOfStock);
            var shop            = LS.Get <Shop>().FirstOrDefault(x => x.ID == order.ShopID);
            var virtualUser     = new User()
            {
                Email     = order.Email,
                FirstName = order.FullName != null ? order.FullName : "",
                ID        = order.UserID,
                Phone     = order.Phone,
                UserName  = order.Email
            };
            var res = Tokenize(templateSystemName, order.Email, new List <object>()
            {
                order
                , shop
                , virtualUser
                , productChangeds
                , productRemoved
            });

            return(res);
        }
Example #6
0
 public ShopCategory()
 {
     if (DisplayOrder == 0)
     {
         var cat = LS.Get <Category>().FirstOrDefault(x => x.ID == this.CategoryID);
         if (cat != null)
         {
             DisplayOrder = cat.DisplayOrder;
         }
     }
 }
 public static void OnUpdating(Category category)
 {
     if (category != null)
     {
         var allCategories = LS.Get <Category>();
         var childs        = allCategories.Any(x => x.ParentCategoryID == category.ID);
         if (childs && category.ParentCategoryID != 0)
         {
             category.ParentCategoryID = 0;
         }
     }
 }
 public static void OnCreating(Product product)
 {
     product.HasImage     = !string.IsNullOrEmpty(product.Image);
     product.DisplayOrder = 0;
     if (product.ProductManufacturerID > 0)
     {
         var m = LS.Get <Manufacturer>().FirstOrDefault(x => x.ID == product.ProductManufacturerID);
         if (m != null)
         {
             product.DisplayOrder = m.DisplayOrder;
         }
     }
 }
Example #9
0
        public async static Task InsertOrder(Order order, string PageUrl, string RefererUrl, string IP)
        {
            if (ConfigurationManager.AppSettings["UseMongo"] != "true")
            {
                return;
            }
            var database   = GetMongoDB();
            var collection = database.GetCollection <UserOrderActivity>("UserOrderActivity");
            var activity   = new UserOrderActivity();

            activity.CreateOn   = DateTime.Now;
            activity.PageUrl    = PageUrl;
            activity.RefererUrl = RefererUrl;
            activity.ShopID     = order.ShopID;
            activity.UserID     = order.UserID;
            activity.UserIDStr  = order.UserID.ToString();
            activity.Address    = order.Address;
            activity.OrderID    = order.ID;
            activity.Total      = order.Total;
            var shop = LS.Get <Shop>().FirstOrDefault(x => x.ID == order.ShopID);

            if (shop != null)
            {
                if (shop.ShopTypeIDs != null)
                {
                    var types = LS.Get <ShopType>();
                    foreach (var type in types)
                    {
                        if (shop.ShopTypeIDs.Contains("," + type.ID.ToString() + ",")
                            ||
                            shop.ShopTypeIDs.StartsWith(type.ID.ToString() + ",")
                            ||
                            shop.ShopTypeIDs.EndsWith("," + type.ID.ToString())
                            )
                        {
                            if (string.IsNullOrEmpty(activity.ShopType))
                            {
                                activity.ShopType = type.Name;
                            }
                            else
                            {
                                activity.ShopType += ", " + type.Name;
                            }
                        }
                    }
                }
            }
            activity.IP = IP;
            await collection.InsertOneAsync(activity);
        }
        public ActionResult _OrderItemAjaxRead([DataSourceRequest] DataSourceRequest request)
        {
            if (CurrentShop == null)
            {
                return(Json(new { }));
            }
            var ShopID     = CurrentShop.ID;
            var decimalInt = (double)((FilterDescriptor)request.Filters.FirstOrDefault()).ConvertedValue;
            var orderID    = Convert.ToInt32(decimalInt);
            var query      = (
                from oi in LS.CurrentEntityContext.OrderItems.Where(x => x.OrderID == orderID)
                from ps in LS.CurrentEntityContext.ProductShopMap.Where(x => x.ID == oi.ProductShopID &&
                                                                        x.ShopID == ShopID).DefaultIfEmpty()
                from p in LS.CurrentEntityContext.Products.Where(x => x.ID == ps.ProductID).DefaultIfEmpty()
                orderby p.CategoryID
                select oi).Distinct();
            var data = query.ToList();

            var productShopsIds = data.Select(x => x.ProductShopID).ToList();
            var productShops    = LS.CurrentEntityContext.ProductShopMap.Where(x => productShopsIds.Contains(x.ID)).ToList();

            var productIds = productShops.Select(x => x.ProductID).ToList();
            var products   = LS.CurrentEntityContext.Products.Where(x => productIds.Contains(x.ID)).ToList();

            foreach (var group in data)
            {
                var ps = productShops.FirstOrDefault(x => x.ID == group.ProductShopID);
                if (ps != null)
                {
                    group.ProductShop = ps;
                    var p = products.FirstOrDefault(x => x.ID == ps.ProductID);
                    if (p != null)
                    {
                        group.ProductShop.Product = p;
                        group.VirtualOrder        = p.CategoryID;
                        var cat = LS.Get <Category>().FirstOrDefault(x => x.ID == p.CategoryID);
                        if (cat != null)
                        {
                            group.ProductShop.Product.Category = cat;
                        }
                    }
                }
            }



            var result = data.OrderBy(x => x.VirtualOrder).Take(request.PageSize).Skip((request.Page - 1) * request.PageSize).ToList();//.Select(x => x.oi).ToList();

            return(Json(new { Data = result, Errors = (List <string>)null, AggregateResults = (List <string>)null, Total = query.Count() }));
        }
        public static OrderNote OnCreated(OrderNote item)
        {
            //send email to client
            var dbcontext      = new DBContextService();
            var messageService = new MessageService(dbcontext.EntityContext);
            var orderId        = item.OrderID;
            var order          = dbcontext.EntityContext.Orders.AsNoTracking().FirstOrDefault(x => x.ID == orderId);

            if (order != null)
            {
                var shop = LS.Get <Shop>().FirstOrDefault(x => x.ID == order.ShopID);
                messageService.SendNewOrderNoteEmailToUser(item, order, shop);
            }
            return(item);
        }
        public ActionResult _TopMenu(int shopID)
        {
            var category1 = LS.Get <Category>()
                            //.Where(x => x.ParentCategoryID == 0)
                            .ToList();

            var shopMenuCategory = LS.Get <ShopCategoryMenu>().Where(x => x.Published && x.ShopID == shopID).ToList();

            if (shopMenuCategory.Count > 0)
            {
                shopMenuCategory.ForEach((item) =>
                {
                    item.Category = category1.FirstOrDefault(x => x.ID == item.CategoryID);
                });
                ViewBag.ShopID = shopID;
                return(View("_TopMenuCustom", shopMenuCategory));
            }

            var shopCatMap = LS.Get <ShopCategory>().Where(x => x.Published);

            var category = (from c in category1
                            join sc in shopCatMap
                            on c.ID equals sc.CategoryID
                            where sc.ShopID == shopID &&
                            c.ParentCategoryID == 0
                            orderby sc.DisplayOrder
                            select c
                            ).Distinct().Take(11).ToList();

            var IDs     = category.Select(x => x.ID).ToList();
            var subcats =
                (from c in category1
                 join sc in shopCatMap
                 on c.ID equals sc.CategoryID
                 where sc.ShopID == shopID &&
                 IDs.Contains(c.ParentCategoryID)
                 orderby sc.DisplayOrder
                 select c
                ).ToList();

            // LS.Get<Category>().Where(x => IDs.Contains(x.ParentCategoryID)).OrderBy(x => x.DisplayOrder).ToList();
            category.AddRange(subcats);
            ViewBag.ShopID = shopID;

            return(View(category));
        }
        public ActionResult _AjaxIndex([DataSourceRequest] DataSourceRequest request)
        {
            IQueryable <SpecificationAttribute> items = _db.SpecificationAttributes.AsQueryable();
            DataSourceResult result = items.ToDataSourceResult(request);
            var specTypes           = LS.Get <SpecificationAttributeType>();

            foreach (var item  in (IEnumerable <SpecificationAttribute>)result.Data)
            {
                item.SpecificationAttributeType = specTypes
                                                  .FirstOrDefault(x => x.ID == item.SpecificationAttributeTypeID);
                if (item.SpecificationAttributeType == null)
                {
                    item.SpecificationAttributeType = new SpecificationAttributeType();
                }
            }
            return(Json(result));
        }
        public ActionResult CSVExport([DataSourceRequest] DataSourceRequest request)
        {
            var filtered = _db.ProductSkuMaps.AsQueryable().ToDataSourceResult(request);
            var shops    = LS.Get <Shop>();
            var products = LS.Get <ProductSmall>(
                "ProductSmall", false, () =>
            {
                return(_db.Products.AsNoTracking()
                       .Select(x => new ProductSmall()
                {
                    ID = x.ID,
                    Image = x.Image,
                    Name = x.Name,
                    SKU = x.SKU
                })
                       .ToList());
            },
                "Product"
                ).AsQueryable();
            var neededData = (filtered.Data as IEnumerable <ProductSkuMap>)
                             .Select(x => new
            {
                ProductName = products.Any(y => y.SKU == x.ProductSKU) ? products.FirstOrDefault(y => y.SKU == x.ProductSKU).Name : "",
                x.ImportProductName,
                x.Imported,

                x.ShortSKU,
                x.ProductSKU,
                x.Price,
                x.Quantity,
                x.ShopID,
                ShopName = shops.Any(y => y.ID == x.ShopID) ? shops.FirstOrDefault(y => y.ID == x.ShopID).Name : ""
            })

                             .ToList();

            byte[] bytes = null;
            bytes = CreateExcelFile.CreateExcelDocument(
                neededData, "ProductSkuMaps_" + DateTime.Now.ToString() + ".xlsx"
                , HttpContext.Response);

            return(File(bytes
                        , "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                        , "ProductSkuMaps_" + DateTime.Now.ToString() + ".xlsx"));
        }
Example #15
0
        public static List <Translation> GetTranslationsReprository()
        {
            return(LS.Get <Translation>());

            string LanguageCode = SF.GetLangCodeThreading();//RP.GetCurrentSettings().LanguageCode; //<- bug
            string Token        = "Translation_" + LanguageCode;

            if (LS.Cache[Token] == null)
            {
                List <Translation> l = new List <Translation>();
                l = _db.Translations.Where(r => r.LangCode == LanguageCode).ToList();

                LS.Cache[Token] = l;
                return(l);
            }
            else
            {
                return(LS.Cache[Token] as List <Translation>);
            }
        }
        public async Task <ActionResult> LandingSelectShop(int shopType, string address, string addressTyped, decimal latitude, decimal longitude)
        {
            var foundedshops = ShoppingService.GetNearestShop(shopType, latitude, longitude, address);
            var bestshop     = foundedshops.FirstOrDefault();

            Session["address"]   = address;
            Session["latitude"]  = latitude;
            Session["longitude"] = longitude;
            var    sht  = LS.Get <ShopType>();
            string type = sht.Where(x => x.ID == shopType).Select(x => x.Name).DefaultIfEmpty("").FirstOrDefault();

            var userActivity = new UserAddressSearchActivity();

            userActivity.Address       = address;
            userActivity.CreateOn      = DateTime.Now;
            userActivity.IP            = LS.GetUser_IP(Request);
            userActivity.RefererUrl    = Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null;
            userActivity.PageUrl       = Request.RawUrl;
            userActivity.Latitude      = latitude;
            userActivity.Longitude     = longitude;
            userActivity.UserID        = LS.CurrentUser.ID;
            userActivity.AddressWroten = addressTyped;
            userActivity.ShopType      = type;

            var _url = "/c/noshop";

            if (bestshop != null)
            {
                _url = string.IsNullOrEmpty(bestshop.SeoUrl) ? "/Shop/Index/" + bestshop.ID : "/" + bestshop.SeoUrl;
                userActivity.ShopID   = bestshop.ID;
                userActivity.ShopName = bestshop.Name;
                if (foundedshops.Count() > 1)
                {
                    Session["OpenedFromHomePage" + bestshop.ID.ToString()] = DateTime.UtcNow;
                }
            }
            _db.UserAddressSearchActivities.Add(userActivity);
            await _db.SaveChangesAsync();

            return(Content(_url));
        }
        private static List <TextComponent> GetTextComponentReprository()
        {
            return(LS.Get <TextComponent>());

            string LanguageCode = RP.GetCurrentSettings().LanguageCode;
            int    DomainID     = RP.GetCurrentSettings().ID;
            string Token        = "TextComponent_" + DomainID + "_" + LanguageCode;

            if (LS.Cache[Token] == null)
            {
                List <TextComponent> l = new List <TextComponent>();
                l = _db.TextComponents.Where(r => r.DomainID == DomainID && r.LangCode == LanguageCode).ToList();

                LS.Cache[Token] = l;
                return(l);
            }
            else
            {
                return(LS.Cache[Token] as List <TextComponent>);
            }
        }
Example #18
0
        public ActionResult Export()
        {
            byte[] bytes = null;

            //string LangCode = "en-US";
            using (var stream = new MemoryStream())
            {
                //  _exportManager.ExportProductsToXlsx(stream, products);
                StreamWriter sw   = new StreamWriter(stream, Encoding.UTF8);
                var          list = _db.Products.AsNoTracking().ToList();
                var          cats = LS.Get <Category>();

                var neededData = cats.Where(x => x.ParentCategoryID > 0).Select
                                 (
                    x => new
                {
                    Category = (cats.FirstOrDefault(y => y.ID == x.ParentCategoryID) != null
                      ? cats.FirstOrDefault(y => y.ID == x.ParentCategoryID).Name : ""),
                    SubCategory = x.Name,
                }
                                 ).ToList();
                neededData.AddRange(cats.Where(x => x.ParentCategoryID == 0).Select
                                    (
                                        x => new
                {
                    Category    = x.Name,
                    SubCategory = "",
                }
                                    ));

                bytes = CreateExcelFile.CreateExcelDocument(
                    neededData, "Category_" + DateTime.Now.ToString() + ".xlsx"
                    , HttpContext.Response);

                return(File(bytes
                            , "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                            , "Category_" + DateTime.Now.ToString() + ".xlsx"));
            }
        }
Example #19
0
        /// <summary>
        /// Returns information about the requested route.
        /// </summary>
        /// <param name="httpContext">An object that encapsulates information about the HTTP request.</param>
        /// <returns>
        /// An object that contains the values from the route definition.
        /// </returns>
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            RouteData data = base.GetRouteData(httpContext);

            if (data != null
                //  && DataSettingsHelper.DatabaseIsInstalled()
                )
            {
                // var urlRecordService = EngineContext.Current.Resolve<IUrlRecordService>();
                var slug      = data.Values["generic_se_name"] as string;
                var urlRecord = LS.Get <UrlRecord>().FirstOrDefault(x => x.Slug.ToLower() == slug.ToLower());
                if (urlRecord != null)
                {
                    data.Values["controller"] = urlRecord.EntityName;
                    data.Values["action"]     = "Index";
                    data.Values["ID"]         = urlRecord.EntityID;
                    data.Values["SeName"]     = urlRecord.Slug;
                }
                //performance optimization.
                //we load a cached verion here. it reduces number of SQL requests for each page load
                //  var urlRecord = urlRecordService.GetBySlugCached(slug);
                //comment the line above and uncomment the line below in order to disable this performance "workaround"
                //var urlRecord = urlRecordService.GetBySlug(slug);


                //  data.Values["controller"] = "Common";
                //   data.Values["action"] = "PageNotFound";
                // return data;

                // data.Values["controller"] = "Product";
                //  data.Values["action"] = "ProductDetails";
                //  data.Values["productid"] = urlRecord.EntityId;
                //  data.Values["SeName"] = urlRecord.Slug;
            }
            return(data);
        }
        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 ActionResult _GetProductsForEndlessScrolling([DataSourceRequest] DataSourceRequest request,
                                                            int shopID, int?categoryID, int[] filtersArray = null, bool isBestSelling = false, string productName = "", bool refreshFilters = false,
                                                            bool favorite = false, bool allOrderedProducts = false, bool deals = false, string keywords = null)
        {
            bool firstBatch = request.Page == 1 ? true : false;

            if (request.PageSize == 0)
            {
                request.PageSize = 20;
            }
            var page = request.Page;
            List <SpecificationOptionModel> specifications = null;
            string tempString = null;
            List <ProductOverviewModel> list = new List <ProductOverviewModel>();

            if (favorite || allOrderedProducts || deals)
            {
                if (favorite)
                {
                    list.AddRange(LS.SearchProducts(shopID, out specifications, request.Page, request.PageSize, favorite: true, loadSpecifications: firstBatch, showDiscounts: true));
                }
                if (allOrderedProducts)
                {
                    list.AddRange(LS.SearchProducts(shopID, out specifications, request.Page, request.PageSize, allOrderedProducts: true, loadSpecifications: firstBatch, showDiscounts: true));
                }
                if (deals)
                {
                    //list.AddRange(LS.SearchProducts(shopID, out specifications, limit: int.MaxValue, discountedProducts: true, showDiscounts: true));
                    list.AddRange(LS.SearchProducts(shopID, out specifications, request.Page, request.PageSize, discountedProducts: true, showDiscounts: true));
                }
            }
            else
            {
                if (string.IsNullOrEmpty(productName))
                {
                    bool FeautureTop = false;
                    if (!categoryID.HasValue &&
                        (filtersArray == null || filtersArray.Length == 0) &&
                        string.IsNullOrEmpty(keywords) &&
                        !isBestSelling
                        )
                    {
                        var sc = LS.Get <ShopCategoryMenu>().FirstOrDefault(x => x.ShopID == shopID && x.Published == true && x.Level == 0);


                        if (sc != null)
                        {
                            categoryID = sc.CategoryID;
                        }
                    }
                    list = LS.SearchProducts(shopID, out specifications, request.Page, request.PageSize, categoryID: categoryID, filters: filtersArray, loadSpecifications: firstBatch,
                                             favorite: favorite, allOrderedProducts: allOrderedProducts, featuredTop: FeautureTop, showDiscounts: true, keywords: keywords).ToList();
                }
                else
                {
                    list = LS.GetProductByName(shopID, productName).Skip(--page * request.PageSize).Take(request.PageSize).ToList(); //search by single name
                }
            }

            int total = request.PageSize * request.Page + 1;

            if (list.Count() < request.PageSize)
            {
                total = request.PageSize * (request.Page - 1) + list.Count();
            }
            var viewList = new List <JsonKeyValue>();

            foreach (var item in list)
            {
                viewList.Add(new JsonKeyValue()
                {
                    Name  = item.ProductShopID.ToString(),
                    Value = RenderPartialViewToString("_ProductGalleryItem", item),
                });
            }
            return(Json(new
            {
                Data = viewList,
                Total = total,
                Errors = tempString,
                AggregateResults = tempString,
            }));
        }
 public void Execute()
 {
     if (!isRunned)
     {
         var needReturn = false;
         lock (_lock)
         {
             if (isRunned)
             {
                 needReturn = true;
             }
             else
             {
                 isRunned = true;
             }
         }
         if (needReturn)
         {
             return;
         }
         try
         {
             using (Db _db = new Db())
             {
                 var lastProductID = _db.ShopSettings.FirstOrDefault(x => x.Key == LASTIDKEY);
                 int lastID        = 0;
                 if (lastProductID != null)
                 {
                     int.TryParse(lastProductID.Value, out lastID);
                     lastProductID.Value = (lastID + porsionLimit).ToString();
                     _db.SaveChanges();
                 }
                 else
                 {
                     lastProductID = new ShopSetting()
                     {
                         Key = LASTIDKEY, Value = (lastID + porsionLimit).ToString()
                     };
                     _db.ShopSettings.Add(lastProductID);
                     _db.SaveChanges();
                 }
                 int pictureSize = LS.Get <Settings>().FirstOrDefault().ProductBoxImageSize;
                 if (pictureSize == 0)
                 {
                     pictureSize = 174;
                 }
                 var products = _db.Products.Where(x => x.HasImage && x.ID > lastID)
                                .Select(x => new
                 {
                     x.ID,
                     x.Image
                 }).Take(porsionLimit).ToList();
                 if (products.Count == 0)
                 {
                     //reset position
                     lastProductID.Value = 0.ToString();
                     _db.SaveChanges();
                 }
                 foreach (var p in products)
                 {
                     try
                     {
                         SF.GetImage(p.Image, pictureSize, pictureSize, true, true);
                     }
                     catch { }
                 }
             }
         }
         finally
         {
             isRunned = false;
         }
     }
 }
        public ActionResult _GetProductByCategoryAndFilters(int shopID, int?categoryID, int[] filters, string viewIn = "gallery", int skip = 0, int take = 20,
                                                            string keywords        = null,
                                                            bool showFirstCategory = false,
                                                            bool isBestSelling     = false, string productName = "", bool refreshFilters = true, bool isForSpider = false)
        {
            List <SpecificationOptionModel>    specifications = null;
            IEnumerable <ProductOverviewModel> data;
            var profiler = MiniProfiler.Current;

            using (profiler.Step("Step Controller _ByCategoryAndFilters"))
            {
                if (string.IsNullOrEmpty(productName))
                {
                    if (showFirstCategory)
                    {
                        //var sc = LS.Get<ShopCategory>().OrderBy(x => x.DisplayOrder).Where(x => x.Published).FirstOrDefault();
                        //var category1 = LS.Get<Category>().ToList();

                        var sc = LS.Get <ShopCategoryMenu>().FirstOrDefault(x => x.ShopID == shopID && x.Published == true && x.Level == 0);


                        if (sc != null)
                        {
                            categoryID = sc.CategoryID;
                        }
                        else
                        {
                            var shopCatMap = LS.Get <ShopCategory>().Where(x => x.Published);

                            var shc = shopCatMap.OrderBy(x => x.DisplayOrder).FirstOrDefault();
                            if (shc != null)
                            {
                                categoryID = shc.CategoryID;
                            }
                        }
                    }
                    bool FeautureTop = false;
                    if (!categoryID.HasValue &&
                        (filters == null || filters.Length == 0) &&
                        string.IsNullOrEmpty(keywords) &&
                        !isBestSelling
                        )
                    {
                        FeautureTop = true;
                    }
                    data = LS.SearchProducts(
                        shopID: shopID,
                        options: out specifications,
                        page: isForSpider ? 1 : (skip / take) + 1,
                        limit: isForSpider ? -1 : take,
                        categoryID: categoryID,
                        filters: filters,
                        loadSpecifications: skip == 0,
                        keywords: keywords,
                        isBestSelling: isBestSelling,
                        featuredTop: FeautureTop,
                        showDiscounts: true);

                    foreach (var d in data)
                    {
                        //d.ProductNoteText = ShoppingService.GetUserNoteForProduct(d.ProductID, LS.CurrentUser.ID);
                    }
                }
                else
                {
                    data = LS.SearchProducts(shopID, out specifications, (skip / take) + 1, take
                                             // , categoryID: categoryID
                                             // , filters: filters
                                             //, loadSpecifications: skip == 0,
                                             , productName: productName
                                             //, isBestSelling: isBestSelling
                                             // , featuredTop: FeautureTop
                                             , showDiscounts: true
                                             );
                }


                ViewBag.LastProductNum = skip + take; //data.Count();
                ViewBag.Specifications = specifications;
                ViewBag.RefreshFilters = refreshFilters;
                ViewBag.CategoryID     = categoryID;
                if (categoryID.HasValue)
                {
                    var cat = LS.Get <Category>().FirstOrDefault(x => x.ID == categoryID.Value);
                    if (cat != null)
                    {
                        ViewBag.Category = cat;
                    }
                }
                if (!string.IsNullOrEmpty(productName) && data.Count() == 0 || !string.IsNullOrEmpty(keywords) && data.Count() == 0)
                {
                    return(Json(new
                    {
                        status = "productNotFound",
                        localizationMessage = RP.T("ShopController.SearchMessage.ProductNotFound").ToString(),
                        localizationTextComponent = RP.Text("ShopController.SearchMessage.ProductNotFoundComponent").ToString()
                    }, JsonRequestBehavior.AllowGet));
                }
            }

            if (data.Count() == 0)
            {
                return(Content(string.Empty));
            }
            var shop = LS.Get <Shop>().FirstOrDefault(x => x.ID == shopID);

            if (shop != null)
            {
                if (!string.IsNullOrEmpty(shop.Theme))
                {
                    this.HttpContext.Items["ShopTheme"] = shop.Theme;
                }
                ViewBag.Shop = shop;
            }
            switch (viewIn)
            {
            case "gallery":
                return(PartialView("_ProductsGallery", data));

            case "table":
                return(PartialView("_ProductsTable", data));

            case "tableItemPartial":
                return(PartialView("_ProductTableItem", data));
            }
            return(Content(string.Empty));
        }
 public static List <ContentUnitMeasureMap> GetContentUnitMeasureMaps()
 {
     return(LS.Get <ContentUnitMeasureMap>());
 }
        public ActionResult Index(int ID = 0, string _escaped_fragment_ = null)
        {
            if (ID == 0)
            {
                if (LS.CurrentHttpContext.Session["ShopID"] != null)
                {
                    ID = (int)LS.CurrentHttpContext.Session["ShopID"];

                    if (ID > 0)
                    {
                        return(RedirectToAction("Index", new { ID = ID }));
                    }
                }
            }

            Shop shop = LS.Get <Shop>().FirstOrDefault(r => r.ID == ID);

            if (shop == null || !shop.Active)
            {
                return(Redirect("~/"));
            }
            ViewBag.Shop = shop;
            if (Request.Url.AbsolutePath.ToLower().Contains("shop/index/") && shop.SeoUrl != null)
            {
                return(Redirect("/" + shop.SeoUrl));
            }
            UserActivityService.InsertShopOpen(LS.CurrentUser.ID, ID
                                               , Request.RawUrl,
                                               Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                               , LS.GetUser_IP(Request));
            LS.CurrentHttpContext.Session["ShopID"] = shop.ID;

            if (!string.IsNullOrEmpty(_escaped_fragment_))
            {
                EscapedFragmentDescriptor descriptor = null;
                try
                {
                    descriptor = new EscapedFragmentDescriptor(_escaped_fragment_);
                }
                catch (IndexOutOfRangeException)
                {
                    return(HttpNotFound());
                }

                switch (descriptor.Target)
                {
                case EscapedFragmentDescriptor.Targets.Category:
                {
                    ViewBag.UseLayout = true;
                    return(_GetProductByCategoryAndFilters(descriptor.ShopID, descriptor.CategoryID, null, isForSpider: true));
                }

                case EscapedFragmentDescriptor.Targets.Product:
                {
                    ViewBag.UseLayout = true;
                    return(_GetProductPopup(descriptor.ShopID));
                }
                }
            }
            if (!string.IsNullOrEmpty(shop.Theme))
            {
                this.HttpContext.Items["ShopTheme"] = shop.Theme;
            }
            shop.ShopMessages = new List <ShopMessage>();
            if (Request.Cookies["_slkmess" + shop.ID.ToString()] == null)
            {
                //get messages
                var curDate = DateTime.Now;
                var mess    = LS.Get <ShopMessage>().Where(x => x.ShopID == shop.ID &&
                                                           x.Active &&
                                                           (!x.StartDate.HasValue || x.StartDate.Value < curDate) &&
                                                           (!x.EndDate.HasValue || x.EndDate.Value > curDate)).OrderByDescending(x => x.StartDate).FirstOrDefault();
                if (mess != null)
                {
                    shop.ShopMessages.Add(mess);
                }
            }

            return(View(shop));
        }
        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
                }
            }
        }
Example #27
0
        public ActionResult Import(HttpPostedFileBase attachment)
        {
            if (attachment == null)
            {
                // TempData["MessageRed"] = "File Error";
                return(Json(new { success = "error", message = "File Error" }));
            }

            string FolderPath = Server.MapPath("~/App_Data/Temp/");
            //1
            string FileName = "";
            string FilePath = "";

            FileName = Path.GetFileName(attachment.FileName);
            FilePath = Path.Combine(FolderPath, FileName);
            attachment.SaveAs(FilePath);
            if (!FileName.EndsWith(".xls") && !FileName.EndsWith(".xlsx") && !FileName.EndsWith(".csv"))
            {
                return(Json(new { success = "error", message = "File must have extension : xls, xlsx, csv" }));
            }

            var existingFile = new FileInfo(FilePath);
            var all          = new List <Dictionary <int, string> >();

            // Open and read the XlSX file.
            using (var package = new ExcelPackage(existingFile))
            {
                // Get the work book in the file
                ExcelWorkbook workBook = package.Workbook;
                if (workBook != null)
                {
                    if (workBook.Worksheets.Count > 0)
                    {
                        // Get the first worksheet
                        ExcelWorksheet currentWorksheet = workBook.Worksheets.First();

                        var begin = currentWorksheet.Dimension.Start;
                        var end   = currentWorksheet.Dimension.End;
                        for (var i = begin.Row + 1; i <= end.Row; i++)
                        {
                            // read some data
                            Dictionary <int, string> row = new Dictionary <int, string>();
                            for (var c = begin.Column; c <= end.Column; c++)
                            {
                                var val = currentWorksheet.Cells[i, c].Value;
                                row[c - 1] = val != null?val.ToString() : "";
                            }
                            all.Add(row);
                        }
                    }
                }
            }

            var             AllCategories   = LS.Get <Category>(); //get category cache
            List <Category> treeLevelParent = new List <Category>();

            foreach (var s in all)
            {
                if (s.Count != 2)
                {
                    continue;
                }
                if (s[0] != null && !string.IsNullOrEmpty(s[0].ToString()))
                {
                    var categoryParent = new Category();
                    categoryParent.DisplayOrder     = 500;
                    categoryParent.Name             = s[0].ToString().Trim();
                    categoryParent.Published        = true;
                    categoryParent.ParentCategoryID = 0;
                    treeLevelParent.Add(categoryParent);
                }
            }
            foreach (var c in treeLevelParent)
            {
                if (!AllCategories.Any(x => x.Name == c.Name))
                {
                    _db.Categories.Add(c);
                    AllCategories.Add(c);
                }
            }
            _db.SaveChanges(); //save parent categories
            List <Category> treeLevelChild = new List <Category>();

            AllCategories = LS.Get <Category>();
            foreach (var s in all)
            {
                if (s[1] != null && !string.IsNullOrEmpty(s[1].ToString()))
                {
                    var category = new Category();
                    category.DisplayOrder     = 1000;
                    category.Name             = s[1].ToString().Trim();
                    category.Published        = true;
                    category.ParentCategoryID = 0;
                    if (s[0] != null && !string.IsNullOrEmpty(s[0].ToString()))
                    {
                        var parentName = s[0].ToString().Trim();
                        var parentCat  = AllCategories.FirstOrDefault(x => x.Name == parentName);
                        if (parentCat != null)
                        {
                            category.ParentCategoryID = parentCat.ID;
                        }
                    }
                    //  category.ParentCategory = categoryParent; //save parent for ID
                    treeLevelChild.Add(category);
                }
            }
            foreach (var c in treeLevelChild)
            {
                if (!AllCategories.Any(x => x.Name == c.Name))
                {
                    _db.Categories.Add(c);
                    AllCategories.Add(c);
                }
            }
            _db.SaveChanges(); //save categories
            return(Json(new { success = "ok", message = "Import Success" }));
            //TempData["MessageGreen"] = "Import Success";
            // return Content("");
        }
        public static IEnumerable <Shop> GetNearestShop(int shopType, decimal latitude, decimal longitude
                                                        , string address, bool ignoreDistance = false)
        {
            var allShops    = LS.Get <Shop>();
            var cacheSource = allShops.Where(x => x.ShopTypeIDs != null &&
                                             (x.IsShipEnabled || x.InStorePickUpEnabled) &&
                                             x.Active
                                             );
            var allAdditionalZones = LS.Get <ShopDeliveryZone>();

            if (shopType > 0)
            {
                cacheSource = cacheSource.Where(x => x.ShopTypeIDs.Contains("," + shopType.ToString() + ",") ||
                                                x.ShopTypeIDs == shopType.ToString() ||
                                                x.ShopTypeIDs.StartsWith(shopType.ToString() + ",") ||
                                                x.ShopTypeIDs.EndsWith("," + shopType.ToString())
                                                );
            }

            var source = cacheSource.Select(x => new DistanceSearchItem()
            {
                ID             = x.ID,
                RadiusLatitude = x.RadiusLatitude
                ,
                RadiusLongitude = x.RadiusLongitude
                ,
                ShipRadius = x.ShipRadius
                ,
                ShipCost     = x.ShipCost,
                Rate         = x.Rate,
                DisplayOrder = x.DisplayOrder
            }).ToList();

            source.AddRange(
                (from az in allAdditionalZones
                 join s in allShops
                 on az.ShopID equals s.ID
                 where az.Active && az.ShopID > 0
                 select new DistanceSearchItem()
            {
                ID = s.ID,
                RadiusLatitude = az.RadiusLatitude
                ,
                RadiusLongitude = az.RadiusLongitude
                ,
                ShipRadius = az.ShipRadius
                ,
                ShipCost = az.ShipCost,
                Rate = s.Rate,
                DisplayOrder = s.DisplayOrder,
                IsWholeCity = az.DeliveryFroAllCity,
                City = az.City
            }
                )
                );
            List <IntDoublePair> distances = new List <IntDoublePair>();
            double maxRate   = 0.1;
            double maxShip   = 0.1;
            int    maxOrders = 0;
            // 1) Display Order
            var lowerCaseAddress = address != null?address.ToLower() : "";

            foreach (var s in source)
            {
                if (s.IsWholeCity)
                {
                    //check the city in address
                    if (!string.IsNullOrEmpty(s.City) &&
                        (
                            lowerCaseAddress.Contains(", " + s.City.ToLower() + ", ") ||
                            lowerCaseAddress.StartsWith(s.City.ToLower() + ", ")
                            // || lowerCaseAddress.EndsWith(", " + s.City.ToLower())
                            // || lowerCaseAddress.StartsWith(s.City.ToLower() + " ")
                            || lowerCaseAddress.EndsWith(", " + s.City.ToLower())
                        )
                        )
                    {
                        //city founded
                        distances.Add(new IntDoublePair()
                        {
                            Int = s.ID, Double = 1
                        });
                    }
                    else if (ignoreDistance)
                    {
                        //not this city
                        distances.Add(new IntDoublePair()
                        {
                            Int = s.ID, Double = 10000
                        });
                    }
                }
                else if (!ignoreDistance)
                {
                    var clientradius = distance((double)s.RadiusLatitude, (double)s.RadiusLongitude, (double)latitude, (double)longitude, 'K');
                    if (clientradius <= (double)s.ShipRadius)
                    {
                        distances.Add(new IntDoublePair()
                        {
                            Int = s.ID, Double = clientradius
                        });
                    }
                }
                else
                {
                    distances.Add(new IntDoublePair()
                    {
                        Int = s.ID, Double = 10000
                    });
                }
                if ((double)s.Rate > maxRate)
                {
                    maxRate = (double)s.Rate;
                }
                if ((double)s.ShipCost > maxShip)
                {
                    maxShip = (double)s.ShipCost;
                }
                int ShopID = s.ID;

                int ordersToday = LS.GetCachedFunc <int>(() =>
                {
                    var curDateOnly = DateTime.Now.Date;
                    var count       = LS.CurrentEntityContext.Orders.Count(x => x.ShopID == ShopID && x.CreateOn >= curDateOnly);
                    return(count);
                }, "shopOrdersToday_" + ShopID.ToString(), 10); //cache 10 min
                if (ordersToday > maxOrders)
                {
                    maxOrders = ordersToday;
                }
            }
            double max = 1;

            if (distances.Count > 0)
            {
                max = distances.Select(x => x.Double).Max();
            }
            if (max == 0)
            {
                max = 1;//prevent zero division
            }
            var curdate     = DateTime.Now.Date;
            var curdateTime = DateTime.Now;
            var lastdate    = curdate.AddDays(7);

            foreach (var s in source)
            {
                var groupDistances = distances.Where(x => x.Int == s.ID).ToList();
                if (groupDistances.Count > 0)
                {
                    groupDistances.ForEach((e) =>
                    {
                        e.Double = s.DisplayOrder                                 // 70 %
                                   + (max - e.Double) * 10 / max                  // 10 %
                                   + (maxShip - (double)s.ShipCost) * 5 / maxShip //
                                   + (double)s.Rate * 10 / maxRate
                        ;
                        int ShopID = s.ID;
                        if (maxOrders > 0)
                        {
                            int ordersToday = LS.GetCachedFunc <int>(() =>
                            {
                                var curDateOnly = DateTime.Now.Date;
                                var count       = LS.CurrentEntityContext.Orders.Count(x => x.ShopID == ShopID && x.CreateOn >= curDateOnly);
                                return(count);
                            }, "shopOrdersToday_" + ShopID.ToString(), 10); //cache 10 min
                            e.Double += ordersToday * 5 / maxOrders;
                        }
                        //check shop closed
                        var WorkTimes =
                            LS.GetCachedFunc <List <ShopWorkTime> >(() =>
                        {
                            return(LS.CurrentEntityContext.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)
                                   .ToList());
                        }, "shopWorkTime_" + ShopID.ToString(), 60);

                        var time = WorkTimes.FirstOrDefault(
                            x => (x.IsSpecial && x.Date.Date == curdate)
                            ||
                            (!x.IsSpecial && x.Day == curdate.DayOfWeek)

                            );
                        bool validTime = false;
                        if (time != null)
                        {
                            int curIntTime = curdateTime.Hour * 60 + curdateTime.Minute;
                            if (time.TimeFrom <= curIntTime && curIntTime <= time.TimeTo)
                            {
                                validTime = true;
                            }
                        }
                        if (!validTime)
                        {
                            e.Double -= 30;
                        }
                        //end shop closed check
                    });
                }
            }



            var shopIds = (from s in allShops
                           join d in distances
                           on s.ID equals d.Int
                           orderby d.Double descending
                           select s
                           );

            return(shopIds);
        }
 public static IList <ShopType> GetShopTypes()
 {
     return(LS.Get <ShopType>());
 }
        //public static int GetOrderItemStatus(string name)
        //{
        //   // var status = LS.Get<OrderItemStatus>().FirstOrDefault(x => x.Name == name);
        //   // if (status != null) return status.ID;
        //    return 0;
        //}


        //public static int NewItemStatus()
        //{
        //    return GetOrderItemStatus("New");
        //}
        //public static int AcceptedItemStatus()
        //{
        //    return GetOrderItemStatus("Accepted");
        //}
        //public static int OutOfStockItemStatus()
        //{
        //    return GetOrderItemStatus("Out of stock");
        //}
        //public static int ApprovedItemStatus()
        //{
        //    return GetOrderItemStatus("Approved by customer");
        //}
        //public static int ChangedItemStatus()
        //{
        //    return GetOrderItemStatus("Changed");
        //}
        //public static int CanceledItemStatus()
        //{
        //    return GetOrderItemStatus("Canceled by customer");
        //}

        #endregion
        public static Shop GetShopByID(int ID)
        {
            return(LS.Get <Shop>().FirstOrDefault(x => x.ID == ID));
        }