public ActionResult OrderRefund(int ID)
        {
            if (CurrentShop == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.ShopNotFound") }));
            }
            var order = _db.Orders.FirstOrDefault(x => x.ID == ID && x.ShopID == CurrentShop.ID);

            if (order == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderNotFound") }));
            }
            if (order.OrderStatus != OrderStatus.Delivered)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderNotDeliveredYet") }));
            }
            // order.OrderStatus = OrderStatus.Refunded;
            order.RefundOn     = DateTime.Now;
            order.RefundAmount = order.Total;
            _db.SaveChanges();
            if (order.PaymentMethod == PaymentMethod.Credit)
            {
                ShoppingService.RefundOrder(order);
            }
            return(Json(new { result = "ok", message = RP.S("Member.OrderChanged.OrderRefounded") }));
        }
        public ActionResult SendPasswordAjx(string Model, string InvisibleCaptchaValue, string CaptchaValue)
        {
            if (!CaptchaController.IsCaptchaValid(CaptchaValue) || !CaptchaController.IsInvisibleCaptchaValid(InvisibleCaptchaValue))
            {
                ModelState.AddModelError(string.Empty, RP.S("Errors.Common.CaptchaWrong"));
                return(Json(new { result = "error", message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));
            }

            if (ModelState.IsValid)
            {
                User u = _db.Users.FirstOrDefault(r => r.Email == Model);
                if (u == null)
                {
                    ModelState.AddModelError("", RP.S("Errors.Account.UserNameIncorrect"));
                    return(Json(new { result = "error", message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));
                }
                else
                {
                    var messService = new MessageService(_db);
                    messService.SendUserPasswordEmailToUser(u);
                    ModelState.AddModelError("", RP.S("Info.Account.PasswordSended"));
                    return(Json(new { result = "error", message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));
                }
            }
            return(Json(new { result = "error", message = ModelState.Values.Select(x => new { Value = x.Value != null ? x.Value.AttemptedValue : "", errors = x.Errors.Select(y => y.ErrorMessage) }) }));
        }
        public ActionResult OrderPartialRefund(int ID, decimal Amount)
        {
            if (CurrentShop == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.ShopNotFound") }));
            }
            if (Amount <= 0)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.AmountMustBeGreatenThanZero") }));
            }
            var order = _db.Orders.FirstOrDefault(x => x.ID == ID && x.ShopID == CurrentShop.ID);

            if (order == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderNotFOund") }));
            }
            if (order.OrderStatus != OrderStatus.Delivered)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderNotDeliveredYet") }));
            }
            if ((Amount + order.RefundAmount) > (order.Total))
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.AmountMustBeLessThanOrderTotal") }));
            }
            // order.OrderStatus = OrderStatus.PartialRefunded;
            order.RefundOn      = DateTime.Now;
            order.RefundAmount += Amount;
            _db.SaveChanges();
            if (order.PaymentMethod == PaymentMethod.Credit)
            {
                ShoppingService.PartialRefundOrder(order);
            }
            return(Json(new { result = "ok", message = RP.S("Member.OrderChanged.PartialRefoundMaked") }));
        }
        public ActionResult ReadWorkTimes()
        {
            if (CurrentShop == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.ShopNotFound") }));
            }
            var list = _db.ShopWorkTimes.Where(x => x.ShopID == CurrentShop.ID &&
                                               !x.IsSpecial).ToList();

            foreach (var en in Enum.GetValues(typeof(DayOfWeek)))
            {
                if (!list.Any(x => x.Day == (DayOfWeek)en))
                {
                    var time = GetWorkTime((DayOfWeek)en);
                    if ((int)en == 6)
                    {
                        time        = GetWorkTime((DayOfWeek)en, 1140, 1440);
                        time.Active = false;
                    }
                    else if ((int)en == 5)
                    {
                        time = GetWorkTime((DayOfWeek)en, 480, 840);
                    }

                    _db.ShopWorkTimes.Add(time);
                    _db.SaveChanges();
                    list.Add(time);
                }
            }

            return(Json(new { result = "ok", data = list }));
        }
        public ActionResult WorkTimeChange(ShopWorkTime time)
        {
            if (CurrentShop == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.ShopNotFound") }));
            }

            var CurTime = _db.ShopWorkTimes.FirstOrDefault(x => x.ShopID == CurrentShop.ID &&
                                                           x.Day == time.Day &&
                                                           !x.IsSpecial);

            if (CurTime != null)      //already exist
            {
                CurTime.Active   = time.Active;
                CurTime.TimeFrom = time.TimeFrom;
                CurTime.TimeTo   = time.TimeTo;
                _db.SaveChanges();
            }
            else
            {      //create new day
                time.ShopID    = CurrentShop.ID;
                time.IsSpecial = false;
                time.Date      = DateTime.Now;
                _db.ShopWorkTimes.Add(time);
                _db.SaveChanges();
                CurTime = time;
            }
            return(Json(new { result = "ok", data = CurTime }));
        }
