public static void AddProductToFavorite(int ProductShopID, Guid UserID = new Guid())
        {
            if (UserID == Guid.Empty && LS.isHaveID())
            {
                UserID = LS.CurrentUser.ID;
            }
            if (UserID == Guid.Empty)
            {
                return;
            }
            var fav = LS.CurrentEntityContext.ProductFavorites.FirstOrDefault(x => x.ProductShopID == ProductShopID &&
                                                                              x.UserID == UserID);

            if (fav == null)
            {
                UserActivityService.InsertFavoriteProduct(UserID, ProductShopID, false
                                                          , HttpContext.Current.Request.RawUrl,
                                                          HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.OriginalString : null
                                                          , LS.GetUser_IP(HttpContext.Current.Request));

                fav = new ProductFavorite()
                {
                    CreateDate    = DateTime.Now,
                    ProductShopID = ProductShopID,
                    UserID        = UserID
                };
                LS.CurrentEntityContext.ProductFavorites.Add(fav);
                LS.CurrentEntityContext.SaveChanges();
            }
        }
Beispiel #2
0
 public ActionResult Password()
 {
     UserActivityService.InsertUserClick(LS.CurrentUser.ID,
                                         Request.RawUrl,
                                         Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                         , LS.GetUser_IP(Request));
     return(View());
 }
        public ActionResult _GetShopInfo(int shopID)
        {
            var culture = new System.Globalization.CultureInfo("he-IL");
            var data    = LS.GetFirst <Shop>(x => x.ID == shopID);

            UserActivityService.InsertShopOpen(LS.CurrentUser.ID, shopID
                                               , Request.RawUrl,
                                               Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                               , LS.GetUser_IP(Request));
            data.ShopCommentModels = ShoppingService.GetShopComments(shopID);
            //data.ShopType = LS.Get<ShopType>()
            //    .FirstOrDefault(x => data.ShopTypeIDs!= null && data.ShopTypeIDs.Contains(x.ID.ToString() ) );

            var curdate  = DateTime.Now.Date;
            var lastdate = curdate.AddDays(7);

            data.WorkTimes = 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)
                             .Select(x => new ShipTimeModel()
            {
                Date        = x.Date,
                Day         = x.Day,
                TimeFromInt = x.TimeFrom,
                TimeToInt   = x.TimeTo,
                IsSpecial   = x.IsSpecial,
            }).ToList();

            foreach (var t in data.WorkTimes)
            {
                t.DayStr       = culture.DateTimeFormat.GetDayName(t.Day);
                t.TimeFromeStr = TimeSpan.FromMinutes(t.TimeFromInt).ToString("hh':'mm"); //ntToTime(t.TimeFromInt);
                t.TimeToStr    = TimeSpan.FromMinutes(t.TimeToInt).ToString("hh':'mm");
                t.DateStr      = t.Date.ToString("dd/MM");
            }

            data.ShipTimes = _db.ShopShipTimes.Where(x => x.ShopID == shopID && x.Active && !x.IsSpecial)
                             .Select(x => new ShipTimeModel()
            {
                Date        = x.Date,
                Day         = x.Day,
                TimeFromInt = x.TimeFrom,
                TimeToInt   = x.TimeTo,
            }).ToList();
            foreach (var t in data.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");
            }

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

            return(PartialView("_ShopInfoPopup", data));
        }
Beispiel #4
0
        public ActionResult DiscountHistory()
        {
            UserActivityService.InsertUserClick(LS.CurrentUser.ID,
                                                Request.RawUrl,
                                                Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                                , LS.GetUser_IP(Request));
            if (!LS.isHaveID())
            {
                return(Redirect("~/"));
            }
            var model = LS.CurrentUser;

            return(View(model));
        }
Beispiel #5
0
        public ActionResult Index()
        {
            UserActivityService.InsertUserClick(LS.CurrentUser.ID,
                                                Request.RawUrl,
                                                Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                                , LS.GetUser_IP(Request));

            if (!LS.isHaveID())
            {
                return(Redirect("~/Account/LogOn"));
            }
            var model = LS.CurrentUser;

            return(View("Orders", model));
        }
        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));
        }
        public ActionResult _AddContactData(int shopID, Contact model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    UserActivityService.InsertShopContact(LS.CurrentUser.ID, shopID
                                                          , model.ContactData,
                                                          model.ContactEmail,
                                                          model.ContactName
                                                          , model.ContactPhone
                                                          , model.DropDownItems

                                                          , Request.RawUrl,
                                                          Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                                          , LS.GetUser_IP(Request)
                                                          );


                    model.ContactData = RP.T("Views.Shared.Contact.DropDownChooseText").ToString().ToLower() + ": " + model.ContactData;
                    if (model.DropDownItems.Count > 0)
                    {
                        model.ContactData = model.ContactData + "<br />" +
                                            RP.T("Views.Shared.Contact.TextAreaPlaceholder").ToString().ToLower() + ": " + model.DropDownItems.FirstOrDefault();
                    }
                    model.ContactDate    = DateTime.Now;
                    model.ContactReferal = SF.GetCookie("Referal");
                    model.ContactUrl     = "<a target='_blank' href='" + Request.UrlReferrer.ToString() + "'>" + Request.UrlReferrer.ToString() + "</a>";
                    model.RoleDefault    = "Member";
                    ShoppingService.AddContact(model);

                    return(Redirect("/c/contact-sent"));
                }
                catch (Exception exc)
                {
                    SF.LogError(exc);
                }
            }
            TempData["ViewData"] = ViewData;
            return(RedirectToAction("Contact", new { ID = shopID }));
        }
Beispiel #8
0
        public ActionResult Address()
        {
            UserActivityService.InsertUserClick(LS.CurrentUser.ID,
                                                Request.RawUrl,
                                                Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                                , LS.GetUser_IP(Request));
            if (!LS.isHaveID())
            {
                return(Redirect("~/"));
            }
            var model = LS.CurrentUser;

            if (string.IsNullOrEmpty(model.AddressMap))
            {
                var checkoutData = GetCheckoutData();
                if (checkoutData.Address != null)
                {
                    model.AddressMap = checkoutData.Address;
                }
            }
            return(View(model));
        }
