Ejemplo n.º 1
0
        public ActionResult OrderAjax([DataSourceRequest] DataSourceRequest request)
        {
            if (!LS.isHaveID())
            {
                return(Json(new { }));
            }
            //kendo reset manual sort to default =(
            if (request.Sorts == null)
            {
                request.Sorts = new List <SortDescriptor>();
            }
            if (request.Sorts.Count == 0)
            {
                request.Sorts.Add(new SortDescriptor("OrderStatus",
                                                     System.ComponentModel.ListSortDirection.Ascending));
                request.Sorts.Add(new SortDescriptor("ID",
                                                     System.ComponentModel.ListSortDirection.Descending));
            }
            var items = _db.Orders.Where(x => x.UserID == LS.CurrentUser.ID && !x.RegularOrder);

            DataSourceResult result = items.ToDataSourceResult(request);

            foreach (var item in (IEnumerable <Order>)result.Data)
            {
                item.TotalStr           = ShoppingService.FormatPrice(item.Total);
                item.RegularIntervalStr = RP.T("Enums." + item.RegularInterval.ToString()).ToString();
                item.OrderStatusStr     = RP.T("Enums." + item.OrderStatus.ToString()).ToString();
            }
            return(Json(result));
        }
        public ActionResult CSVExport([DataSourceRequest] DataSourceRequest request)
        {
            Expression <Func <Order, bool> > predicate = x => true
                                                         //  && x.OrderStatus != OrderStatus.New
                                                         // && x.OrderStatus != OrderStatus.Canceled
                                                         //  && x.OrderStatus != OrderStatus.Rejected
            ;

            if (request.Filters != null)
            {
                predicate = GetPredicate(predicate, request.Filters);
            }
            var items = _db.Orders.Where(predicate).Select(x => new PaymentReportItemModel()
            {
                ID            = x.ID,
                ShopID        = x.ShopID,
                IsPaidUp      = x.IsPaidUp,
                OrderID       = x.ID,
                Date          = x.CreateOn,
                PaymentMethod = x.PaymentMethod,
                Total         = x.Total
            }).ToList();

            foreach (var item in items)
            {
                item.Total            = item.Cash + item.Card;
                item.TotalStr         = ShoppingService.FormatPrice(item.Total);
                item.PayedTo          = item.Card > 0 ? PayedToType.ToAdmin : PayedToType.ToShop;
                item.PayedToStr       = RP.T("Enums." + item.PayedTo.ToString()).ToString();
                item.PaymentMethodStr = RP.T("Enums." + item.PaymentMethod.ToString()).ToString();
                item.DateStr          = item.Date.HasValue ? item.Date.Value.ToString("dd/MM HH:mm") : "";
            }
            // var items = _db.AbstractPages.Where(r => r.Visible == true).OrderBy(r => r.Title).ToList();
            MemoryStream output = new MemoryStream();
            StreamWriter writer = new StreamWriter(output, Encoding.UTF8);

            writer.Write(RP.M("PaymentReportItemModel", "OrderID") + ",");
            writer.Write(RP.M("PaymentReportItemModel", "Date") + ",");
            writer.Write(RP.M("PaymentReportItemModel", "Total") + ",");
            writer.Write(RP.M("PaymentReportItemModel", "PaymentMethod") + ",");
            writer.Write(RP.M("PaymentReportItemModel", "PayedTo"));
            writer.WriteLine();
            var csvQuote = "\"";

            foreach (var item in items)
            {
                writer.Write(item.OrderID); writer.Write(",\"");
                writer.Write(item.DateStr.Replace(csvQuote, csvQuote + csvQuote)); writer.Write("\",\"");
                writer.Write(item.TotalStr.Replace(csvQuote, csvQuote + csvQuote)); writer.Write("\",\"");
                writer.Write(item.PaymentMethodStr.Replace(csvQuote, csvQuote + csvQuote)); writer.Write("\",\"");
                writer.Write(item.PayedToStr.Replace(csvQuote, csvQuote + csvQuote)); writer.Write("\"");
                writer.WriteLine();
            }
            writer.Flush();
            output.Position = 0;
            Encoding heb = Encoding.GetEncoding("windows-1255");

            return(File(heb.GetBytes(new StreamReader(output).ReadToEnd()), "text/csv", "PaymentReport_" + (DateTime.Now.ToString("dd/MM HH:mm")) + ".csv"));
        }
        public ActionResult _AjaxPaymentReport([DataSourceRequest] DataSourceRequest request)
        {
            if (CurrentShop == null)
            {
                return(Json(new {}));
            }
            //kendo reset manual sort to default =(
            if (request.Sorts.Count == 0)
            {
                request.Sorts.Add(new SortDescriptor("ID",
                                                     System.ComponentModel.ListSortDirection.Descending));
            }
            Expression <Func <Order, bool> > predicate = x => x.ShopID == CurrentShop.ID
                                                         //  && x.OrderStatus != OrderStatus.New
                                                         // && x.OrderStatus != OrderStatus.Canceled
                                                         //  && x.OrderStatus != OrderStatus.Rejected
            ;
            var items = _db.Orders.Where(predicate)
                        .Select(x => new PaymentReportItemModel()
            {
                ID            = x.ID,
                ShopID        = x.ShopID,
                IsPaidUp      = x.IsPaidUp,
                OrderID       = x.ID,
                Date          = x.CreateOn,
                PaymentMethod = x.PaymentMethod,
                Total         = x.Total,
            });

            DataSourceResult result = items.ToDataSourceResult(request);

            foreach (var item in (IEnumerable <PaymentReportItemModel>)result.Data)
            {
                item.Total            = item.Cash + item.Card;
                item.TotalStr         = ShoppingService.FormatPrice(item.Total);
                item.PayedTo          = item.PaymentMethod == PaymentMethod.Credit ? PayedToType.ToAdmin : PayedToType.ToShop;
                item.PayedToStr       = RP.T("Enums." + item.PayedTo.ToString()).ToString();
                item.PaymentMethodStr = RP.T("Enums." + item.PaymentMethod.ToString()).ToString();
                item.DateStr          = item.Date.HasValue ? item.Date.Value.ToString("dd/MM HH:mm") : "";
            }

            //prepare report model
            var model = new PaymentReportModel();

            //prepare filters, get from kendo grid filter
            if (request.Filters != null)
            {
                predicate = GetPredicate(predicate, request.Filters);
            }
            model.TotalShop = _db.Orders.Where(predicate).Where(x => x.PaymentMethod == PaymentMethod.CreditShopOwner && !x.LessFee)
                              .Select(x => x.Total).DefaultIfEmpty(0).Sum();
            model.TotalShop += _db.Orders.Where(predicate).Where(x => !x.LessFee).Select(x => x.Total).DefaultIfEmpty(0).Sum();
            var totalSpecial = _db.Orders.Where(predicate).Where(x => x.PaymentMethod == PaymentMethod.CreditShopOwner && x.LessFee)
                               .Select(x => x.Total).DefaultIfEmpty(0).Sum();

            totalSpecial += _db.Orders.Where(predicate).Where(x => x.LessFee).Select(x => x.Total).DefaultIfEmpty(0).Sum();


            model.TotalAdmin = _db.Orders.Where(predicate).Where(x => x.PaymentMethod == PaymentMethod.Credit)
                               .Select(x => x.Total).DefaultIfEmpty(0).Sum();

            var     date1     = items.Where(x => x.Date.HasValue).Select(x => x.Date.Value).DefaultIfEmpty(DateTime.Now).Max();
            var     date2     = items.Where(x => x.Date.HasValue).Select(x => x.Date.Value).DefaultIfEmpty(DateTime.Now).Min();
            int     mouthes   = ((date1.Year - date2.Year) * 12) + date1.Month - date2.Month;
            decimal mounthFee = CurrentShop.MounthlyFee * mouthes;

            model.TotalFee   = (model.TotalShop * CurrentShop.PercentFee / 100) - model.TotalAdmin + mounthFee;
            model.TotalFee  += (totalSpecial * CurrentShop.SpecialPercentFee / 100);
            model.TotalShop += totalSpecial;
            // if (model.TotalFee < 0) { model.TotalFee = 0; }

            model.TotalAdminStr = ShoppingService.FormatPrice(model.TotalAdmin);
            model.TotalShopStr  = ShoppingService.FormatPrice(model.TotalShop);
            model.TotalFeeStr   = ShoppingService.FormatPrice(model.TotalFee);


            return(Json(new { result.Data, result.AggregateResults, result.Errors, result.Total, model }));
        }