Esempio n. 6
0
 public ActionResult RemoveNotMappedShortSku()
 {
     if (CurrentShop != null)
     {
         var ShopID     = CurrentShop.ID;
         var sqlcommand = string.Format("DELETE FROM [ProductSkuMaps] WHERE [ShopID] = {0} AND ([ProductSKU] IS NULL OR [ProductSKU] = N'')", ShopID);
         var sqlsay     = _db.Database.ExecuteSqlCommand(sqlcommand);
         return(Content(RP.S("Member.ProductSkuMap.Removed") + " SQL: " + sqlcommand + " SQLRETURN: " + sqlsay.ToString()));
     }
     return(Content("Shop not found"));
 }
        public ActionResult OrderConfirm(int ID)
        {
            if (CurrentShop == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.ShopNotFound") }));
            }
            var order = _db.Orders.FirstOrDefault(x => x.ID == ID && x.ShopID == CurrentShop.ID);

            if (order == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderNotFound") }));
            }
            if (order.OrderStatus != OrderStatus.New && order.OrderStatus != OrderStatus.Paid)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderAlreadyProcessed") }));
            }
            //check if member accept all items
            OrderItemStatus acceptedItemStatus = OrderItemStatus.Accepted;
            OrderItemStatus changedItemStatus  = OrderItemStatus.Changed;
            var             any = _db.OrderItems.Any(x => x.OrderID == order.ID && x.OrderItemStatus != acceptedItemStatus && x.OrderItemStatus != changedItemStatus);

            if (any)  //member missing some products
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.YouMustAcceptAllItemsFirst") }));
            }
            if (order.PaymentMethod == PaymentMethod.Credit)
            {
                if (order.OrderStatus == OrderStatus.Paid)
                {
                    order.OrderStatus = OrderStatus.Accepted;
                    _db.SaveChanges();
                }
                else
                {
                    //run paid procedure
                    order.PayedOn = DateTime.Now;
                    //
                    order.OrderStatus = OrderStatus.Accepted;
                    _db.SaveChanges();
                    //and accept
                    // return Json(new { result = "error", message = "Oreder not paid, yet" });
                }
            }
            else
            {
                order.OrderStatus = OrderStatus.Accepted;  //ShoppingService.AcceptedOrderStatus();
                order.PayedOn     = DateTime.Now;
                _db.SaveChanges();
            }

            return(Json(new { result = "ok", message = RP.S("Member.OrderChanged.Confirmed") }));
        }
        public void Run(string SystemName)
        {
            MethodInfo method = typeof(PlanedProcessTask).GetMethod(SystemName, BindingFlags.Public | BindingFlags.Static);

            if (method != null)
            {
                method.Invoke(null, new object[] { SystemName });
            }
            else
            {
                throw new Exception(RP.S("Admin.PlanedTask.MethodNotFound"));
            }
        }
