private void UpdateOptionLocales(ProductAttributeOption productAttributeOption, ProductAttributeOptionModel model)
 {
     foreach (var localized in model.Locales)
     {
         _localizedEntityService.SaveLocalizedValue(productAttributeOption, x => x.Name, localized.Name, localized.LanguageId);
         _localizedEntityService.SaveLocalizedValue(productAttributeOption, x => x.Alias, localized.Alias, localized.LanguageId);
     }
 }
        public virtual void UpdateProductAttributeOption(ProductAttributeOption productAttributeOption)
        {
            Guard.NotNull(productAttributeOption, nameof(productAttributeOption));

            _productAttributeOptionRepository.Update(productAttributeOption);

            _eventPublisher.EntityUpdated(productAttributeOption);
        }
        public virtual void InsertProductAttributeOption(ProductAttributeOption productAttributeOption)
        {
            Guard.NotNull(productAttributeOption, nameof(productAttributeOption));

            _productAttributeOptionRepository.Insert(productAttributeOption);

            _eventPublisher.EntityInserted(productAttributeOption);
        }
Example #4
0
 public static void DeleteProductOptionById(int id)
 {
     using (EcommerceEntities entities = new EcommerceEntities())
     {
         ProductAttributeOption propductAttributeOption = entities.ProductAttributeOptions.Where(entry => entry.ID == id).FirstOrDefault();
         entities.ProductAttributeOptions.Remove(propductAttributeOption);
         entities.SaveChanges();
     }
 }
Example #5
0
        /// <summary>
        /// Deletes a product attribute option
        /// </summary>
        /// <param name="specificationAttributeOption">The specification attribute option</param>
        public virtual void DeleteProductAttributeOption(ProductAttributeOption productAttributeOption)
        {
            if (productAttributeOption == null)
            {
                throw new ArgumentNullException("productAttributeOption");
            }

            _productAttributeOptionRepository.Delete(productAttributeOption);

            _cacheManager.RemoveByPattern(PRODUCTATTRIBUTEOPTION_PATTERN_KEY);
            _eventPublisher.EntityDeleted(productAttributeOption);
        }
Example #6
0
        public static ResponseViewModel <ProductAttributeOption> UpdateOption(ProductAttributeOption productAttributeOption)
        {
            ResponseViewModel <ProductAttributeOption> responseViewModel = new ResponseViewModel <ProductAttributeOption>();

            using (EcommerceEntities entities = new EcommerceEntities())
            {
                ProductAttributeOption productAttributeOptionDb = entities.ProductAttributeOptions.Where(entry => entry.ID == productAttributeOption.ID).FirstOrDefault();
                productAttributeOptionDb.Value = productAttributeOption.Value;
                responseViewModel.Data         = productAttributeOptionDb;
                entities.SaveChanges();
            }
            return(responseViewModel);
        }