Ejemplo n.º 4
0
        public ActionResult _TopStatus()
        {
            if (!LS.isHaveID())
            {
                return(Content(""));
            }
            var model = new ProfileStatusLine();

            var startCurDate = DateTime.Now.Date;

            var items = _db.Orders.Where(x => x.UserID == LS.CurrentUser.ID &&
                                         x.CreateOn >= startCurDate)
                        //.Select(x=>new {
                        //    x.ID,x.ShopID,x.OrderStatus,x.Total,x.TotalCash,x.CreateOn,x.DeliveredOn,x.PayedOn,
                        //    x.SentOn
                        //})
                        .OrderByDescending(x => x.ID)
                        .ToList();

            foreach (Order order in items)
            {
                OrderStatusLine line = new OrderStatusLine();
                line.OrderDate  = order.CreateOn.ToString("dd/MM HH:mm");
                line.OrderID    = order.ID;
                line.OrderTotal = ShoppingService.FormatPrice(order.Total);
                line.StepStatus = (int)order.OrderStatus;
                line.Status     = order.OrderStatus.ToString();

                if (order.ShippingMethod == ShippingMethod.Manual)
                {
                    line.OrderEndDate = SF.MoveOrderReadyTimeToWorkHours(order).AddMinutes(30).ToString("dd/MM HH:mm");
                }
                else
                {
                    line.OrderEndDate =
                        order.DeliveredOn.HasValue ? order.DeliveredOn.Value.ToString("HH:mm") :
                        order.SentOn.HasValue ? order.SentOn.Value.AddMinutes(ShoppingService.GetShopByID(order.ShopID).DeliveryTime).ToString("HH:mm") :
                        order.PayedOn.HasValue ? order.PayedOn.Value.AddMinutes(ShoppingService.GetShopByID(order.ShopID).DeliveryTime + 15).ToString("HH:mm") :
                        order.CreateOn.AddMinutes(ShoppingService.GetShopByID(order.ShopID).DeliveryTime + 30).ToString("HH:mm");
                }

                model.Orders.Add(line);
            }

            model.Orders = items.Select(x => new OrderStatusLine()
            {
                OrderDate    = x.CreateOn.ToString("dd/MM HH:mm"),
                OrderEndDate =
                    x.DeliveredOn.HasValue ? x.DeliveredOn.Value.ToString("HH:mm") :
                    x.SentOn.HasValue ? x.SentOn.Value.AddMinutes(ShoppingService.GetShopByID(x.ShopID).DeliveryTime).ToString("HH:mm") :
                    x.PayedOn.HasValue ? x.PayedOn.Value.AddMinutes(ShoppingService.GetShopByID(x.ShopID).DeliveryTime + 15).ToString("HH:mm") :
                    x.CreateOn.AddMinutes(ShoppingService.GetShopByID(x.ShopID).DeliveryTime + 30).ToString("HH:mm")
                ,
                OrderID    = x.ID,
                OrderTotal = ShoppingService.FormatPrice(x.Total),
                StepStatus = (int)x.OrderStatus,
                Status     = x.OrderStatus.ToString()
            })

                           .ToList();

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

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

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


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

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


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

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

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

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

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

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

                    data.Add(model);
                }
            }

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

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

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

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

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

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

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

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

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



                    var lowerCaseAddress = address.ToLower();

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

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



            if (withdiscount)
            {
                // process total discounts

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


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

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

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

            if (feutured)
            {
                var exceptProductShopIds = model.Items.Select(x => x.ProductShopID).ToList();
                model.FeaturedProducts = LS.SearchProducts(ShopID, out specifications, featuredLeft: true, excludeProductShopList: exceptProductShopIds, limit: 10).ToList();
                if (model.FeaturedProducts.Count < 10)
                {
                    int limitLeft = 10 - model.FeaturedProducts.Count;
                    var ordered   = LS.SearchProducts(ShopID, out specifications, allOrderedProducts: true, excludeProductShopList: exceptProductShopIds, limit: limitLeft).ToList();
                    foreach (var p in ordered)
                    {
                        if (!model.FeaturedProducts.Any(x => x.ProductShopID == p.ProductShopID))
                        {
                            model.FeaturedProducts.Add(p);
                        }
                    }
                }
                if (model.FeaturedProducts.Count < 10)
                {
                    int limitLeft = 10 - model.FeaturedProducts.Count;
                    var catId     = model.Items.Select(x => x.CategoryID).ToList();
                    if (catId.Count > 0)
                    {
                        var ordered = LS.SearchProducts(ShopID, out specifications, inCategories: catId, excludeProductShopList: exceptProductShopIds, limit: limitLeft).ToList();
                        foreach (var p in ordered)
                        {
                            if (!model.FeaturedProducts.Any(x => x.ProductShopID == p.ProductShopID))
                            {
                                model.FeaturedProducts.Add(p);
                            }
                        }
                    }
                }
            }
            return(model);
        }
        public static IList <ShoppingCartItemModel> GetShoppingCartItemsByList(int ShopID, IList <ShoppingCartItemModel> shoppingcartItems, bool loadAttributes = false)
        {
            var needed     = shoppingcartItems.Select(x => x.ProductID);
            var parentDict = shoppingcartItems.ToList();
            var data       = (from ps in LS.CurrentEntityContext.ProductShopMap
                              join p in LS.CurrentEntityContext.Products
                              on ps.ProductID equals p.ID
                              where ps.ShopID == ShopID &&
                              needed.Contains(p.ID)
                              //join psao in LS.CurrentEntityContext.ProductAttributeOptions
                              //on sci.ProductAttributeOptionID equals psao.ID
                              select new ShoppingCartItemModel()
            {
                ID = 0,
                Name = p.Name,
                Price = ps.Price,
                SKU = p.SKU,
                Image = p.Image,
                ProductID = p.ID,
                ProductShopID = ps.ID,
                QuantityResource = ps.Quantity,
                QuantityType = ps.QuantityType,
                // Quantity = 0,
                ShopID = ps.ShopID,
                // UnitPrice = ps.Price * 0,
                // ProductAttributeOptionID = sci.ProductAttributeOptionID,
                AttributeDescription = "",
                CategoryID = p.CategoryID,
                MeasureUnit = p.MeasureUnit,
                MeasureUnitStep = p.MeasureUnitStep,
            }).ToList();

            foreach (var pitem in parentDict)
            {
                var item = data.FirstOrDefault(x => x.ProductID == pitem.ProductID);
                if (item == null)
                {
                    item = new ShoppingCartItemModel();
                    item.AttributeDescription = pitem.AttributeDescription;
                    item.Image          = pitem.Image;
                    item.Name           = pitem.Name;
                    item.Price          = pitem.Price;
                    item.ProductID      = pitem.ProductID;
                    item.ProductShopID  = pitem.ProductShopID;
                    item.QuantityType   = pitem.QuantityType;
                    item.ShopID         = pitem.ShopID;
                    item.SKU            = pitem.SKU;
                    item.UnitPrice      = pitem.UnitPrice;
                    item.IsNotAvaliable = true;//mark as not avaliable
                    data.Add(item);
                }
                item.Quantity = pitem.Quantity;
                if (pitem.ProductAttributeOptionID > 0)
                {
                    var attributes = (from pao in LS.CurrentEntityContext.ProductAttributeOptions
                                      //  join pa in LS.CurrentEntityContext.ProductAttributes
                                      // on pao.ProductAttributeID equals pa.ID
                                      where pao.ProductShopID == item.ProductShopID
                                      select new ProductAttributeOptionModel()
                    {
                        ID = pao.ID,
                        Name = pao.Name,
                        OverridenPrice = pao.OverridenPrice,
                        OverridenSku = pao.OverridenSku,
                        //  ProductAttributeID = pao.ProductAttributeID,
                        ProductShopID = pao.ProductShopID,
                        Quantity = pao.Quantity,
                        // ProductAttribute = pa.Name
                    }).ToList();
                    item.Attributes = attributes;

                    var attribute = attributes.FirstOrDefault(x => x.Name == pitem.AttributeDescription);
                    if (attribute != null)
                    {
                        item.AttributeDescription     = attribute.ProductAttribute + ": " + attribute.Name;
                        item.ProductAttributeOptionID = attribute.ID;
                        if (item.QuantityType == ProductQuantityType.CheckByProductOptions)
                        {
                            item.QuantityResource = attribute.Quantity;
                        }
                        if (!string.IsNullOrEmpty(attribute.OverridenSku))
                        {
                            item.SKU = attribute.OverridenSku;
                        }
                        if (attribute.OverridenPrice.HasValue)
                        {
                            item.Price     = attribute.OverridenPrice.Value;
                            item.UnitPrice = item.Price * item.Quantity;
                        }
                    }
                    else
                    {
                        item.SelectedAttributeNotAvaliable = true;//mark as not avaliable
                    }
                }
                if ((item.QuantityType == ProductQuantityType.CheckByProduct ||
                     item.QuantityType == ProductQuantityType.CheckByProductOptions
                     ) && item.QuantityResource < item.Quantity)
                {
                    item.IsHaveNotQuantity = true;
                }
                item.UnitPrice    = item.Price * item.Quantity;
                item.PriceStr     = ShoppingService.FormatPrice(item.Price);
                item.UnitPriceStr = ShoppingService.FormatPrice(item.UnitPrice);
            }
            return(data);
        }
        public static ShoppingCartItemModel GetShoppingCartItemByID(int ID)
        {
            var item = (from sci in LS.CurrentEntityContext.ShoppingCartItems
                        join ps in LS.CurrentEntityContext.ProductShopMap
                        on sci.ProductShopID equals ps.ID
                        join p in LS.CurrentEntityContext.Products
                        on ps.ProductID equals p.ID
                        where sci.UserID == LS.CurrentUser.ID &&
                        sci.ID == ID
                        //join psao in LS.CurrentEntityContext.ProductAttributeOptions
                        //on sci.ProductAttributeOptionID equals psao.ID
                        select new ShoppingCartItemModel()
            {
                ID = sci.ID,
                Name = p.Name,
                Price = ps.Price,
                SKU = p.SKU,
                Image = p.Image,
                ProductShopID = ps.ID,
                Quantity = sci.Quantity,
                ShopID = ps.ShopID,
                UnitPrice = ps.Price * sci.Quantity,
                ProductAttributeOptionID = sci.ProductAttributeOptionID,
                AttributeDescription = "",
                CategoryID = p.CategoryID,
                MeasureUnit = p.MeasureUnit,
                MeasureUnitStep = p.MeasureUnitStep,
            }).FirstOrDefault();

            if (item != null)
            {
                if (item.ProductAttributeOptionID > 0)
                {
                    var attribute = (from pao in LS.CurrentEntityContext.ProductAttributeOptions
                                     //  join pa in LS.CurrentEntityContext.ProductAttributes
                                     //on pao.ProductAttributeID equals pa.ID
                                     where pao.ID == item.ProductAttributeOptionID
                                     select new ProductAttributeOptionModel()
                    {
                        ID = pao.ID,
                        Name = pao.Name,
                        OverridenPrice = pao.OverridenPrice,
                        OverridenSku = pao.OverridenSku,
                        // ProductAttributeID = pao.ProductAttributeID,
                        ProductShopID = pao.ProductShopID,
                        Quantity = pao.Quantity,
                        // ProductAttribute = pa.Name
                    }).FirstOrDefault();
                    if (attribute != null)
                    {
                        item.AttributeDescription = attribute.ProductAttribute + ": " + attribute.Name;
                        if (!string.IsNullOrEmpty(attribute.OverridenSku))
                        {
                            item.SKU = attribute.OverridenSku;
                        }
                        if (attribute.OverridenPrice.HasValue)
                        {
                            item.Price     = attribute.OverridenPrice.Value;
                            item.UnitPrice = item.Price * item.Quantity;
                        }
                    }
                }
                item.PriceStr     = ShoppingService.FormatPrice(item.Price);
                item.UnitPriceStr = ShoppingService.FormatPrice(item.UnitPrice);
            }
            return(item);
        }