Esempio n. 9
0
        public ActionResult MoveProducts(int from, int to)
        {
            if (from != to)
            {
                var products = _db.Products.Where(x => x.CategoryID == from).ToList();
                foreach (var p in products)
                {
                    p.CategoryID = to;
                }
                _db.SaveChanges();
                return(Json(new { message = RP.S("Admin.Category.ProductsMoved") }));
            }

            return(Json(new { message = RP.S("Admin.Category.ItsSameCategory") }));
        }
 public void Execute()
 {
     using (Db _db = new Db())
     {
         var plans = _db.PlanedTasks.Where(x => !x.Started && x.Active).ToList();
         foreach (var action in plans)
         {
             action.Started   = true;
             action.Message   = RP.S("Admin.PlanedTask.Started");
             action.LastStart = DateTime.UtcNow;
             action.LastEnd   = null;
             _db.SaveChanges();
             StartNewInThread(action.SystemName);
         }
     }
 }
        public ActionResult OrderReject(int ID)
        {
            if (CurrentShop == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.ShopNotFound") }));
            }
            var order = _db.Orders.FirstOrDefault(x => x.ID == ID && x.ShopID == CurrentShop.ID);

            if (order == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderNotFound") }));
            }
            if (order.OrderStatus != OrderStatus.New && order.OrderStatus != OrderStatus.Paid)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderAlreadyProcessed") }));
            }
            order.OrderStatus = OrderStatus.Rejected; //ShoppingService.RejectedOrderStatus();
            _db.SaveChanges();
            // add to cart
            var             items         = _db.OrderItems.Where(x => x.OrderID == order.ID).ToList();
            OrderItemStatus outItemStatus = OrderItemStatus.OutOfStock;

            foreach (var oi in items)
            {
                if (oi.OrderItemStatus != outItemStatus && oi.Quantity > 0)
                {
                    ShoppingCartService.AddToCart(order.UserID, new ShoppingCartItem()
                    {
                        ProductAttributeOptionID = oi.ProductAttributeOptionID,
                        ProductShopID            = oi.ProductShopID,
                        Quantity = oi.Quantity,
                        ShopID   = order.ShopID,
                    });
                }
            }
            //send email
            var messService = new MessageService(_db);
            var user        = _db.Users.FirstOrDefault(x => x.ID == order.UserID);

            var shop = _db.Shops.FirstOrDefault(x => x.ID == order.ShopID);

            messService.OrderCanceledSmsToUser(order, user);
            messService.OrderCanceledEmailToUser(order, shop);
            return(Json(new { result = "ok", message = RP.S("Member.OrderChange.Rejected") }));
        }
        public ActionResult OrderDelivered(int ID)
        {
            if (CurrentShop == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.ShopNotFound") }));
            }
            var order = _db.Orders.FirstOrDefault(x => x.ID == ID && x.ShopID == CurrentShop.ID);

            if (order == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderNotFound") }));
            }
            if (order.OrderStatus != OrderStatus.Sent)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.YouMustAcceptOrderFirst") }));
            }
            order.OrderStatus = OrderStatus.Delivered; //ShoppingService.DeliveredOrderStatus();//canceled
            _db.SaveChanges();
            return(Json(new { result = "ok", message = RP.S("Member.OrderChanged.OrderMarkedAsDelivered") }));
        }
        public ActionResult OrderSent(int ID)
        {
            if (CurrentShop == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.ShopNotFound") }));
            }
            var order = _db.Orders.FirstOrDefault(x => x.ID == ID && x.ShopID == CurrentShop.ID);

            if (order == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderNotFound") }));
            }
            if (order.OrderStatus != OrderStatus.Accepted)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.YouMustAcceptOrderFirst") }));
            }
            order.OrderStatus = OrderStatus.Sent; //ShoppingService.SentOrderStatus();//
            order.SentOn      = DateTime.Now;
            _db.SaveChanges();
            return(Json(new { result = "ok", message = RP.S("Member.OrderChanged.Sended") }));
        }
        public void StartNewInThread(string SystemName)
        {
            System.Threading.Tasks.Task.Factory.StartNew(() =>
            {
                string message = RP.S("Admin.PlanedTask.Success");
                int?progress   = 100;
                try
                {
                    Run(SystemName);
                }
                catch (Exception e)
                {
                    message       = RP.S("Admin.PlanedTask.Error");
                    var exception = e;
                    while (exception != null)
                    {
                        message  += " " + exception.Message + Environment.NewLine + exception.StackTrace + " ";
                        exception = exception.InnerException;
                    }
                    progress = null;
                }
                using (Db _db = new Db())
                {
                    var currentTask = _db.PlanedTasks.FirstOrDefault(x => x.SystemName == SystemName);
                    if (currentTask != null)
                    {
                        currentTask.Active  = false;
                        currentTask.Started = false;

                        currentTask.Message = message;
                        if (progress.HasValue)
                        {
                            currentTask.PercentProgress = progress.Value;
                            currentTask.LastEnd         = DateTime.UtcNow;
                        }
                        _db.SaveChanges();
                    }
                }
            });
        }
        public void Execute()
        {
            CultureInfo culture = new CultureInfo("he-IL");

            culture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
            System.Threading.Thread.CurrentThread.CurrentCulture   = culture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = culture;
            using (Db _db = new Db())
            {
                DateTime date = DateTime.Now.AddMinutes(-10);

                var orders = _db.Orders.Where(x => x.OrderStatus == OrderStatus.New &&
                                              (x.PaymentMethod == PaymentMethod.Credit || x.PaymentMethod == PaymentMethod.CreditShopOwner) &&
                                              x.CreateOn < date).ToList();
                if (orders.Count > 0)
                {
                    var messService = new MessageService(_db);
                    foreach (var order in orders)
                    {
                        messService.SendOrderUserCantPayToUser(order);
                        var shop = ShoppingService.GetShopByID(order.ShopID);
                        messService.SendOrderUserCantPayToMember(order, shop);
                        messService.SendOrderUserCantPayToAdmin(order);
                        order.OrderStatus = OrderStatus.Canceled;

                        var logrecord = new OrderNote()
                        {
                            CreateDate = DateTime.Now,
                            OrderID    = order.ID,
                            Note       = RP.S("Task.Order.Canceled.NotPaid"),
                        };
                        _db.OrderNotes.Add(logrecord);
                        // messService.OrderCanceledEmailToUser(order); //no need, already sended
                    }
                    _db.SaveChanges();
                }
            }
        }
        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();
            //}
        }
        public ActionResult SaveCell(int ID, string Field, string Value, string OrderNote)
        {
            //if(string.IsNullOrEmpty(OrderNote))
            //{
            //    return Json(new { result = "error", message = "Note required", value = Value });
            //}
            var order = _db.Orders.FirstOrDefault(x => x.ID == ID);

            if (order != null)
            {
                var property = order.GetType().GetProperty(Field);
                if (property != null)
                {
                    var oldValue = property.GetValue(order);
                    order.SetValueFromString(Field, Value);
                    var newValue    = property.GetValue(order);
                    var oldValueStr = oldValue.ToString();
                    var newValueStr = newValue.ToString();
                    if (property.PropertyType.Name == "Double")
                    {
                        oldValueStr = ((decimal)oldValue).ToString("0.00");
                        newValueStr = ((decimal)newValue).ToString("0.00");
                    }

                    if (Field != "Total" && Field != "TotalCash")
                    {
                        //fix totals
                        if (order.ShippingMethod == ShippingMethod.Manual)
                        {
                            order.ShipCost = 0;
                        }
                        order.Total = order.SubTotal + order.ShipCost + order.Fee - order.TotalDiscountAmount;
                    }

                    if (newValueStr != oldValueStr)
                    {
                        _db.SaveChanges();
                        //adding note
                        if (string.IsNullOrEmpty(OrderNote))
                        {
                            OrderNote = RP.S("Member.OrderNote.DefaultMessage");
                        }
                        var note = new OrderNote()
                        {
                            CreateDate = DateTime.Now,
                            Field      = RP.M("Order", Field),
                            OrderID    = order.ID,
                            Note       = OrderNote,
                            NewValue   = newValueStr,
                            OldValue   = oldValueStr
                        };
                        _db.OrderNotes.Add(note);
                        _db.SaveChanges();

                        return(Json(new { result = "ok", value = Value }));
                    }
                    return(Json(new { result = "error", message = "Value not changed", value = Value }));
                }
                return(Json(new { result = "error", message = "no property", value = Value }));
            }
            return(Json(new { result = "error", message = "not found", value = Value }));
        }