Example #7
0
        public static List <CartAttributeViewModel> GetCartItems(int cartId)
        {
            List <CartAttributeViewModel> response        = new List <CartAttributeViewModel>();
            List <CartItemOption>         cartItemOptions = new List <CartItemOption>();
            Cart cart = GetCart(cartId);

            if (cart != null)
            {
                using (EcommerceEntities entities = new EcommerceEntities())
                {
                    List <GetCartItemsByCartId_Result> cartItems = entities.GetCartItemsByCartId(cartId).ToList();
                    foreach (var cartitem in cartItems)
                    {
                        ProductAtrributeOptionsViewModel        productAtrributeViewModel     = null;
                        List <ProductAtrributeOptionsViewModel> productAtrributeViewModelList = new List <ProductAtrributeOptionsViewModel>();
                        CartAttributeViewModel viewModel      = new CartAttributeViewModel();
                        CartItemOption         cartItemOption = new CartItemOption();
                        viewModel.cartItem = cartitem;
                        cartItemOptions    = entities.CartItemOptions.Where(entry => entry.CartItemID == cartitem.ID).ToList();
                        foreach (var cartOption in cartItemOptions)
                        {
                            productAtrributeViewModel = new ProductAtrributeOptionsViewModel();
                            ProductAttributeOption optionDb           = new ProductAttributeOption();
                            OptionList             option             = new OptionList();
                            List <OptionList>      optionList         = new List <OptionList>();
                            ProductAttribute       productAttributeDb = new ProductAttribute();
                            optionDb           = entities.ProductAttributeOptions.Where(entry => entry.ID == cartOption.OptionsID).FirstOrDefault();
                            productAttributeDb = entities.ProductAttributes.Where(entry => entry.ID == optionDb.ProductAtrributeID).FirstOrDefault();
                            option.optionId    = Convert.ToInt32(cartOption.OptionsID);
                            option.optionName  = optionDb.Value;
                            optionList.Add(option);
                            productAtrributeViewModel.attributeId   = Convert.ToInt32(productAttributeDb.ID);
                            productAtrributeViewModel.attributeName = productAttributeDb.Name;
                            productAtrributeViewModel.optionList    = optionList;
                            productAtrributeViewModelList.Add(productAtrributeViewModel);
                        }
                        viewModel.options = productAtrributeViewModelList;
                        response.Add(viewModel);
                    }
                }
            }
            return(response);
        }
        private void PrepareProductAttributeOptionModel(ProductAttributeOptionModel model, ProductAttributeOption option)
        {
            // TODO: DRY, similar code in ProductController (ProductAttributeValueList, ProductAttributeValueEditPopup...)
            if (option != null)
            {
                model.NameString             = Server.HtmlEncode(option.Color.IsEmpty() ? option.Name : $"{option.Name} - {option.Color}");
                model.PriceAdjustmentString  = (option.ValueType == ProductVariantAttributeValueType.Simple ? option.PriceAdjustment.ToString("G29") : "");
                model.WeightAdjustmentString = (option.ValueType == ProductVariantAttributeValueType.Simple ? option.WeightAdjustment.ToString("G29") : "");
                model.TypeName      = option.ValueType.GetLocalizedEnum(Services.Localization, Services.WorkContext);
                model.TypeNameClass = (option.ValueType == ProductVariantAttributeValueType.ProductLinkage ? "fa fa-link mr-2" : "d-none hide hidden-xs-up");

                var linkedProduct = _productService.GetProductById(option.LinkedProductId);
                if (linkedProduct != null)
                {
                    model.LinkedProductName          = linkedProduct.GetLocalized(p => p.Name);
                    model.LinkedProductTypeName      = linkedProduct.GetProductTypeLabel(Services.Localization);
                    model.LinkedProductTypeLabelHint = linkedProduct.ProductTypeLabelHint;

                    if (model.Quantity > 1)
                    {
                        model.QuantityInfo = $" × {model.Quantity}";
                    }
                }

                AddLocales(_languageService, model.Locales, (locale, languageId) =>
                {
                    locale.Name  = option.GetLocalized(x => x.Name, languageId, false, false);
                    locale.Alias = option.GetLocalized(x => x.Alias, languageId, false, false);
                });
            }
        }
Example #9
0
 public static ProductAttributeOption ToEntity(this ProductAttributeOptionModel model, ProductAttributeOption destination)
 {
     return(Mapper.Map(model, destination));
 }
Example #10
0
 public static ProductAttributeOptionModel ToModel(this ProductAttributeOption entity)
 {
     return(Mapper.Map <ProductAttributeOption, ProductAttributeOptionModel>(entity));
 }
        public virtual void InsertProductAttributeOption(ProductAttributeOption productAttributeOption)
        {
            Guard.NotNull(productAttributeOption, nameof(productAttributeOption));

            _productAttributeOptionRepository.Insert(productAttributeOption);
        }
        public virtual void DeleteProductAttributeOption(ProductAttributeOption productAttributeOption)
        {
            Guard.NotNull(productAttributeOption, nameof(productAttributeOption));

            _productAttributeOptionRepository.Delete(productAttributeOption);
        }
Example #13
0
 public static ProductAttributeOption ToEntity(this ProductAttributeOptionModel model, ProductAttributeOption entity)
 {
     MapperFactory.Map(model, entity);
     return(entity);
 }