Beispiel #9
0
        public ActionResult OrderDetail(int ID)
        {
            UserActivityService.InsertUserClick(LS.CurrentUser.ID,
                                                Request.RawUrl,
                                                Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                                , LS.GetUser_IP(Request));
            if (!LS.isHaveID())
            {
                return(Redirect("~/"));
            }
            var order = _db.Orders.FirstOrDefault(x => x.ID == ID && x.UserID == LS.CurrentUser.ID);

            if (order == null)
            {
                TempData["MessageRed"] = "Order doesn`t exists";
                return(RedirectToAction("Index"));
            }
            order.User = LS.CurrentUser;
            // order.OrderStatus = _db.OrderStatuses.FirstOrDefault(x => x.ID == order.OrderStatusID);

            return(View(order));
        }
        public static void RemoveProductFromFavorite(int ProductShopID, Guid UserID = new Guid())
        {
            if (UserID == Guid.Empty && LS.isHaveID())
            {
                UserID = LS.CurrentUser.ID;
            }
            if (UserID == Guid.Empty)
            {
                return;
            }
            var fav = LS.CurrentEntityContext.ProductFavorites.FirstOrDefault(x => x.ProductShopID == ProductShopID &&
                                                                              x.UserID == UserID);

            if (fav != null)
            {
                UserActivityService.InsertFavoriteProduct(UserID, ProductShopID, true
                                                          , HttpContext.Current.Request.RawUrl,
                                                          HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.OriginalString : null
                                                          , LS.GetUser_IP(HttpContext.Current.Request));

                LS.CurrentEntityContext.ProductFavorites.Remove(fav);
                LS.CurrentEntityContext.SaveChanges();
            }
        }
Beispiel #11
0
        public ActionResult Settings()
        {
            UserActivityService.InsertUserClick(LS.CurrentUser.ID,
                                                Request.RawUrl,
                                                Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                                , LS.GetUser_IP(Request));
            if (!LS.isLogined())
            {
                return(Redirect("~/"));
            }
            if (TempData["ViewData"] != null)
            {
                ViewData = (ViewDataDictionary)TempData["ViewData"];
            }
            var model = new UserModel();

            model.CompanyName = LS.CurrentUser.CompanyName;
            model.Email       = LS.CurrentUser.Email;
            model.FirstName   = LS.CurrentUser.FirstName;
            model.LastName    = LS.CurrentUser.LastName;
            model.Phone       = LS.CurrentUser.Phone;
            model.NewsLetter  = _db.Newsletters.Any(x => x.NewsletterEmail == model.Email);
            return(View(model));
        }
        public ActionResult _GetProductPopup(int productShopID)
        {
            List <SpecificationOptionModel> specifications = null;
            var productInfo = GetProductByID(productShopID);

            UserActivityService.InsertProductOpen(LS.CurrentUser.ID, productShopID, productInfo.ProductID
                                                  , Request.RawUrl,
                                                  Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null
                                                  , LS.GetUser_IP(Request));


            productInfo.ProductComments = ShoppingService.GetProductComments(productInfo.ProductID).ToList();

            // productInfo.RelatedProducts = LS.SearchProducts(productInfo.ShopID, out specifications, limit: 4).ToList();


            var cart = LS.CurrentEntityContext.ShoppingCartItems.Where(x => x.ShopID == productInfo.ShopID &&
                                                                       x.UserID == LS.CurrentUser.ID)
                       .ToList();

            var curCartItem = cart.FirstOrDefault(x => x.ProductShopID == productInfo.ProductShopID);

            if (curCartItem != null)
            {
                productInfo.isInShoppingCart = true;
                productInfo.QuantityToBuy    = curCartItem.Quantity;
                productInfo.QuantityType     = curCartItem.QuantityType;
            }

            //save last seen Product
            // if (LS.isLogined())
            //   {
            //      ShoppingService.AddLastSeenProduct(productShopID);
            //  }
            return(PartialView("_ProductPopup", productInfo));
        }
        public static List <ProductShortModel> GetProductAutocomplete(int ShopID, string text)
        {
            var result = new List <ProductShortModel>();

            var sett = RP.GetCurrentSettings();

            if (sett != null && sett.AutocompleteOptions != null)
            {
                result.AddRange(
                    sett.AutocompleteOptions.Split(new char[] { '\n' }).Where(x => x.ToLower().Contains(text.ToLower())).Select(x => new ProductShortModel()
                {
                    Name = x,
                    ID   = 0
                })
                    );
            }

            #region Improving Search
            // "ת","ה","ות" - woman variants


            var source = LS.CurrentEntityContext.Products.AsNoTracking().AsQueryable();


            List <List <string> > searchAndOrList = new List <List <string> >();
            var words      = text.Split(new char[] { ' ', ',', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            var countWords = words.Count;
            for (var i = 0; i < countWords; i++)
            {
                var listor = new List <string>();
                listor.Add(words[i]);
                searchAndOrList.Add(listor);
            }

            for (var i = 0; i < countWords; i++)
            {
                var word = words[i];
                //1)
                #region woman
                if (word.EndsWith("ת"))
                {
                    var variant1 = word.Remove(word.Length - 1, 1) + "ה";
                    var variant2 = word.Remove(word.Length - 1, 1) + "ות";
                    searchAndOrList[i].Add(variant1);
                    searchAndOrList[i].Add(variant2);
                    continue;
                }
                else if (word.EndsWith("ה"))
                {
                    var variant1 = word.Remove(word.Length - 1, 1) + "ת";
                    var variant2 = word.Remove(word.Length - 1, 1) + "ות";
                    searchAndOrList[i].Add(variant1);
                    searchAndOrList[i].Add(variant2);
                    continue;
                }
                else if (word.EndsWith("ות"))
                {
                    var variant1 = word.Remove(word.Length - 1, 1) + "ה";
                    var variant2 = word.Remove(word.Length - 2, 2) + "ת";
                    searchAndOrList[i].Add(variant1);
                    searchAndOrList[i].Add(variant2);
                    continue;
                }
                #endregion

                #region man couple
                // "ים"
                if (word.EndsWith("ים"))
                {
                    var variant1 = word.Remove(word.Length - 2, 2);
                    //replace
                    //"פ" - "ף"
                    //"נ" - "ן"
                    //"מ" - "ם"
                    // "כ" - "ך"
                    // "צ" - "ץ"
                    if (variant1.EndsWith("פ"))
                    {
                        variant1 = variant1.Remove(variant1.Length - 1, 1) + "ף";
                    }
                    else if (variant1.EndsWith("נ"))
                    {
                        variant1 = variant1.Remove(variant1.Length - 1, 1) + "ן";
                    }
                    else if (variant1.EndsWith("מ"))
                    {
                        variant1 = variant1.Remove(variant1.Length - 1, 1) + "ם";
                    }
                    else if (variant1.EndsWith("כ"))
                    {
                        variant1 = variant1.Remove(variant1.Length - 1, 1) + "ך";
                    }
                    else if (variant1.EndsWith("צ"))
                    {
                        variant1 = variant1.Remove(variant1.Length - 1, 1) + "ץ";
                    }

                    searchAndOrList[i].Add(variant1);
                    continue;
                }
                #endregion

                #region man couple 2

                //"פ" - "ף"
                //"נ" - "ן"
                //"מ" - "ם"
                // "כ" - "ך"
                // "צ" - "ץ"
                if (word.EndsWith("ף"))
                {
                    var variant1 = word.Remove(word.Length - 1, 1) + "פ";
                    variant1 += "ים";
                    searchAndOrList[i].Add(variant1);
                    continue;
                }
                else if (word.EndsWith("ן"))
                {
                    var variant1 = word.Remove(word.Length - 1, 1) + "נ";
                    variant1 += "ים";
                    searchAndOrList[i].Add(variant1);
                    continue;
                }
                else if (word.EndsWith("ם"))
                {
                    var variant1 = word.Remove(word.Length - 1, 1) + "מ";
                    variant1 += "ים";
                    searchAndOrList[i].Add(variant1);
                    continue;
                }
                else if (word.EndsWith("ך"))
                {
                    var variant1 = word.Remove(word.Length - 1, 1) + "כ";
                    variant1 += "ים";
                    searchAndOrList[i].Add(variant1);
                    continue;
                }
                else if (word.EndsWith("ץ"))
                {
                    var variant1 = word.Remove(word.Length - 1, 1) + "צ";
                    variant1 += "ים";
                    searchAndOrList[i].Add(variant1);
                    continue;
                }

                #endregion
            }
            //   var orTextPredicate = words.Where(x => x.Length > 3).ToList(); // select only length > 3, keywords
            //if (orTextPredicate.Count > 0)
            int whatPosition = 0;
            foreach (var orTextPredicate in searchAndOrList)
            {
                Expression <Func <Product, bool> > predicate = null;
                foreach (var s in orTextPredicate)
                {
                    if (whatPosition == 0)
                    {
                        if (predicate != null)
                        {
                            predicate = predicate.MultiSearchOrSql(x => x.Name.StartsWith(s + " ") ||
                                                                   x.SKU.StartsWith(s + " ") ||
                                                                   x.ShortDescription.StartsWith(s + " ") ||
                                                                   x.FullDescription.StartsWith(s + " ")
                                                                   //     || x.Manufacturer.Contains(s)
                                                                   );
                        }
                        else
                        {
                            predicate = x => (x.Name.StartsWith(s) ||
                                              x.SKU.StartsWith(s) ||
                                              x.ShortDescription.StartsWith(s) ||
                                              x.FullDescription.StartsWith(s)
                                              //      || x.Manufacturer.Contains(s)
                                              );
                        }
                    }
                    else
                    {
                        if (predicate != null)
                        {
                            predicate = predicate.MultiSearchOrSql(x => x.Name.Contains(s) ||
                                                                   x.SKU.Contains(s) ||
                                                                   x.ShortDescription.Contains(s) ||
                                                                   x.FullDescription.Contains(s)
                                                                   //     || x.Manufacturer.Contains(s)
                                                                   );
                        }
                        else
                        {
                            predicate = x => (x.Name.Contains(s) ||
                                              x.SKU.Contains(s) ||
                                              x.ShortDescription.Contains(s) ||
                                              x.FullDescription.Contains(s)
                                              //      || x.Manufacturer.Contains(s)
                                              );
                        }
                    }
                }
                if (predicate != null)
                {
                    source = source.Where(predicate);
                }
                whatPosition++;
            }


            #endregion

            result.AddRange((from ps in LS.CurrentEntityContext.ProductShopMap
                             join p in source
                             on ps.ProductID equals p.ID
                             where ps.ShopID == ShopID
                             // && p.Name.Contains(text)
                             select new ProductShortModel
            {
                Name = p.Name,
                ID = ps.ProductID
            }).Take(20).ToList());
            if (result.Count == 0)
            {
                //no result
                UserActivityService.InsertSearchNotFound(text, ShopID, LS.CurrentUser.ID
                                                         , HttpContext.Current.Request.RawUrl,
                                                         HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.OriginalString : null
                                                         , LS.GetUser_IP(HttpContext.Current.Request));
            }
            return(result);
        }
        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));
        }