Esempio n. 18
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 ActionResult OrderMissing(int ID)
        {
            if (CurrentShop == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.ShopNotFound") }));
            }
            var order = _db.Orders.FirstOrDefault(x => x.ID == ID && x.ShopID == CurrentShop.ID);

            if (order == null)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderNotFound") }));
            }
            if (order.OrderStatus != OrderStatus.New && order.OrderStatus != OrderStatus.Paid)
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.OrderAlreadyProcessed") }));
            }
            OrderItemStatus outItemStatus     = OrderItemStatus.OutOfStock;
            OrderItemStatus changedItemStatus = OrderItemStatus.Changed;
            var             any = _db.OrderItems.Any(x => x.OrderID == order.ID && (x.OrderItemStatus == outItemStatus
                                                                                    ||
                                                                                    x.OrderItemStatus == changedItemStatus)
                                                     );

            if (!any)  //check out of stock items
            {
                return(Json(new { result = "error", message = RP.S("Member.Error.YouDontHaveChangedProducts") }));
            }
            order.OrderStatus = OrderStatus.Rejected;  //ShoppingService.RejectedOrderStatus();//canceled
            _db.SaveChanges();
            // add to cart
            var items = _db.OrderItems.Where(x => x.OrderID == order.ID).ToList();

            foreach (var oi in items)
            {
                if (oi.OrderItemStatus != outItemStatus && oi.Quantity > 0)
                {
                    ShoppingCartService.AddToCart(order.UserID, new ShoppingCartItem()
                    {
                        ProductAttributeOptionID = oi.ProductAttributeOptionID,
                        ProductShopID            = oi.ProductShopID,
                        Quantity = oi.Quantity,
                        ShopID   = order.ShopID,
                    });
                }
            }
            //send email
            var messService = new MessageService(_db);

            messService.SendOrderChangedEmailToUser(order, items
                                                    .Where(x => x.OrderItemStatus == OrderItemStatus.Changed
                                                           ).ToList(),
                                                    items
                                                    .Where(x => x.OrderItemStatus == OrderItemStatus.OutOfStock
                                                           ).ToList()
                                                    );
            var user = _db.Users.FirstOrDefault(x => x.ID == order.UserID);

            messService.SendOrderChangedSmsToUser(order, user);

            //
            return(Json(new { result = "ok", message = RP.S("Member.OrderChanged.ProductsReturnedToClientOrderRejected") }));
        }
        public static void ProductAdminImport(string SystemName)
        {
            using (Db _db = new Db())
            {
                var currentTask = _db.PlanedTasks.FirstOrDefault(x => x.SystemName == SystemName);
                if (currentTask != null)
                {
                    currentTask.Message         = RP.S("Admin.PlanedTask.InProgress");
                    currentTask.PercentProgress = 10;
                    _db.SaveChanges();

                    if (string.IsNullOrEmpty(currentTask.ProcessData))
                    {
                        return;
                    }
                    #region Import

                    string FolderPath = HostingEnvironment.MapPath("~/App_Data/Import/");
                    if (!Directory.Exists(FolderPath))
                    {
                        Directory.CreateDirectory(FolderPath);
                    }
                    //1
                    string FileName = "";
                    string FilePath = "";

                    FileName = Path.GetFileName(currentTask.ProcessData);
                    FilePath = Path.Combine(FolderPath, FileName);
                    if (!File.Exists(FilePath))
                    {
                        throw new Exception(RP.S("Admin.Product.Import.FileNotFound"));
                    }
                    var existingFile = new FileInfo(FilePath);
                    var all          = new List <Dictionary <int, string> >();
                    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);
                                    }
                                }
                            }
                        }
                    }
                    //Dictionary<string, string> skuImageMap = new Dictionary<string, string>();
                    //Dictionary<int, string> idImageMap = new Dictionary<int, string>();
                    var productforInsert         = new List <Product>();
                    var productForUpdate         = new List <Product>();
                    var productForUpdateVariable = new List <ProductVariable <Product> >();
                    var productForDelete         = new List <Product>();
                    var productsList             = _db.Products
                                                   .OrderBy(x => x.ID)
                                                   .Select(x => new
                    {
                        x.ID,
                        x.SKU,
                        x.IgnoreOnImport
                        ,
                        x.Name,
                        x.IsKosher,
                        x.KosherType,
                        x.Capacity,
                        x.MeasureUnit,

                        x.Components,
                        x.ProductMeasureID,
                        x.UnitsPerPackage,
                        x.CategoryID,
                        x.ProductManufacturerID,
                        x.NoTax,
                        // x.RecomendedPrice
                        // ,
                        x.MadeCoutry,
                        x.SoldByWeight,
                        x.ShortDescription,
                        x.FullDescription
                        ,
                        x.ProductShopOptions,
                        x.ContentUnitMeasureID,
                        x.ContentUnitPriceMultiplicator
                    })         // optimization
                                                   .ToList().ToDictionary(x => x.SKU);
                    // var replaceSkuMap = _db.ProductSkuMaps.AsNoTracking().ToList();
                    var                       decimalSeparator             = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
                    var                       AllCategories                = LS.Get <Category>(); //get category cache
                    var                       AllManufacturers             = LS.Get <Manufacturer>();
                    PIsheme                   sheme                        = new PIsheme();
                    int                       lineNum                      = 1;
                    StringBuilder             errors                       = new StringBuilder();
                    StringBuilder             lastEmpty                    = new StringBuilder();
                    List <ProcessError>       processErrors                = new List <ProcessError>();
                    bool                      needCreateCategoryIfNotExist = false;
                    Dictionary <string, bool> processed                    = new Dictionary <string, bool>();

                    var allMeasures = LS.Get <Measure>();
                    foreach (var s in all)
                    {
                        lineNum++;
                        if (lineNum == 2)
                        {
                            continue;
                        }                              //skip second row (excell numeration)
                        if (s.Count < 17)
                        {
                            processErrors.Add(new ProcessError()
                            {
                                LineNum = lineNum, Message = string.Format(RP.S("Admin.Product.Import.Error.WrongColumnCount-LineNume{0}"), lineNum)
                            });
                            errors.AppendLine(string.Format(RP.S("Admin.Product.Import.Error.WrongColumnCount-LineNume{0}"), lineNum));
                            continue;
                        }
                        string actionFlag = s[sheme.FlagOperation];
                        if (string.IsNullOrEmpty(actionFlag))
                        {
                            actionFlag = "1";
                        }
                        bool isInsert = false;
                        bool isDelete = actionFlag == "0";
                        bool isInsertUpdateIfNotDest = actionFlag == "1"; // insert or add if before empty or null or default;
                        bool isUpdateIfSource        = actionFlag == "2"; // update only if not null empty or default
                        bool isFullUpdate            = actionFlag == "3"; // update only if not null empty or default
                        if (!isDelete)
                        {
                            isInsert = true;
                        }
                        long test           = 0;
                        bool validRow       = true;
                        bool SKUorNameEmpty = false;
                        if (s[sheme.SKU] == null)
                        {
                            SKUorNameEmpty = true;
                        }
                        else if (s[sheme.SKU].ToString().Trim() == "")
                        {
                            SKUorNameEmpty = true;
                        }
                        else if (s[sheme.Name] == null)
                        {
                            SKUorNameEmpty = true;
                        }
                        else if (s[sheme.Name] == "")
                        {
                            SKUorNameEmpty = true;
                        }
                        else if (!long.TryParse(s[sheme.SKU].ToString(), out test))
                        {
                            //  SKUorNameEmpty = true;
                        }

                        if (SKUorNameEmpty)
                        {
                            processErrors.Add(new ProcessError()
                            {
                                LineNum = lineNum
                                ,
                                Message = string.Format(RP.S("Admin.Product.Import.Error.SKUorNameEmpty-LineNume{0}"), lineNum)
                            });

                            lastEmpty.AppendLine(string.Format(RP.S("Admin.Product.Import.Error.SKUorNameEmpty-LineNume{0}"), lineNum));
                            continue;
                        }
                        //check SKU code
                        var sku = s[sheme.SKU].ToString().Trim();
                        sku = Regex.Replace(sku, "[^.0-9]", "");
                        var fieldsToUpdate = new List <string>();

                        //Ignore numbers in s[sheme.MeasureUnit]
                        s[sheme.MeasureUnit] = Regex.Replace(s[sheme.MeasureUnit], "[0-9]", "");
                        //check map table
                        //  var replaceTo = replaceSkuMap.FirstOrDefault(x => x.ShortSKU == sku);
                        //if (replaceTo != null)
                        // {
                        //     sku = replaceTo.ProductSKU;
                        // }
                        //check if not repeated row
                        if (processed.ContainsKey(sku))
                        {
                            validRow = false;
                            processErrors.Add(new ProcessError()
                            {
                                LineNum = lineNum
                                ,
                                SKU = sku
                                ,
                                Message = string.Format(RP.S("Admin.Product.Import.Error.SKUAlreadyProcessed-LineNume{0}"), lineNum)
                            });
                            errors.AppendLine(string.Format(RP.S("Admin.Product.Import.Error.SKUAlreadyProcessed-LineNume{0}"), lineNum));

                            continue;
                        }
                        processed[sku] = true;

                        if (sku.Length == 13 || sku.Length == 12)
                        {
                            // 036000291454x

                            int codelength = 12;
                            int startFrom1 = 1;
                            int startFrom2 = 0;
                            if (sku.Length == 12)
                            {
                                // 03600029145x
                                codelength = 11;
                                startFrom1 = 0;
                                startFrom2 = 1;
                            }
                            int odd   = 0;
                            int even  = 0;
                            int check = 0;
                            int.TryParse(sku[codelength].ToString(), out check);

                            int tmp = 0;
                            for (int i = startFrom1; i < codelength; i = i + 2)
                            {
                                int.TryParse(sku[i].ToString(), out tmp);
                                odd += tmp;
                            }
                            odd = odd * 3;
                            for (int i = startFrom2; i < codelength; i = i + 2)
                            {
                                int.TryParse(sku[i].ToString(), out tmp);
                                even += tmp;
                            }
                            int sum    = odd + even;
                            int module = sum % 10;
                            int mustBe = (10 - module) % 10;
                            if (mustBe != check)
                            {
                                //validRow = false;
                                processErrors.Add(new ProcessError()
                                {
                                    LineNum = lineNum
                                    ,
                                    SKU = sku
                                    ,
                                    Message = string.Format(RP.S("Admin.Product.Import.Error.SKUnotValid-LineNume{0}"), lineNum)
                                });
                                errors.AppendLine(string.Format(RP.S("Admin.Product.Import.Error.SKUnotValid-LineNume{0}"), lineNum));
                            }
                        }


                        if (lastEmpty.Length > 0)
                        {
                            errors.AppendLine(lastEmpty.ToString());
                            lastEmpty.Clear();
                        }
                        //var priceStr = s[sheme.Price].ToString().Trim();
                        //if (priceStr == "")
                        //{
                        //    priceStr = "0";
                        //}
                        //else
                        //{
                        //    fieldsToUpdate.Add("RecomendedPrice");
                        //}
                        if (!string.IsNullOrEmpty(s[sheme.Name].ToString()))
                        {
                            fieldsToUpdate.Add("Name");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.IsKosher].ToString()))
                        {
                            fieldsToUpdate.Add("IsKosher");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.KosherType].ToString()))
                        {
                            fieldsToUpdate.Add("KosherType");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.MadeCountry]))
                        {
                            fieldsToUpdate.Add("MadeCoutry");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.Capacity].ToString()))
                        {
                            fieldsToUpdate.Add("Capacity");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.MeasureUnit].ToString()))
                        {
                            fieldsToUpdate.Add("MeasureUnit");
                            fieldsToUpdate.Add("ProductMeasureID");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.Components].ToString()))
                        {
                            fieldsToUpdate.Add("Components");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.Tax].ToString()))
                        {
                            fieldsToUpdate.Add("NoTax");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.SoldByWeight].ToString()))
                        {
                            fieldsToUpdate.Add("SoldByWeight");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.ShortDescription].ToString()))
                        {
                            fieldsToUpdate.Add("ShortDescription");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.FullDescription].ToString()))
                        {
                            fieldsToUpdate.Add("FullDescription");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.ProductOptions].ToString()))
                        {
                            fieldsToUpdate.Add("ProductShopOptions");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.UnitPerPackage].ToString()))
                        {
                            fieldsToUpdate.Add("UnitPerPackage");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.Manufacturer].ToString()))
                        {
                            fieldsToUpdate.Add("ProductManufacturerID");
                            fieldsToUpdate.Add("DisplayOrder");
                        }
                        if (!string.IsNullOrEmpty(s[sheme.SubCategory].ToString()))
                        {
                            fieldsToUpdate.Add("CategoryID");
                        }

                        if (!string.IsNullOrEmpty(s[sheme.UnitOfMeasure].ToString()) &&
                            !string.IsNullOrEmpty(s[sheme.QuantityUnitOfMeasure].ToString()))
                        {
                            fieldsToUpdate.Add("ContentUnitPriceMultiplicator");
                            fieldsToUpdate.Add("ContentUnitMeasureID");
                        }



                        var product = new Product()
                        {
                            SKU      = sku,
                            Name     = s[sheme.Name].ToString().Trim(),
                            IsKosher = s[sheme.IsKosher].ToString().Trim() == "1" ||
                                       s[sheme.IsKosher].ToString().Trim() == "true" ||
                                       s[sheme.IsKosher].ToString().Trim() == "True" ||
                                       !string.IsNullOrEmpty(s[sheme.KosherType].ToString().Trim()),
                            KosherType = s[sheme.KosherType].ToString().Trim(),

                            Capacity    = s[sheme.Capacity].ToString().Trim(),
                            MeasureUnit = s[sheme.MeasureUnit].ToString().Trim() == "" ? null : s[sheme.MeasureUnit].ToString().Trim(),
                            // ProductMeasureID = allMeasures
                            Components = s[sheme.Components].ToString().Trim(),
                            // Manufacturer = s[sheme.Manufacturer].ToString().Trim(),
                            NoTax              = s[sheme.Tax].ToString().Trim() == "1" || s[sheme.Tax].ToString().Trim() == "true" || s[sheme.Tax].ToString().Trim() == "True",
                            SoldByWeight       = s[sheme.SoldByWeight].ToString().Trim() == "1" || s[sheme.SoldByWeight].ToString().Trim() == "true" || s[sheme.SoldByWeight].ToString().Trim() == "True",
                            ShortDescription   = s[sheme.ShortDescription].ToString().Trim(),
                            FullDescription    = s[sheme.FullDescription].ToString().Trim(),
                            ProductShopOptions = s[sheme.ProductOptions].ToString().Trim(),
                            MadeCoutry         = s[sheme.MadeCountry].Trim()
                        };

                        PrepareContentUnitMeasure(s, sheme, product);
                        //Searching for measure matching
                        var firstMatchedMeasure = allMeasures.FirstOrDefault(x => x.VariantList.Contains(s[sheme.MeasureUnit]));
                        if (firstMatchedMeasure != null)
                        {
                            product.ProductMeasureID = firstMatchedMeasure.ID;
                        }
                        //if (!string.IsNullOrEmpty(priceStr))
                        //{
                        //    decimal price = 0;
                        //    bool valid = decimal.TryParse(priceStr.Replace(".", decimalSeparator).Replace(",", decimalSeparator)
                        //         , out price);

                        //    product.RecomendedPrice = price;
                        //    if (!valid)
                        //    {
                        //        validRow = false;
                        //        processErrors.Add(new ProcessError()
                        //        {
                        //            LineNum = lineNum
                        //            ,
                        //            SKU = sku,
                        //            Message = string.Format(RP.S("Admin.Product.Import.Error.PriceNotValid-LineNume{0}"), lineNum)
                        //        });
                        //        errors.AppendLine(string.Format(RP.S("Admin.Product.Import.Error.PriceNotValid-LineNume{0}"), lineNum));
                        //    }
                        //}

                        //step for quantity change
                        if (!string.IsNullOrEmpty(s[sheme.UnitPerPackage]))
                        {
                            decimal step  = 0;
                            bool    valid = decimal.TryParse(s[sheme.UnitPerPackage].ToString().Trim(), out step);
                            if (step > 0)
                            {
                                product.MeasureUnitStep = step;
                            }
                            product.UnitsPerPackage = step;

                            if (!valid)
                            {
                                validRow = false;
                                processErrors.Add(new ProcessError()
                                {
                                    LineNum = lineNum
                                    ,
                                    SKU     = sku,
                                    Message = string.Format(RP.S("Admin.Product.Import.Error.UnitPerPackageNotValidNumber-LineNume{0}"), lineNum)
                                });
                                errors.AppendLine(string.Format(RP.S("Admin.Product.Import.Error.UnitPerPackageNotValidNumber-LineNume{0}"), lineNum));
                            }
                        }
                        var manuf = s[sheme.Manufacturer].ToString().Trim();
                        if (!string.IsNullOrEmpty(manuf))
                        {
                            var man = AllManufacturers.FirstOrDefault(x => x.Name != null && x.Name.ToLower() == manuf.ToLower());
                            if (man == null)
                            {
                                man = new Manufacturer()
                                {
                                    DisplayOrder = 0,
                                    Published    = true,
                                    Name         = manuf
                                };
                                _db.Manufacturers.Add(man);
                                _db.SaveChanges();
                                AllManufacturers.Add(man);
                            }
                            if (man != null)
                            {
                                product.ProductManufacturerID = man.ID;
                                product.DisplayOrder          = man.DisplayOrder;
                            }
                        }
                        //category
                        //var parentcat = AllCategories.FirstOrDefault(x => x.Name == s[sheme.Category].ToString() && x.ParentCategoryID == 0);
                        //if (parentcat == null)
                        //{
                        //    parentcat = new Category()
                        //    {
                        //        DisplayOrder = 500,
                        //        Name = s[sheme.Category],
                        //        ParentCategoryID=0,
                        //        Published=true,
                        //    };
                        //    _db.Categories.Add(parentcat);
                        //    _db.SaveChanges();
                        //    AllCategories.Add(parentcat);
                        //}
                        if (validRow && !string.IsNullOrEmpty(s[sheme.SubCategory].ToString().Trim()))
                        {
                            var cat = AllCategories.FirstOrDefault(x => x.Name == s[sheme.SubCategory].ToString().Trim());
                            if (cat == null &&
                                needCreateCategoryIfNotExist)
                            {
                                cat = new Category()
                                {
                                    DisplayOrder     = 500,
                                    Name             = s[sheme.SubCategory].ToString().Trim(),
                                    ParentCategoryID = 0,
                                    Published        = true,
                                };
                                _db.Categories.Add(cat);
                                _db.SaveChanges();
                                AllCategories.Add(cat);
                            }
                            if (cat != null)
                            {
                                product.CategoryID = cat.ID;
                            }
                        }
                        if (!isDelete)
                        {
                            fieldsToUpdate.Add("Deleted");
                        }
                        if (isDelete || validRow)
                        {
                            if (productsList.ContainsKey(sku))
                            {
                                var oldProduct = productsList[sku];
                                product.ID = oldProduct.ID;


                                if (isInsertUpdateIfNotDest)
                                {
                                    #region Flag 1 (Update if Destination null empty or default)
                                    fieldsToUpdate.Clear();
                                    //if (oldProduct.RecomendedPrice == 0)
                                    //{
                                    //    fieldsToUpdate.Add("RecomendedPrice");
                                    //}
                                    if (string.IsNullOrEmpty(oldProduct.Name))
                                    {
                                        fieldsToUpdate.Add("Name");
                                    }
                                    if (!oldProduct.IsKosher)
                                    {
                                        fieldsToUpdate.Add("IsKosher");
                                    }
                                    if (string.IsNullOrEmpty(oldProduct.KosherType))
                                    {
                                        fieldsToUpdate.Add("KosherType");
                                    }
                                    if (!string.IsNullOrEmpty(oldProduct.MadeCoutry))
                                    {
                                        fieldsToUpdate.Add("MadeCoutry");
                                    }
                                    if (string.IsNullOrEmpty(oldProduct.Capacity))
                                    {
                                        fieldsToUpdate.Add("Capacity");
                                    }
                                    if (string.IsNullOrEmpty(oldProduct.MeasureUnit))
                                    {
                                        fieldsToUpdate.Add("MeasureUnit");
                                    }
                                    if (oldProduct.ProductMeasureID == 0)
                                    {
                                        fieldsToUpdate.Add("ProductMeasureID");
                                    }
                                    if (string.IsNullOrEmpty(oldProduct.Components))
                                    {
                                        fieldsToUpdate.Add("Components");
                                    }
                                    if (!oldProduct.NoTax)
                                    {
                                        fieldsToUpdate.Add("NoTax");
                                    }
                                    if (!oldProduct.SoldByWeight)
                                    {
                                        fieldsToUpdate.Add("SoldByWeight");
                                    }
                                    if (string.IsNullOrEmpty(oldProduct.ShortDescription))
                                    {
                                        fieldsToUpdate.Add("ShortDescription");
                                    }
                                    if (string.IsNullOrEmpty(oldProduct.FullDescription))
                                    {
                                        fieldsToUpdate.Add("FullDescription");
                                    }
                                    if (string.IsNullOrEmpty(oldProduct.ProductShopOptions))
                                    {
                                        fieldsToUpdate.Add("ProductShopOptions");
                                    }
                                    if (!oldProduct.UnitsPerPackage.HasValue)
                                    {
                                        fieldsToUpdate.Add("UnitPerPackage");
                                    }
                                    if (oldProduct.ProductManufacturerID == 0)
                                    {
                                        fieldsToUpdate.Add("ProductManufacturerID");
                                        fieldsToUpdate.Add("DisplayOrder");
                                    }
                                    if (oldProduct.CategoryID == 0)
                                    {
                                        fieldsToUpdate.Add("CategoryID");
                                    }

                                    if (oldProduct.ContentUnitMeasureID == 0)
                                    {
                                        fieldsToUpdate.Add("ContentUnitMeasureID");
                                    }

                                    if (oldProduct.ContentUnitPriceMultiplicator == 0)
                                    {
                                        fieldsToUpdate.Add("ContentUnitPriceMultiplicator");
                                    }



                                    productForUpdateVariable.Add(new ProductVariable <Product>()
                                    {
                                        Fields = fieldsToUpdate,
                                        Entity = product
                                    });
                                    #endregion
                                }
                                else if (isUpdateIfSource)
                                {
                                    #region Flag 2 isUpdateIfSource
                                    productForUpdateVariable.Add(new ProductVariable <Product>()
                                    {
                                        Fields = fieldsToUpdate,
                                        Entity = product
                                    });
                                    #endregion
                                }
                                else if (isFullUpdate)
                                {
                                    //flag 3
                                    productForUpdate.Add(product);
                                }
                                else if (isDelete)
                                {
                                    //Flag 0
                                    productForDelete.Add(product);
                                }


                                #region oldImport
                                //if (!productsList[sku].IgnoreOnImport)
                                //{
                                //    var pID = productsList[sku].ID;
                                //    product.ID = pID;
                                //    //update
                                //    if (isUpdateIfSource)
                                //        productForUpdate.Add(product);

                                //    //delete
                                //    if (isDelete)
                                //        productForDelete.Add(product);
                                //}
                                #endregion
                            }
                            else
                            {
                                //insert
                                if (isInsert)
                                {
                                    if (!productforInsert.Any(x => x.SKU == product.SKU))
                                    {
                                        productforInsert.Add(product);
                                    }
                                }
                            }
                        }
                    }
                    string message = RP.S("Admin.Product.Import.SeeError");
                    if (true)// || errors.Length < 2) //no errors
                    {
                        currentTask.Message         = RP.S("Admin.PlanedTask.InProgress.SqlBulkOperation");
                        currentTask.PercentProgress = 80;
                        _db.SaveChanges();
                        var insertRes    = productforInsert.SqlInsert(returnLog: true);
                        var updateRes    = productForUpdate.SqlUpdateById(false, returnLog: true);
                        var updateVarRes = productForUpdateVariable.SqlUpdateById(true);
                        var deleteRes    = productForDelete.SqlMarkAsDeletedById(true);
                        message = RP.S("Admin.Product.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 = 0;
                                procError.UserID = LS.CurrentUser.ID;
                            }
                            processErrors.SqlInsert();
                        }
                        catch
                        {
                        }

                        // ActivityLogFiles
                        if (false)
                        {
                            var filename = Guid.NewGuid().ToString().ToLower()
                                           .Replace("-", "")
                                           + Path.GetExtension(FilePath);
                            var filePath = HostingEnvironment.MapPath("~/Content/ActivityLogFiles/") + filename;
                            System.IO.File.Copy(FilePath, filePath, true);
                            ActivityLog activity = new ActivityLog()
                            {
                                ActivityType = ActivityType.Bulk,
                                CreateOn     = DateTime.Now,
                                DirectSQL    = insertRes.SqlLog.ToString() + @"
                    
--UPDATE SQL
" + updateRes.SqlLog.ToString()

                                               + @"
                    
--DELETE SQL
" + deleteRes.SqlLog.ToString()
                                ,
                                EntityType = EntityType.Product,
                                FullText   = "",
                                // RequestUrl = Request.RawUrl,
                                ShortDescription = "",
                                // UploadedFileName = attachment.FileName,
                                CopiedFileName = filename,
                                UserID         = LS.CurrentUser.ID
                            };
                        }
                    }
                    #endregion
                }
            }
        }