Example #14
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 Copy(int Id)
        {
            var shop = _db.Shops.FirstOrDefault(x => x.ID == Id);

            if (shop != null)
            {
                _db.Configuration.ValidateOnSaveEnabled = false;

                var clonedShopp = new Shop();
                #region copy fileds
                clonedShopp.Active                    = shop.Active;
                clonedShopp.Address                   = shop.Address;
                clonedShopp.AddressMap                = shop.AddressMap;
                clonedShopp.CreateTime                = DateTime.Now;
                clonedShopp.CreditGuardMid            = shop.CreditGuardMid;
                clonedShopp.CreditGuardPass           = shop.CreditGuardPass;
                clonedShopp.CreditGuardTerminal       = shop.CreditGuardTerminal;
                clonedShopp.CreditGuardUrl            = shop.CreditGuardUrl;
                clonedShopp.CreditGuardUser           = shop.CreditGuardUser;
                clonedShopp.DeliveryManualDescription = shop.DeliveryManualDescription;
                clonedShopp.DeliveryTime              = shop.DeliveryTime;
                clonedShopp.DisplayOrder              = shop.DisplayOrder;
                clonedShopp.Email                = shop.Email;
                clonedShopp.FreeShipFrom         = shop.FreeShipFrom;
                clonedShopp.FullDescription      = shop.FullDescription;
                clonedShopp.Image                = shop.Image;
                clonedShopp.InStorePickUpEnabled = shop.InStorePickUpEnabled;
                clonedShopp.IsShipEnabled        = shop.IsShipEnabled;
                clonedShopp.IsToShopOwnerCredit  = shop.IsToShopOwnerCredit;
                clonedShopp.Kosher               = shop.Kosher;
                clonedShopp.Latitude             = shop.Latitude;
                clonedShopp.Longitude            = shop.Longitude;
                clonedShopp.MounthlyFee          = shop.MounthlyFee;
                clonedShopp.Name              = shop.Name;
                clonedShopp.PercentFee        = shop.PercentFee;
                clonedShopp.Phone             = shop.Phone;
                clonedShopp.Phone2            = shop.Phone2;
                clonedShopp.RadiusLatitude    = shop.RadiusLatitude;
                clonedShopp.RadiusLongitude   = shop.RadiusLongitude;
                clonedShopp.SeoUrl            = shop.SeoUrl;
                clonedShopp.ShipCost          = shop.ShipCost;
                clonedShopp.ShipRadius        = shop.ShipRadius;
                clonedShopp.ShopTypeIDs       = shop.ShopTypeIDs;
                clonedShopp.ShortDescription  = shop.ShortDescription;
                clonedShopp.SpecialPercentFee = shop.SpecialPercentFee;
                clonedShopp.UserID            = shop.UserID;
                clonedShopp.Youtube           = shop.Youtube;
                #endregion
                _db.Shops.Add(clonedShopp);
                _db.SaveChanges();
                // 1) work times
                #region work times
                var worktimes = _db.ShopWorkTimes.Where(x => x.ShopID == shop.ID).ToList();
                foreach (var w in worktimes)
                {
                    var sw = new ShopWorkTime();
                    sw.Active    = w.Active;
                    sw.Date      = w.Date;
                    sw.Day       = w.Day;
                    sw.IsSpecial = w.IsSpecial;
                    sw.ShopID    = clonedShopp.ID;
                    sw.TimeFrom  = w.TimeFrom;
                    sw.TimeTo    = w.TimeTo;
                    _db.ShopWorkTimes.Add(sw);
                }
                _db.SaveChanges();
                #endregion
                // 2) ship times
                #region ship times
                var shipimes = _db.ShopShipTimes.Where(x => x.ShopID == shop.ID).ToList();
                foreach (var w in shipimes)
                {
                    var sw = new ShopShipTime();
                    sw.Active    = w.Active;
                    sw.Date      = w.Date;
                    sw.Day       = w.Day;
                    sw.IsSpecial = w.IsSpecial;
                    sw.ShopID    = clonedShopp.ID;
                    sw.TimeFrom  = w.TimeFrom;
                    sw.TimeTo    = w.TimeTo;

                    _db.ShopShipTimes.Add(sw);
                }
                _db.SaveChanges();
                #endregion
                // 3) products with attr
                #region shop product
                var products = _db.ProductShopMap.Where(x => x.ShopID == shop.ID).ToList();
                List <ProductShop> copied = new List <ProductShop>();
                foreach (var p in products)
                {
                    var sp = new ProductShop();
                    sp.CreateDate         = DateTime.Now;
                    sp.DontImportPrice    = p.DontImportPrice;
                    sp.HaveDiscount       = false;
                    sp.IncludeInShipPrice = p.IncludeInShipPrice;
                    sp.IncludeVat         = p.IncludeVat;
                    sp.MaxCartQuantity    = p.MaxCartQuantity;
                    sp.NotInCategory      = p.NotInCategory;
                    sp.Price        = sp.Price;
                    sp.ProductID    = p.ProductID;
                    sp.Quantity     = p.Quantity;
                    sp.QuantityType = p.QuantityType;
                    sp.ShopID       = clonedShopp.ID;

                    _db.ProductShopMap.Add(sp);
                    copied.Add(sp);
                    //attr
                    sp.ProductAttributeOptions = _db.ProductAttributeOptions.Where(x => x.ProductShopID == p.ID).ToList();
                }
                _db.SaveChanges();
                foreach (var sp in copied)
                {
                    foreach (var a in sp.ProductAttributeOptions)
                    {
                        var sa = new ProductAttributeOption();
                        sa.Name           = a.Name;
                        sa.OverridenPrice = a.OverridenPrice;
                        sa.OverridenSku   = a.OverridenSku;
                        sa.ProductShopID  = sp.ID;
                        sa.Quantity       = a.Quantity;
                        _db.ProductAttributeOptions.Add(sa);
                    }
                }
                _db.SaveChanges();
                #endregion
                // 4) categories
                #region categories
                var cats = _db.ShopCategories.Where(x => x.ShopID == shop.ID).ToList();
                foreach (var c in cats)
                {
                    var sc = new ShopCategory();
                    sc.CategoryID   = c.CategoryID;
                    sc.DisplayOrder = c.DisplayOrder;
                    var cat = LS.Get <Category>().FirstOrDefault(x => x.ID == c.CategoryID);
                    if (cat != null)
                    {
                        sc.DisplayOrder = cat.DisplayOrder;
                    }
                    sc.Published = c.Published;
                    sc.ShopID    = clonedShopp.ID;
                    _db.ShopCategories.Add(sc);
                }
                _db.SaveChanges();
                #endregion

                #region times



                #endregion
                return(RedirectToAction("Edit", "Generic", new { model = "Shop", ID = clonedShopp.ID }));
            }
            return(RedirectToAction("Edit", "Generic", new { model = "Shop", ID = Id }));
        }
 public static ProductOptionViewModel GetProductById(int id)
 {
     ProductOptionViewModel productAtrributeViewModel = new ProductOptionViewModel();
     List<ProductAtrributeOptionsViewModel> viewModel = new List<ProductAtrributeOptionsViewModel>();
     using (EcommerceEntities entities = new EcommerceEntities())
     {
         //ResponseViewModel<ProductAtrributeOptionsViewModel> response = new ResponseViewModel<ProductAtrributeOptionsViewModel>();
         List<Product_Attribute> options = new List<Product_Attribute>();
         List<ProductAttribute> attributes = new List<ProductAttribute>();
         //List<ProductAttributeOption> options = new List<ProductAttributeOption>();
         GetProductById_Result result = entities.GetProductById(id).FirstOrDefault();//get api of product
         Product product = new Product();
         product.Name = result.Name;
         product.ID = result.ID;
         product.Price = result.Price;
         product.ProductCateogoryID = result.CategoryId;
         product.ProductSubCategoryID = result.SubCategoryID;
         product.Image = result.Image;
         product.Description = result.Description;
         product.Discount = result.Discount;
         product.Quentity = result.Quentity;
         options = entities.Product_Attribute.Where(entry => entry.ProductID == id).ToList();
         //attributes = entities.ProductAttributes.Where(entry => entry. == product.ProductSubCategoryID).ToList();
         if (options != null)
         {
             foreach (var option in options)
             {
                 ProductAtrributeOptionsViewModel attributeOptionViewModel = new ProductAtrributeOptionsViewModel();
                 ProductAtrributeOptionsViewModel attributeOptionViewModelObj = new ProductAtrributeOptionsViewModel();
                 List<OptionList> optionsList = new List<OptionList>();
                 ProductAttributeOption optionDb = new ProductAttributeOption();
                 ProductAttribute productAttributeDb = new ProductAttribute();
                 optionDb = entities.ProductAttributeOptions.Where(entry => entry.ID == option.OptionID).FirstOrDefault();
                 productAttributeDb = entities.ProductAttributes.Where(entry => entry.ID == optionDb.ProductAtrributeID).FirstOrDefault();
                 attributeOptionViewModel.attributeName = productAttributeDb.Name;
                 attributeOptionViewModel.attributeId = Convert.ToInt32(productAttributeDb.ID);
                 if(viewModel.Any(entry => entry.attributeId == attributeOptionViewModel.attributeId))
                 {
                     attributeOptionViewModelObj = viewModel.Where(entry => entry.attributeId == attributeOptionViewModel.attributeId).FirstOrDefault();
                     if (attributeOptionViewModelObj != null)
                     {
                         OptionList optionViewModel = new OptionList();
                         optionViewModel.optionName = optionDb.Value;
                         optionViewModel.optionId = Convert.ToInt32(optionDb.ID);
                         attributeOptionViewModel.optionList = optionsList;
                         attributeOptionViewModelObj.optionList.Add(optionViewModel);
                     }   
                 }
                 else
                 {
                     OptionList optionViewModel = new OptionList();
                     optionViewModel.optionName = optionDb.Value;
                     optionViewModel.optionId = Convert.ToInt32(optionDb.ID);
                     optionsList.Add(optionViewModel);
                     attributeOptionViewModel.optionList = optionsList;
                     viewModel.Add(attributeOptionViewModel);
                 }
             }
         }
         productAtrributeViewModel.product = product;
         productAtrributeViewModel.ViewModel = viewModel;
     }
     return productAtrributeViewModel;
 }