public async Task <IActionResult> PutProductShop(int id, ProductShop productShop)
        {
            if (id != productShop.ProductShopId)
            {
                return(BadRequest());
            }
            var pr = new PriceRecord();

            pr.Price     = productShop.Price;
            pr.PriceDate = productShop.PriceDate;

            productShop.AddRecord(pr);
            _context.Entry(productShop).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductShopExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        public async Task <ActionResult <ProductShop> > PostProductShop(ProductShop productShop)
        {
            _context.ProductShops.Add(productShop);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetProductShop", new { id = productShop.ProductShopId }, productShop));
        }
        public ProductShop Add(ProductShop item)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }
            item.Id = _nextId++;

            var product = repository.Products.Find(p => p.Id == item.ProductId);

            if (product == null)
            {
                item.ProductId = 0;
            }
            else
            {
                item.Product = product;
            }

            var shop = repository.Shops.Find(s => s.Id == item.ShopId);

            if (shop == null)
            {
                item.ShopId = 0;
            }
            else
            {
                item.Shop = shop;
            }

            repository.ProductShops.Add(item);
            return(item);
        }
示例#4
0
 public static dtoProductShop ToDtoProductShop(ProductShop productShop)
 {
     return(new dtoProductShop()
     {
         Code = Convert.ToInt32(productShop.Code), CodeProduct = Convert.ToInt32(productShop.CodeProduct), CodeShop = Convert.ToInt32(productShop.CodeShop), Product = Converts.ToDtoProduct(productShop.Product)
     });
 }
示例#5
0
        public void AddShopProduct(ShopProductDTO model)
        {
            ProductShop dbModel = mapper.Map <ProductShop>(model);

            services.Shop.AddProductShop(dbModel);
            services.Commit();
        }
示例#6
0
        public bool Insert()
        {
            ProductShop s = Converts.ToProductShop(this);

            GeneralDB generalDB = new GeneralDB();

            generalDB.MyDb.ProductShops.Add(s);
            generalDB.MyDb.SaveChanges();
            return(true);
        }
示例#7
0
        public void AddProductShop(ProductShop model)
        {
            var newmodel = Context.ProductShops.Where(x => x.ProductId == model.ProductId && x.ShopId == model.ShopId).FirstOrDefault();

            if (newmodel != null)
            {
                newmodel.Price   = model.Price;
                newmodel.BarCode = model.BarCode;
                Context.ProductShops.Update(newmodel);
            }
            else
            {
                Context.ProductShops.Add(new ProductShop()
                {
                    ProductId = model.ProductId, ShopId = model.ShopId, BarCode = model.BarCode, Price = model.Price
                });
            }
        }
        public bool Update(ProductShop item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            int index = repository.ProductShops.FindIndex(ps => ps.Id == item.Id);

            if (index == -1)
            {
                return(false);
            }
            repository.ProductShops.RemoveAt(index);

            var product = repository.Products.Find(p => p.Id == item.ProductId);

            if (product == null)
            {
                item.ProductId = 0;
            }
            else
            {
                item.Product = product;
            }

            var shop = repository.Shops.Find(s => s.Id == item.ShopId);

            if (shop == null)
            {
                item.ShopId = 0;
            }
            else
            {
                item.Shop = shop;
            }

            repository.ProductShops.Add(item);

            return(true);
        }
示例#9
0
        // GET: ShopPage
        public ActionResult Index(string productType, string sortOrder, string brand, string currentFilter, string searchString, int?page)
        {
            int productTypeId = db.ProductTypes.Where(m => m.ProductTypeName == productType).Select(m => m.ProductTypeId).FirstOrDefault();

            ViewBag.ProductTypeName = productType;
            ViewBag.ProductTypeId   = productTypeId;

            List <ProductShop> listPrd = new List <ProductShop>();

            //--Create a list to show Product Shop List
            if (productType != null)
            {
                foreach (var item in db.Products.Where(m => m.ProductTypeId == productTypeId))
                {
                    var                prdId             = item.ProductId;
                    ProductShop        productShop       = new ProductShop();
                    Nullable <decimal> PriceCheapestType = Decimal.MaxValue;
                    int                count             = 0;

                    //Find branch cheapest in Product to show page shop, Sale marketting
                    if (productType == "Smartphone")
                    {
                        //Search in PortableDevice by product id
                        foreach (var item1 in db.ProductPortableDevices.Where(m => m.ProductId == prdId))
                        {
                            if (item1.Price < PriceCheapestType)
                            {
                                PriceCheapestType = item1.Price;
                            }
                            //Check Quantiny this product to show nofication
                            count += item1.Quantiny;
                        }
                    }
                    else if (productType == "Accessory")
                    {
                        //Search in AccessoryDevice by product id
                        foreach (var item1 in db.ProductAccessories.Where(m => m.ProductId == prdId))
                        {
                            if (item1.Price < PriceCheapestType)
                            {
                                PriceCheapestType = item1.Price;
                            }
                            count += item1.Quantiny;
                        }
                    }

                    //Assign variable Price Cheapest branch
                    if (productType == "Smartphone")
                    {
                        //Search in PortableDevice by product id
                        foreach (var item1 in db.ProductPortableDevices.Where(m => m.ProductId == prdId))
                        {
                            if (item1.Price == PriceCheapestType)
                            {
                                productShop.CheapestProductId = item1.ProductPortableDeviceId;
                            }
                        }
                    }
                    else if (productType == "Accessory")
                    {
                        //Search in AccessoryDevice by product id
                        foreach (var item1 in db.ProductAccessories.Where(m => m.ProductId == prdId))
                        {
                            if (item1.Price == PriceCheapestType)
                            {
                                productShop.CheapestProductId = item1.ProductAccessoryId;
                            }
                        }
                    }

                    productShop.ProductId         = prdId;
                    productShop.ProductName       = item.ProductName;
                    productShop.RealeaseDate      = item.RealeaseDate;
                    productShop.FileImage         = item.FileImage;
                    productShop.PriceCheapestType = PriceCheapestType;
                    productShop.Brand             = db.BrandTypes.Where(m => m.BrandTypeId == item.BrandTypeId).Select(m => m.BrandName).FirstOrDefault();
                    if (count == 0)
                    {
                        productShop.Stocking = false;
                    }
                    listPrd.Add(productShop);
                }
            }
            //----------------------------------------

            ViewBag.CountProduct = listPrd.Count();
            ViewBag.ProductType  = productType;
            ViewBag.BrandList    = listPrd.Select(m => m.Brand).Distinct();

            //Paging, sorting part
            ViewBag.CurrentSort  = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;

            if (!String.IsNullOrEmpty(searchString))
            {
                listPrd = listPrd.Where(s => s.ProductName.Contains(searchString)).ToList();
            }

            if (!String.IsNullOrEmpty(brand))
            {
                listPrd = listPrd.Where(m => m.Brand == brand).ToList();
            }

            switch (sortOrder)
            {
            case "name_desc":
                listPrd = listPrd.OrderByDescending(s => s.ProductName).ToList();
                break;

            case "Date":
                listPrd = listPrd.OrderBy(s => s.RealeaseDate).ToList();
                break;

            case "date_desc":
                listPrd = listPrd.OrderByDescending(s => s.RealeaseDate).ToList();
                break;

            default:
                listPrd = listPrd.OrderBy(s => s.ProductName).ToList();
                break;
            }
            int pageSize   = 20;
            int pageNumber = (page ?? 1);

            return(View(listPrd.ToPagedList(pageNumber, pageSize)));
        }
示例#10
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 }));
        }