Beispiel #15
0
        public ActionResult Import(HttpPostedFileBase attachment, bool deleteold = false, bool useContains = false)
        {
            if (CurrentShop == null)
            {
                return(Json(new { success = "error", message = RP.S("Admin.ProductShop.Import.Error.NoShop") }));
            }
            if (attachment == null)
            {
                // TempData["MessageRed"] = "File Error";
                return(Json(new { success = "error", message = RP.S("Admin.ProductShop.Import.Error.FileMissing") }));
            }
            _db.Configuration.ValidateOnSaveEnabled = false;
            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 = RP.S("Admin.ProductShop.Import.Error.FileExtensionMustBe.xls.xlsx.csv") }));
            }

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

            #region read excell
            if (FileName.EndsWith(".xls"))
            {
                using (var fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                {
                    var wb = new HSSFWorkbook(fs);
                    // get sheet
                    var sh       = (HSSFSheet)wb.GetSheetAt(0);
                    var head     = sh.GetRow(0);
                    int colCount = 0;
                    if (head != null)
                    {
                        colCount = head.Cells.Count;
                    }
                    int i = 1;
                    while (sh.GetRow(i) != null)
                    {
                        var xlsRow = sh.GetRow(i);
                        // read some data
                        Dictionary <int, string> row = new Dictionary <int, string>();
                        // write row value
                        for (int j = 0; j < colCount; j++)
                        {
                            var cell = xlsRow.GetCell(j);

                            if (cell != null)
                            {
                                // TODO: you can add more cell types capability, e. g. formula
                                switch (cell.CellType)
                                {
                                case NPOI.SS.UserModel.CellType.Numeric:
                                    var valN = cell.NumericCellValue;
                                    row[j] = valN.ToString();
                                    break;

                                case NPOI.SS.UserModel.CellType.String:
                                    var val = cell.StringCellValue;
                                    row[j] = val != null ? val : "";
                                    break;

                                default:
                                    row[j] = "";
                                    break;
                                }
                            }
                            else
                            {
                                row[j] = "";
                            }
                        }
                        all.Add(row);
                        i++;
                    }
                }
            }
            else
            {
                // 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);
                            }
                        }
                    }
                }
            }
            #endregion
            //Dictionary<string, string> skuImageMap = new Dictionary<string, string>();
            //Dictionary<int, string> idImageMap = new Dictionary<int, string>();
            var productforInsert = new List <ProductShop>();
            var productForUpdate = new List <ProductShop>();
            var productForDelete = new List <ProductShop>();
            //  var productForDelete = new List<Product>();
            var productsList = _db.Products
                               .OrderBy(x => x.ID)
                               .Select(x => new { x.ID, x.SKU, x.ProductShopOptions, x.CategoryID, x.UnitsPerPackage }) // optimization
                               .ToList().ToDictionary(x => x.SKU);
            int shopID          = CurrentShop.ID;
            var shopCategories  = _db.ShopCategories.Where(x => x.ShopID == shopID).ToList(); // LS.Get<ShopCategory>().Where(x => x.ShopID == shopID).ToList();
            var categories      = LS.Get <Category>();
            var productShopList = _db.ProductShopMap
                                  .OrderBy(x => x.ID)
                                  .Where(x => x.ShopID == shopID)
                                  .Select(x => new { x.ID, x.ProductID, x.DontImportPrice }).ToList();
            var replaceSkuMap    = _db.ProductSkuMaps.AsNoTracking().Where(x => x.ShopID == shopID).ToList();
            var decimalSeparator = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
            //  var AllCategories = LS.Get<Category>(); //get category cache
            //options container
            //Dictionary<int,
            List <ProductAttributeOption> updateAttributes = new List <ProductAttributeOption>();
            Dictionary <int, List <ProductAttributeOption> > insertAttributes = new Dictionary <int, List <ProductAttributeOption> >();

            Dictionary <int, int> productShopIDMap       = new Dictionary <int, int>();
            List <int>            notDeleteListIds       = new List <int>();
            List <int>            notDeleteListSkuMapIds = new List <int>();

            //Run each excell
            StringBuilder       resultMessage                   = new StringBuilder();
            List <ProcessError> processErrors                   = new List <ProcessError>();
            bool                     needAddCategory            = true;
            int                      minCoulCount               = 9;
            int                      curLine                    = 1;
            StringBuilder            lastEmpty                  = new StringBuilder();
            bool                     createProductIfSkuNotExist = false;
            Dictionary <string, int> processed                  = new Dictionary <string, int>();
            var                      sheme = new PShopImportSheme();
            foreach (var s in all)
            {
                curLine++;
                bool allOk = true;
                if (curLine == 2)
                {
                    continue;
                }                              //skip second row (excell numeration)
                if (s.Count < minCoulCount)
                {
                    processErrors.Add(new ProcessError()
                    {
                        LineNum = curLine
                        ,
                        Message = string.Format(RP.S("Admin.ProductShop.Import.Error.MissingColumns-ParameterLineNum{0}"), curLine)
                    });
                    resultMessage.AppendLine(string.Format(RP.S("Admin.ProductShop.Import.Error.MissingColumns-ParameterLineNum{0}"), curLine));
                    continue;
                }
                if (s[sheme.SKU] == null || s[sheme.SKU].ToString().Trim() == "")
                {
                    allOk = false;
                    processErrors.Add(new ProcessError()
                    {
                        LineNum = curLine
                        ,
                        Message = string.Format(RP.S("Admin.ProductShop.Import.Error.SKUEmpty-LineNume{0}"), curLine)
                    });
                    lastEmpty.AppendLine(string.Format(RP.S("Admin.ProductShop.Import.Error.SKUEmpty-LineNume{0}"), curLine));
                    continue;
                    //    continue;
                }
                if (lastEmpty.Length > 0)
                {
                    resultMessage.AppendLine(lastEmpty.ToString());
                    lastEmpty.Clear();
                }
                var sku = s[sheme.SKU].ToString().Trim();//must be unique, check and validate
                sku = Regex.Replace(sku, "[^.0-9]", "");
                var originalSku = sku;
                //check map table
                var replaceTo = replaceSkuMap.FirstOrDefault(x => (
                                                                 x.ShortSKU != null &&
                                                                 sku != null &&
                                                                 x.ShortSKU == sku)
                                                             );
                if (replaceTo != null && !string.IsNullOrEmpty(replaceTo.ProductSKU))
                {
                    sku = replaceTo.ProductSKU;
                    notDeleteListSkuMapIds.Add(replaceTo.ID);
                }
                else if (useContains && originalSku.Length >= minSkuLength)
                {
                    sku = productsList.Keys.FirstOrDefault(x => x.EndsWith(originalSku));
                    sku = string.IsNullOrEmpty(sku) ? originalSku : sku;
                }

                if (string.IsNullOrEmpty(sku) && string.IsNullOrEmpty(s[sheme.Name]))
                {
                    continue;
                }
                //check if not repeated row
                if ((sku != null && processed.ContainsKey(sku))
                    )
                {
                    processErrors.Add(new ProcessError()
                    {
                        LineNum = curLine
                        ,
                        SKU = sku
                        ,
                        Message = string.Format(RP.S("Admin.Product.Import.Error.SKUAlreadyProcessed-LineNume{0}"), curLine)
                                  + " (Row: " + processed [sku].ToString() + ")"
                    });
                    resultMessage.AppendLine(string.Format(RP.S("Admin.Product.Import.Error.SKUAlreadyProcessed-LineNume{0}"), curLine) + " (Row: " + processed[sku].ToString() + ")");

                    continue;
                }
                var     priceStr     = s[sheme.Price].ToString().Trim();
                decimal productPrice = 0;
                int     stepQuantity = 1000;
                if (!int.TryParse(s[sheme.Quantity].Trim(), out stepQuantity))
                {
                    stepQuantity = 1000;
                }
                try
                {
                    productPrice = Convert.ToDecimal(priceStr.Replace(".", decimalSeparator).Replace(",", decimalSeparator));
                }
                catch
                { }
                if (sku != null)
                {
                    processed[sku] = curLine;
                }
                else
                {
                    processed[s[sheme.Name]] = curLine;
                }
                int temp = 0;
                if (sku == null || !productsList.ContainsKey(sku))
                {
                    //add to map if not exists
                    if (!replaceSkuMap.Any(x => (
                                               x.ShortSKU != null &&
                                               originalSku != null &&
                                               x.ShortSKU == originalSku)
                                           ))
                    {
                        var newMapSkuSlk = new ProductSkuMap()
                        {
                            // ProductSKU = ,
                            ShortSKU          = originalSku,
                            ShopID            = shopID,
                            Price             = productPrice,
                            ImportProductName = s[sheme.Name],
                            Quantity          = stepQuantity
                        };
                        _db.ProductSkuMaps.Add(newMapSkuSlk);
                        _db.SaveChanges();
                        replaceSkuMap.Add(newMapSkuSlk);
                    }
                    else
                    {
                        notDeleteListSkuMapIds.Add(replaceSkuMap.FirstOrDefault(x => (
                                                                                    x.ShortSKU != null &&
                                                                                    originalSku != null &&
                                                                                    x.ShortSKU == originalSku)
                                                                                // || (x.ShortSKU == null && x.ImportProductName != null && s[sheme.Name] != null
                                                                                // && x.ImportProductName == s[sheme.Name])
                                                                                ).ID);
                    }
                    //process insert new product (parent)
                    if (!createProductIfSkuNotExist)
                    {
                        allOk = false;
                        processErrors.Add(new ProcessError()
                        {
                            LineNum = curLine
                            ,
                            SKU     = sku,
                            Message = string.Format(RP.S("Admin.ProductShop.Import.Error.SkuNotExists-ParameterLineNum{0}"), curLine)
                        });
                        resultMessage.AppendLine(string.Format(RP.S("Admin.ProductShop.Import.Error.SkuNotExists-ParameterLineNum{0}"), curLine));
                        continue;
                    }
                    else
                    {
                        var productSku = new Product()
                        {
                            SKU  = sku,
                            Name = sku,
                        };
                        _db.Products.Add(productSku);
                        _db.SaveChanges();
                        productsList.Add(sku, new
                        {
                            productSku.ID,
                            productSku.SKU
                            ,
                            productSku.ProductShopOptions,
                            productSku.CategoryID,
                            productSku.UnitsPerPackage
                        });
                    }
                    // resultMessage.AppendLine(string.Format(RP.S("Admin.ProductShop.Import.Error.NoProductWithSKU-ParameterSKU"), sku));
                    //  continue; // no product
                }
                replaceTo = replaceSkuMap.FirstOrDefault(x => (
                                                             x.ShortSKU != null &&
                                                             originalSku != null &&
                                                             x.ShortSKU == originalSku)
                                                         //  || (x.ShortSKU == null && x.ImportProductName != null && s[sheme.Name] != null
                                                         // && x.ImportProductName == s[sheme.Name])
                                                         );

                if (replaceTo == null)
                {
                    var newMapSkuSlk = new ProductSkuMap()
                    {
                        ProductSKU        = productsList[sku].SKU,
                        ShortSKU          = originalSku,
                        ShopID            = shopID,
                        Price             = productPrice,
                        ImportProductName = s[sheme.Name],
                        Quantity          = stepQuantity,
                        Imported          = true
                    };
                    _db.ProductSkuMaps.Add(newMapSkuSlk);
                    _db.SaveChanges();
                    replaceSkuMap.Add(newMapSkuSlk);
                }
                else
                {
                    notDeleteListSkuMapIds.Add(replaceTo.ID);
                }
                var pID            = productsList[sku].ID;
                var defaultOptions = productsList[sku].ProductShopOptions;
                var categoryID     = productsList[sku].CategoryID;

                // if (priceStr == "")
                // {
                //    priceStr = "0";
                // }
                var product = new ProductShop()
                {
                    ProductID = pID,
                    ShopID    = shopID,

                    IncludeVat         = true,
                    IncludeInShipPrice = true
                };
                try
                {
                    product.Price = Convert.ToDecimal(priceStr.Replace(".", decimalSeparator).Replace(",", decimalSeparator));
                    if (productsList[sku].UnitsPerPackage.HasValue && productsList[sku].UnitsPerPackage.Value > 0)
                    {
                        //price by one unit
                        product.PriceByUnit = product.Price / productsList[sku].UnitsPerPackage.Value;
                    }
                }
                catch (Exception e)
                {
                    allOk = false;
                    processErrors.Add(new ProcessError()
                    {
                        LineNum = curLine
                        ,
                        SKU     = sku,
                        Message = string.Format(RP.S("Admin.ProductShop.Import.Error.BadPrice-ParameterLineNum{0}"), curLine)
                    });
                    resultMessage.AppendLine(string.Format(RP.S("Admin.ProductShop.Import.Error.BadPrice-ParameterLineNum{0}"), curLine));
                    // continue;
                }
                if (s[sheme.VAT].ToString().Trim() == "0" || s[sheme.VAT].ToString().Trim() == "false" ||
                    s[sheme.VAT].ToString().Trim() == "False")
                {
                    product.IncludeVat = false;
                }
                if (s[sheme.IncludeInShipPrice].ToString().Trim() == "0" ||
                    s[sheme.IncludeInShipPrice].ToString().Trim() == "false" ||
                    s[sheme.IncludeInShipPrice].ToString().Trim() == "False")
                {
                    product.IncludeInShipPrice = false;
                }
                product.QuantityType = ProductQuantityType.NotCheck;
                if (s[sheme.QuantityChecking].ToString().Trim() == "1")
                {
                    product.QuantityType = ProductQuantityType.CheckByProduct;
                }
                else if (s[sheme.QuantityChecking].ToString().Trim() == "2")
                {
                    product.QuantityType = ProductQuantityType.CheckByProductOptions;
                }
                //step for quantity change
                int step = 1000;
                if (!string.IsNullOrEmpty(s[sheme.Quantity]))
                {
                    bool valid = int.TryParse(s[sheme.Quantity].ToString().Trim(), out step);
                    if (!valid)
                    {
                        step = 1000;
                    }
                    else
                    {
                        product.QuantityType = ProductQuantityType.CheckByProduct;
                    }
                }
                product.Quantity = step;
                if (!string.IsNullOrEmpty(s[sheme.MaxToOrder].ToString().Trim()))
                {
                    step = 0;
                    bool valid = int.TryParse(s[sheme.MaxToOrder].ToString().Trim(), out step);
                    if (step > 0)
                    {
                        product.MaxCartQuantity = step;
                    }
                    if (!valid)
                    {
                        allOk = false;
                        processErrors.Add(new ProcessError()
                        {
                            LineNum = curLine
                            ,
                            SKU     = sku,
                            Message = string.Format(RP.S("Admin.ProductShop.Import.Error.MaxCartQuantity-ParameterLineNum{0}"), curLine)
                        });
                        resultMessage.AppendLine(string.Format(RP.S("Admin.ProductShop.Import.Error.MaxCartQuantity-ParameterLineNum{0}"), curLine));
                    }
                }
                if (!allOk)
                {
                    continue;
                }
                var psh = productShopList.FirstOrDefault(x => x.ProductID == pID);
                if (psh != null)
                {
                    if (product.Price == 0 || (product.Quantity == 0))
                    //&& product.QuantityType != ProductQuantityType.NotCheck) )
                    {
                        //delete product
                        productForDelete.Add(new ProductShop()
                        {
                            ID = psh.ID
                        });
                        continue;
                    }
                    if (psh.DontImportPrice)
                    {
                        product.Price = 0;//don`t import price
                    }
                    product.ID = psh.ID;
                    productForUpdate.Add(product);
                    productShopIDMap[pID] = psh.ID;
                    if (deleteold)
                    {
                        notDeleteListIds.Add(psh.ID);
                    }
                }
                else
                {
                    if (product.Price == 0 || (product.Quantity == 0))
                    //&& product.QuantityType != ProductQuantityType.NotCheck))
                    {
                        //don`t import if price 0
                        continue;
                    }
                    product.CreateDate = DateTime.Now;
                    productforInsert.Add(product);
                }

                //category check
                if (categoryID > 0)
                {
                    if (!shopCategories.Any(x => x.CategoryID == categoryID))
                    {
                        //create and add
                        var shopCat = new ShopCategory()
                        {
                            CategoryID   = categoryID,
                            DisplayOrder = 1000,
                            Published    = true,
                            ShopID       = shopID
                        };
                        _db.ShopCategories.Add(shopCat);
                        shopCategories.Add(shopCat);
                        //check if parent cat in shop map
                        var cat = categories.FirstOrDefault(x => x.ID == categoryID);
                        if (cat != null && cat.ParentCategoryID > 0)
                        {
                            int parentCategoryID = cat.ParentCategoryID;
                            if (!shopCategories.Any(x => x.CategoryID == parentCategoryID))
                            {
                                //create and add
                                var shopCatParent = new ShopCategory()
                                {
                                    CategoryID   = parentCategoryID,
                                    DisplayOrder = 1000,
                                    Published    = true,
                                    ShopID       = shopID
                                };
                                _db.ShopCategories.Add(shopCatParent);
                                shopCategories.Add(shopCatParent);
                            }
                        }
                        _db.SaveChanges();
                    }
                    else
                    {
                        //update visibility
                        var ct = shopCategories.FirstOrDefault(x => x.CategoryID == categoryID);
                        if (ct != null && !ct.Published)
                        {
                            ct.Published = true;
                            //check parent
                            var cat = categories.FirstOrDefault(x => x.ID == categoryID);
                            if (cat != null && cat.ParentCategoryID > 0)
                            {
                                int parentCategoryID = cat.ParentCategoryID;
                                if (!shopCategories.Any(x => x.CategoryID == parentCategoryID))
                                {
                                    //create and add
                                    var shopCatParent = new ShopCategory()
                                    {
                                        CategoryID   = parentCategoryID,
                                        DisplayOrder = 1000,
                                        Published    = true,
                                        ShopID       = shopID
                                    };
                                    _db.ShopCategories.Add(shopCatParent);
                                    shopCategories.Add(shopCatParent);
                                }
                                else
                                {
                                    var prcat = shopCategories.FirstOrDefault(x => x.CategoryID == parentCategoryID);
                                    if (prcat != null && !prcat.Published)
                                    {
                                        prcat.Published = true;
                                    }
                                }
                            }

                            _db.SaveChanges();
                        }
                    }
                }
                else
                {
                    product.NotInCategory = true;
                    if (needAddCategory)//run only one time
                    {
                        var otherCategory = categories.FirstOrDefault(x => x.Name == "מוצרים נוספים" && x.ParentCategoryID == 0);
                        if (otherCategory == null)
                        {
                            otherCategory = new Category()
                            {
                                DisplayOrder = 1000000,
                                Name         = "מוצרים נוספים",
                                Published    = true,
                            };
                            _db.Categories.Add(otherCategory);
                            _db.SaveChanges();
                            categories.Add(otherCategory);
                        }
                        var catshopmap = shopCategories.FirstOrDefault(x => x.CategoryID == otherCategory.ID);
                        if (catshopmap == null)
                        {
                            var otherShopCategory = new ShopCategory()
                            {
                                CategoryID   = otherCategory.ID,
                                DisplayOrder = 1000000,
                                Published    = true,
                                ShopID       = shopID
                            };
                            _db.ShopCategories.Add(otherShopCategory);
                            _db.SaveChanges();
                        }
                        else
                        {
                            if (!catshopmap.Published)
                            {
                                var catshopMapAttached = _db.ShopCategories.FirstOrDefault(x => x.ID == catshopmap.ID);
                                if (catshopMapAttached != null)
                                {
                                    catshopMapAttached.Published = true;
                                    _db.SaveChanges();
                                }
                            }
                        }
                        needAddCategory = false;
                    }
                }

                //options
                string options = s[sheme.Options].ToString().Trim();
                if (string.IsNullOrEmpty(options))
                {
                    //default options
                    options = defaultOptions;
                }
                if (!string.IsNullOrEmpty(options))
                {
                    string[] values   = options.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    var      listattr = new List <ProductAttributeOption>();
                    foreach (var o in values)
                    {
                        ProductAttributeOption pao = new ProductAttributeOption()
                        {
                            Name = o,

                            ProductShopID = product.ID
                        };
                        listattr.Add(pao);
                    }
                    if (psh != null)
                    {
                        updateAttributes.AddRange(listattr);
                    }
                    else
                    {
                        insertAttributes.Add(pID, listattr);
                    }
                }
            }
            string message = RP.S("Admin.ProductShop.Import.SeeError");
            if (true)// || resultMessage.Length < 3)
            {
                productForUpdate.SqlUpdateById(false);
                int lastID = _db.ProductShopMap.Select(x => x.ID).DefaultIfEmpty().Max();
                productforInsert.SqlInsert();
                productForDelete.SqlDeleteById();
                //run options insert update
                //1) get last product shop ID and get list of products

                if (deleteold)
                {
                    List <ProductShop> deleteThis = new List <ProductShop>();
                    foreach (var pshID in productShopList)
                    {
                        if (!notDeleteListIds.Contains(pshID.ID))
                        {
                            deleteThis.Add(new ProductShop()
                            {
                                ID = pshID.ID
                            });
                        }
                    }
                    deleteThis.SqlDeleteById();



                    List <ProductSkuMap> deleteThisMap = new List <ProductSkuMap>();
                    foreach (var mapID in replaceSkuMap)
                    {
                        if (!notDeleteListSkuMapIds.Contains(mapID.ID))
                        {
                            deleteThisMap.Add(new ProductSkuMap()
                            {
                                ID = mapID.ID
                            });
                        }
                    }
                    deleteThisMap.SqlDeleteById();
                }

                var psmap = _db.ProductShopMap
                            .Where(x => x.ID > lastID && x.ShopID == shopID)
                            .Select(x => new { x.ID, x.ProductID }).ToList();

                foreach (var it in psmap)
                {
                    productShopIDMap[it.ProductID] = it.ID;
                }
                //.ToDictionary(x => x.ProductID, x => x.ID)
                //productShopIDMap.AddRange(

                //    );
                // run options merge
                foreach (var o in insertAttributes)
                {
                    if (productShopIDMap.ContainsKey(o.Key))
                    {
                        int productShopID = productShopIDMap[o.Key];
                        o.Value.ForEach((x) =>
                        {
                            x.ProductShopID = productShopID;

                            updateAttributes.Add(x);
                        });
                    }
                }
                insertAttributes.Clear();
                //runn options insert or update
                var    containsFilterList = updateAttributes.Select(x => x.ProductShopID).Distinct().ToList();
                var    existsAttributes   = _db.ProductAttributeOptions.Where(x => containsFilterList.Contains(x.ProductShopID)).ToList();
                var    forInsertOptions   = new List <ProductAttributeOption>();
                object _lock = new object();//for lock multithread action
                Parallel.ForEach(updateAttributes, x =>
                {
                    var cur = existsAttributes.FirstOrDefault(y => y.ProductShopID == x.ProductShopID && y.Name == x.Name);
                    if (cur != null)
                    {
                        //update
                    }
                    else
                    {
                        //insert
                        lock (_lock)
                        {
                            forInsertOptions.Add(x);
                        }
                    }
                });
                //and insert options
                forInsertOptions.SqlInsert();
                message = RP.S("Admin.ProductShop.Import.Success");
                //add errors to table
                try
                {
                    foreach (var procError in processErrors)
                    {
                        procError.CreateOn        = DateTime.Now;
                        procError.FileServiceName = FileName;
                        procError.IP         = LS.GetUser_IP(Request);
                        procError.PageUrl    = Request.RawUrl;
                        procError.RefererUrl = Request.UrlReferrer != null ? Request.UrlReferrer.OriginalString : null;
                        procError.ShopID     = shopID;
                        procError.UserID     = LS.CurrentUser.ID;
                    }
                    processErrors.SqlInsert();
                }
                catch
                {
                }
            }


            return(Json(new { success = "ok", message = message, errors = resultMessage.ToString() }));
        }
        public static AddToCartModel AddToCart(Guid UserID, ShoppingCartItem item
                                               , decimal?Quantity    = null
                                               , decimal?QuantityBit = null
                                               , bool?Delete         = null
                                               , int?Attribute       = null
                                               , int?qtype           = null,
                                               bool isMobile         = false)
        {
            List <string> Errors = new List <string>();

            if (item.ProductShopID < 1 && item.ID == 0)
            {
                Errors.Add(RP.S("ShoppingCart.AddToCart.Error.DataIssuse"));
                return(new AddToCartModel()
                {
                    errors = Errors,
                    item = item
                });
                // return Json(new { result = "error", message = "Data issuse", data = item });
            }
            bool changeOriginalQuantity = true;

            //if (!LS.isLogined()) //Not actual here
            //{
            //    return Json(new { result = "error", action = "login", message = "You must login first", data = item });
            //}


            if (item.ID > 0)
            {
                item = LS.CurrentEntityContext.ShoppingCartItems.Where(x => x.ID == item.ID
                                                                       ).FirstOrDefault();
                // changeOriginalQuantity = false;
                if (item == null)
                {
                    Errors.Add(RP.S("ShoppingCart.AddToCart.Error.ItemNotFound"));
                    return(new AddToCartModel()
                    {
                        errors = Errors,
                        item = item
                    });
                }
                if (Attribute.HasValue)
                {
                    item.ProductAttributeOptionID = Attribute.Value;
                }
            }



            //if (item.Quantity <= 0)
            //{
            //    Errors.Add(RP.S("ShoppingCart.AddToCart.Error.QuantityLessThan1"));
            //    return new AddToCartModel()
            //    {
            //        errors = Errors,
            //        item = item
            //    };
            //    //  return Json(new { result = "error", message = "Quantity can`t be less then 1", data = item });
            //}
            var maxQuantity = decimal.MaxValue;
            var productShop = LS.CurrentEntityContext.ProductShopMap.FirstOrDefault(x => x.ID == item.ProductShopID);

            if (productShop == null)
            {
                Errors.Add(RP.S("ShoppingCart.AddToCart.Error.ProductNotFound"));
                return(new AddToCartModel()
                {
                    errors = Errors,
                    item = item
                });
                // return Json(new { result = "error", message = "product not found", data = item });
            }
            if (productShop.QuantityType == ProductQuantityType.CheckByProduct)
            {
                maxQuantity = productShop.Quantity;
            }
            if (item.ProductAttributeOptionID == 0)
            {
                if (LS.CurrentEntityContext.ProductAttributeOptions.Any(x => x.ProductShopID == item.ProductShopID))
                {
                    Errors.Add(RP.S("ShoppingCart.AddToCart.Error.OptionNotSelected"));
                    return(new AddToCartModel()
                    {
                        errors = Errors,
                        item = item
                    });
                    //return Json(new { result = "error", message = "Need select option", data = item });
                }
                if (productShop.Price <= 0)
                {
                    Errors.Add(RP.S("ShoppingCart.AddToCart.Error.ZeroPrice"));
                    return(new AddToCartModel()
                    {
                        errors = Errors,
                        item = item
                    });
                    // return Json(new { result = "error", message = "You can`t add product with zero price", data = item });
                }
            }
            else
            {
                var option = LS.CurrentEntityContext.ProductAttributeOptions.FirstOrDefault(x => x.ProductShopID == item.ProductShopID && x.ID == item.ProductAttributeOptionID);
                if (option == null)
                {
                    Errors.Add(RP.S("ShoppingCart.AddToCart.Error.OptionNotFoud"));
                    return(new AddToCartModel()
                    {
                        errors = Errors,
                        item = item
                    });
                    //return Json(new { result = "error", message = "Option not exists", data = item });
                }

                if ((option.OverridenPrice.HasValue && option.OverridenPrice <= 0))
                {
                    Errors.Add(RP.S("ShoppingCart.AddToCart.Error.ZeroPrice"));
                    return(new AddToCartModel()
                    {
                        errors = Errors,
                        item = item
                    });
                    //   return Json(new { result = "error", message = "You can`t add product with zero price", data = item });
                }
                if (!option.OverridenPrice.HasValue &&
                    productShop.Price <= 0)
                {
                    Errors.Add(RP.S("ShoppingCart.AddToCart.Error.ZeroPrice"));
                    return(new AddToCartModel()
                    {
                        errors = Errors,
                        item = item
                    });
                    //   return Json(new { result = "error", message = "You can`t add product with zero price", data = item });
                }
                if (productShop.QuantityType == ProductQuantityType.CheckByProductOptions)
                {
                    maxQuantity = option.Quantity;
                }
            }


            //check existing
            if (maxQuantity == 0)
            {
                Errors.Add(RP.S("ShoppingCart.AddToCart.Error.NoEnoughQuantity"));
                return(new AddToCartModel()
                {
                    errors = Errors,
                    item = item
                });
                // return Json(new { result = "error", message = "No quantity enough", data = item });
            }
            ShoppingCartItem existing = null;

            if (item.ID > 0)
            {
                existing = item;
            }
            else
            {
                existing = LS.CurrentEntityContext.ShoppingCartItems.Where(x => x.UserID == UserID &&
                                                                           x.ProductShopID == item.ProductShopID &&
                                                                           x.ProductAttributeOptionID == item.ProductAttributeOptionID).FirstOrDefault();
            }

            if (existing != null)
            {
                if (QuantityBit.HasValue)
                {
                    if (existing.QuantityType == QuantityType.ByUnit)
                    {
                        if (QuantityBit.Value > 0)
                        {
                            QuantityBit = (decimal)Math.Ceiling(QuantityBit.Value);
                        }
                        else
                        {
                            QuantityBit = (decimal)Math.Floor(QuantityBit.Value);
                        }
                    }
                    existing.Quantity += QuantityBit.Value;
                }
                else
                if (Quantity.HasValue)
                {
                    if (existing.Quantity.ToString("0.000") == Quantity.Value.ToString("0.000") && !qtype.HasValue)
                    {
                        existing.Quantity += 1;
                    }
                    else
                    {
                        existing.Quantity = Quantity.Value;
                    }
                }
                else if (changeOriginalQuantity)
                {
                    if (existing.Quantity.ToString("0.000") == item.Quantity.ToString("0.000") && !qtype.HasValue)
                    {
                        existing.Quantity += 1;
                    }
                    else
                    {
                        existing.Quantity = item.Quantity;
                    }
                }


                if (existing.Quantity > maxQuantity)
                {
                    Errors.Add(RP.S("ShoppingCart.AddToCart.Error.NoQuantityEnought-StringParamMaxQuantity"));
                    return(new AddToCartModel()
                    {
                        errors = Errors,
                        item = item
                    });
                    // return Json(new { result = "error", message = "No quantity enough, max is " + maxQuantity.ToString(), data = item });
                }
                if (qtype.HasValue)
                {
                    existing.QuantityType = (QuantityType)qtype.Value;
                    if (existing.QuantityType == QuantityType.ByUnit)
                    {
                        existing.Quantity = Math.Ceiling(existing.Quantity);
                    }
                }
                if ((Delete.HasValue && Delete.Value) || existing.Quantity <= 0)
                {
                    existing.Quantity = 0;
                    LS.CurrentEntityContext.ShoppingCartItems.Remove(existing);
                }
                else
                {
                    UserActivityService.InsertAddToCart(UserID, item.ProductShopID, item.Quantity
                                                        , item.ShopID, item.ProductAttributeOptionID
                                                        , HttpContext.Current.Request.RawUrl,
                                                        HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.OriginalString : null,
                                                        LS.GetUser_IP(HttpContext.Current.Request));
                }
                LS.CurrentEntityContext.SaveChanges();
                item = existing;
            }
            else
            {
                item.UserID = UserID;
                if (item.Quantity > maxQuantity)
                {
                    Errors.Add(RP.S("ShoppingCart.AddToCart.Error.NoQuantityEnought-StringParamMaxQuantity"));
                    return(new AddToCartModel()
                    {
                        errors = Errors,
                        item = item
                    });
                    //return Json(new { result = "error", message = "No quantity enough, max is " + maxQuantity.ToString(), data = item });
                }
                UserActivityService.InsertAddToCart(UserID, item.ProductShopID, item.Quantity
                                                    , item.ShopID, item.ProductAttributeOptionID
                                                    , HttpContext.Current.Request.RawUrl,
                                                    HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.OriginalString : null
                                                    , LS.GetUser_IP(HttpContext.Current.Request));
                LS.CurrentEntityContext.ShoppingCartItems.Add(item);
                LS.CurrentEntityContext.SaveChanges();
            }
            if (productShop.PriceByUnit.HasValue && productShop.PriceByUnit.Value > 0)
            {
                item.MeasureUnit = "doNotUseIt";
            }
            return(new AddToCartModel()
            {
                errors = Errors,
                item = item
            });


            //check existing - old version
            //var existing = LS.CurrentEntityContext.ShoppingCartItems.Where(x => x.UserID == UserID
            //    && x.ProductShopID == item.ProductShopID
            //    && x.ProductAttributeOptionID == item.ProductAttributeOptionID).FirstOrDefault();
            //if (existing != null)
            //{
            //    existing.Quantity += item.Quantity;
            //    LS.CurrentEntityContext.SaveChanges();
            //    item = existing;
            //}
            //else
            //{
            //    item.UserID = UserID;
            //    LS.CurrentEntityContext.ShoppingCartItems.Add(item);
            //    LS.CurrentEntityContext.SaveChanges();
            //}
        }