Esempio n. 21
0
 public static string DuplicateError(UserCredit credit)
 {
     return(RP.S("Admin.UserCredit.Create.ThisUserAndShopAlreadyAdded"));
 }
Esempio n. 22
0
 public static string InsertGeneralError(UserCredit credit)
 {
     return(RP.S("Admin.UserCredit.Create.CantCreateCredits"));
 }
        public IList <ShoppingCartItemModel> GetShoppingCartItems(int ShopID, bool loadAttributes = false
                                                                  , bool withdiscount             = true
                                                                  , bool checkQuantity            = false
                                                                  , Guid UserID = new Guid())
        {
            if (UserID == Guid.Empty && LS.isHaveID())
            {
                UserID = LS.CurrentUser.ID;
            }
            Dictionary <int, decimal> totalResources = new Dictionary <int, decimal>();
            var data = (from sci in _db.ShoppingCartItems
                        join ps in _db.ProductShopMap
                        on sci.ProductShopID equals ps.ID
                        join p in _db.Products
                        on ps.ProductID equals p.ID
                        where sci.UserID == UserID &&
                        sci.ShopID == ShopID
                        //join psao in LS.CurrentEntityContext.ProductAttributeOptions
                        //on sci.ProductAttributeOptionID equals psao.ID
                        select new ShoppingCartItemModel()
            {
                ID = sci.ID,
                Name = p.Name,
                Price = ps.Price,
                PriceByUnit = ps.PriceByUnit,
                SKU = p.SKU,
                Image = p.Image,
                ProductID = p.ID,
                //  Manufacturer = p.Manufacturer,
                ProductManufacturerID = p.ProductManufacturerID,
                ProductShopID = ps.ID,
                Quantity = sci.Quantity,
                QuantityResource = ps.Quantity,
                QuantityType = ps.QuantityType,
                QuantityPriceType = sci.QuantityType,
                ShopID = ps.ShopID,
                SoldByWeight = p.SoldByWeight,
                Capacity = p.Capacity,
                UnitPrice = ps.Price * sci.Quantity,
                ProductAttributeOptionID = sci.ProductAttributeOptionID,
                AttributeDescription = "",
                CategoryID = p.CategoryID,
                MeasureUnit = p.MeasureUnit,
                MeasureUnitStep = p.MeasureUnitStep,
            }).ToList();

            foreach (var item in data)
            {
                if (item.ProductManufacturerID > 0)
                {
                    var m = LS.Get <Manufacturer>().FirstOrDefault(x => x.ID == item.ProductManufacturerID);
                    item.Manufacturer = m != null ? m.Name : "";
                }
                if (item.QuantityPriceType == QuantityType.ByUnit && item.PriceByUnit.HasValue)
                {
                    item.Price       = item.PriceByUnit.Value;
                    item.UnitPrice   = item.Price * item.Quantity;
                    item.MeasureUnit = null;

                    item.MeasureUnitStep = null;
                    item.SoldByWeight    = false;
                }
                item.Errors = new List <string>();
                if (false && loadAttributes)
                {
                    var attributes = (from pao in _db.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.ID == item.ProductAttributeOptionID);
                    if (attribute != null)
                    {
                        item.AttributeDescription = attribute.Name;
                        if (!string.IsNullOrEmpty(attribute.OverridenSku))
                        {
                            item.SKU = attribute.OverridenSku;
                        }
                        if (attribute.OverridenPrice.HasValue)
                        {
                            item.Price = attribute.OverridenPrice.Value;
                        }
                        if (item.QuantityType == ProductQuantityType.CheckByProductOptions)
                        {
                            item.QuantityResource = attribute.Quantity;
                        }
                    }
                    else if (checkQuantity)
                    {
                        item.Errors.Add(RP.S("ShoppingCart.AddToCart.Error.OptionNotFoud"));
                    }
                }
                else
                {
                    if (item.ProductAttributeOptionID > 0)
                    {
                        var attribute = (from pao in _db.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;
                            }
                            if (item.QuantityType == ProductQuantityType.CheckByProductOptions)
                            {
                                item.QuantityResource = attribute.Quantity;
                            }
                        }
                        else if (checkQuantity)
                        {
                            item.Errors.Add(RP.S("ShoppingCart.AddToCart.Error.OptionNotFoud"));
                        }
                    }
                    else if (false && checkQuantity && LS.CurrentEntityContext.ProductAttributeOptions.Any(x => x.ProductShopID == item.ProductShopID))
                    {
                        item.Errors.Add(RP.S("ShoppingCart.AddToCart.Error.OptionNotSelected"));
                    }
                }
                // check total quantity if different attribute and check by product
                if (checkQuantity && item.QuantityType == ProductQuantityType.CheckByProduct)
                {
                    if (totalResources.ContainsKey(item.ProductShopID))
                    {
                        item.QuantityResource = totalResources[item.ProductShopID];
                        totalResources[item.ProductShopID] -= item.Quantity;
                    }
                    else
                    {
                        totalResources[item.ProductShopID] = item.QuantityResource - item.Quantity;
                    }
                }
                if (checkQuantity && item.QuantityType != ProductQuantityType.NotCheck && item.Quantity > item.QuantityResource)
                {
                    item.Errors.Add(RP.S("ShoppingCart.AddToCart.Error.NoEnoughQuantity"));
                }
                if (item.Price <= 0)
                {
                    item.Errors.Add(RP.S("ShoppingCart.AddToCart.Error.ZeroPrice"));
                }
                if (item.Errors.Count > 0)
                {
                    item.IsValid = false;
                }
            }


            return(data);
        }