Ejemplo n.º 1
0
        public ActionResult Create()
        {
            var model = new ProductEditViewModel();

            ViewBag.TaxClassId = new SelectList(taxClassService.FindAll().ToList().OrderBy(r => r.Name), "Id", "Name");
            return View(model);
        }
        public ViewResult Edit(int Id)
        {
            var product = productRepository.GetProduct(Id);
            ProductEditViewModel productEditViewModel = new ProductEditViewModel()
            {
                ProductName       = product.ProductName,
                ExistingPhotoPath = product.ImagePath,
                Quantity          = product.Quantity,
                ProductPrice      = product.ProductPrice,
                IsActive          = product.IsActive,
            };

            return(View(productEditViewModel));
        }
Ejemplo n.º 3
0
        public ActionResult Create(int?id)
        {
            var model = new ProductEditViewModel {
                CategoryId = (int)id
            };

            using (var db = new MyDbContext())
            {
                model.CategoryName = string.Join("", db.Categories.Where(x => x.CategoryId == id).Select(x => x.Name));
                model.CategoryId   = (int)id;
            }

            return(View(model));
        }
        public ActionResult Create()
        {
            var categories = _categoryTasks.GetAll();
            if (categories.Count == 0)
                ViewBag.CategoryError = "You must create at least one Category before creating a Product.";

            var model = new ProductEditViewModel
            {
                Categories = _categoryTasks.GetAll(),
                Product = new Product(),
                SelectedCategoryId = 0
            };
            return View(model);
        }
        public ActionResult Edit(int?id)
        {
            var model = new ProductEditViewModel();

            if (id != null)
            {
                Product p = _productRepository.GetProductById((int)id);
                model.Id   = id;
                model.产品名称 = p.产品名称;
                model.产品类型 = p.产品类型;
                model.单位名称 = p.单位名称;
                model.库存数量 = p.库存数量;
            }
            return(PartialView(model));
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> EditProduct(ProductEditViewModel productModel)
        {
            if (ModelState.IsValid)
            {
                await Mediator.Send(productModel.ToCommand());

                ConfirmationMessage("Produkt bol upravený.");
                this.logger.Information($"The product '{productModel.NameSlovak}' has been successfully updated.");
                return(RedirectToAction(nameof(Products)));
            }

            productModel.Categories = await Mediator.Send(new GetCategoryListQuery());

            return(View(productModel));
        }
Ejemplo n.º 7
0
        public ViewResult Edit(int id)
        {
            Product product = _productRepository.GetProduct(id);

            ProductEditViewModel productEditViewModel = new ProductEditViewModel()
            {
                Id                = product.Id,
                ProductName       = product.ProductName,
                ProductCount      = product.ProductCount,
                ExistingPhotoPath = product.PhotoPath,
                ProductClass      = product.ProductClass
            };

            return(View(productEditViewModel));
        }
Ejemplo n.º 8
0
        public void Can_Edit_Product()
        {
            // Arrange - create the controller
            AdminController target = new AdminController(_mock.Object);

            // Act
            ProductEditViewModel p1 = target.Edit(1).ViewData.Model as ProductEditViewModel;
            ProductEditViewModel p2 = target.Edit(2).ViewData.Model as ProductEditViewModel;
            ProductEditViewModel p3 = target.Edit(3).ViewData.Model as ProductEditViewModel;

            // Assert
            Assert.AreEqual(1, p1.ProductID);
            Assert.AreEqual(2, p2.ProductID);
            Assert.AreEqual(3, p3.ProductID);
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> Put(long id, [FromBody] ProductEditViewModel model)
        {
            if (id != model.Id)
            {
                return(this.BadRequest("Invalid product"));
            }
            var result = await this.productService.UpdateProduct(model);

            if (result == false)
            {
                return(this.BadRequest());
            }

            return(this.Ok(result));
        }
Ejemplo n.º 10
0
        public ActionResult Edit(int ID)
        {
            ProductEditViewModel model = new ProductEditViewModel();
            var product = productService.Instance.GetProductID(ID);

            model.ID          = product.ID;
            model.Name        = product.Name;
            model.Description = product.Description;
            model.Price       = product.Price;
            model.CategoryID  = product.category != null ? product.category.ID : 0;
            model.ImageURL    = product.ImageURL;

            model.AvailableCategories = CategoriesService.Instance.GetCategory();
            return(PartialView(model));
        }
Ejemplo n.º 11
0
        public ActionResult Edit(ProductEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                _products.Save(model.Product)
                .Commit();

                TempData.AddMessage(MessageType.Success, string.Format("{0} has been saved", model.Product.Name));

                return(RedirectToAction("List", new { category = (string)null }));
            }

            //  there is something wrong with the data values
            return(View(model));
        }
Ejemplo n.º 12
0
        public async Task CheckIfEditingProductReturnsNullReferenceException()
        {
            this.SeedDatabase();
            await this.SeedProducts();

            var productEditViewModel = new ProductEditViewModel
            {
                Id = 3,
            };

            var exception = await Assert
                            .ThrowsAsync <NullReferenceException>(async() => await this.productsService.EditAsync(productEditViewModel));

            Assert.Equal(string.Format(ExceptionMessages.ProductNotFound, productEditViewModel.Id), exception.Message);
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> AddProduct()
        {
            var categories = await _categoryRepository.AllCategories();

            ProductEditViewModel productEditViewModel = new ProductEditViewModel
            {
                Categories = categories.Select(c => new SelectListItem()
                {
                    Text = c.Name, Value = c.Id.ToString()
                }).ToList(),
                CategoryId = categories.FirstOrDefault().Id
            };

            return(View(productEditViewModel));
        }
Ejemplo n.º 14
0
        private void GetCompatibleProducts(ProductEditViewModel product, IQueryable <Product> productsInGroup)
        {
            var compatible = productsInGroup
                             .Select(p => new BasicProdutInfo()
            {
                Id            = p.Id,
                Name          = p.Name,
                Code          = p.Code,
                IsMainInGroup = p.IsMainInGroup
            })
                             .OrderBy(b => b.Name)
                             .ToList();

            product.Compatibility = compatible;
        }
Ejemplo n.º 15
0
        public IActionResult Edit(int id)
        {
            var productVM    = new ProductEditViewModel();
            var productTypes = _productTypeBLL.GetAll();

            var product = _productBLL.GetByIdIncludingAll(id);

            productVM = ProductEditViewModel.FromModel(product, productTypes);

            ViewData["Title"] = productVM.IsCreateMode ? "Create" : "Update";



            return(View(productVM));
        }
Ejemplo n.º 16
0
        public ActionResult Edit(int id, string returnUrl)
        {
            Product product = _products.GetProductById(id);

            IList <Category> allCategories = _categories.GetAllCategories();

            var viewModel = new ProductEditViewModel
            {
                Product    = product,
                Categories = allCategories,
                ReturnUrl  = returnUrl
            };

            return(View(viewModel));
        }
Ejemplo n.º 17
0
        public IActionResult Edit(ProductEditViewModel product)
        {
            if (ModelState.IsValid)
            {
                long size     = 0;
                var  filename = ContentDispositionHeaderValue
                                .Parse(product.Image.ContentDisposition)
                                .FileName
                                .Trim('"');
                var    lastchars = filename.TakeLast(4);
                string suffix    = "";
                foreach (var item in lastchars)
                {
                    suffix += item;
                }
                filename = _hostingEnvironment.WebRootPath + $@"\\images\\Products\\{product.ProductName}{suffix}";
                size    += product.Image.Length;
                using (FileStream fs = System.IO.File.Create(filename))
                {
                    product.Image.CopyTo(fs);
                    fs.Flush();
                    fs.Close();
                }


                var newproduct = new Product
                {
                    ProductImage = $"\\images\\Products\\{product.ProductName}{suffix}",
                    ProductNo    = product.ProductNo,
                    ProductDesc  = product.ProductDesc,
                    CreatedDate  = product.CreatedDate,
                    ModifiedDate = DateTime.Now,
                    IsDeleted    = product.IsDeleted,
                    IsActive     = product.IsActive,
                    Rating       = product.Rating,
                    Price        = product.Price,
                    IsFeatured   = product.IsFeatured,
                    ProductName  = product.ProductName,
                    StockNo      = product.StockNo
                };
                _repository.UpdateProduct(newproduct);
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                return(View(product));
            }
        }
Ejemplo n.º 18
0
        public IActionResult Edit(ProductEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                Products newProduct = new Products
                {
                    Id          = model.Id,
                    ProductName = model.ProductName,
                    Price       = model.Price,
                };

                _productRepository.Edit(newProduct);
                return(RedirectToAction("Products", "buyandsell"));
            }
            return(View(model));
        }
Ejemplo n.º 19
0
        // GET: Products/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ProductEditViewModel model = new ProductEditViewModel();

            model.Product = db.Products.Find(id);
            if (model.Product == null)
            {
                return(HttpNotFound());
            }
            model.Suppliers = new SelectList(db.Suppliers, "Id", "CompanyName", model.Product.SupplierId);
            return(View(model));
        }
Ejemplo n.º 20
0
        // GET
        public IActionResult ProductEdit(int id)
        {
            var viewModel = new ProductEditViewModel();
            var dbProduct = DbContext.Products
                            .Include(c => c.Category)
                            .First(i => i.Id == id);

            viewModel.Id               = dbProduct.Id;
            viewModel.Name             = dbProduct.ProductName;
            viewModel.AllCategories    = GetCategoriesListItems();
            viewModel.SelectCategoryId = dbProduct.Category.Id;
            viewModel.Price            = dbProduct.Price;
            viewModel.Description      = dbProduct.Description;

            return(View(viewModel));
        }
Ejemplo n.º 21
0
        public IActionResult Edit(int Id, ProductEditViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var dbProduct = _dbContext.Produkter.Include(p => p.ProductCategory).First(r => r.Id == Id);
                dbProduct.ProductCategory = _dbContext.ProductCategories.First(r => r.Id == viewModel.SelectedProductCategoryId);
                dbProduct.Name            = viewModel.Namn;
                dbProduct.Price           = viewModel.Pris;
                dbProduct.Description     = viewModel.Comment;
                _dbContext.SaveChanges();
                return(RedirectToAction("Index"));
            }

            viewModel.AllProductCategory = GetCategorySelectListItems();
            return(View(viewModel));
        }
Ejemplo n.º 22
0
        private string UploadedFileEdit(ProductEditViewModel viewModel)
        {
            string uniqueFileName = null;

            if (viewModel.Image != null)
            {
                string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "img");
                uniqueFileName = Guid.NewGuid().ToString() + "_" + viewModel.Image.FileName;
                string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    viewModel.Image.CopyTo(fileStream);
                }
            }
            return(uniqueFileName);
        }
Ejemplo n.º 23
0
        public IActionResult Edit(int Id)
        {
            var viewModel = new ProductEditViewModel();

            var dbProduct = _dbContext.Product.Include(r => r.ProductCategory).First(r => r.Id == Id);

            viewModel.SelectedCategoryId = dbProduct.ProductCategory.Id;
            viewModel.AllCategories      = GetProductsListItems();
            viewModel.Name        = dbProduct.Name;
            viewModel.Id          = dbProduct.Id;
            viewModel.Description = dbProduct.Description;
            viewModel.Price       = dbProduct.Price;


            return(View(viewModel));
        }
Ejemplo n.º 24
0
        public IActionResult Edit(int Id)
        {
            var viewModel = new ProductEditViewModel();

            var dbProduct = _dbContext.Products.Include(r => r.Category).First(r => r.Id == Id);

            viewModel.Id             = dbProduct.Id;
            viewModel.Title          = dbProduct.Title;
            viewModel.Description    = dbProduct.Description;
            viewModel.Price          = dbProduct.Price;
            viewModel.Category       = dbProduct.Category.Id;
            viewModel.Categories     = GetAllCategories();
            viewModel.CategortyTitle = dbProduct.Category.Title;

            return(View(viewModel));
        }
        public ViewResult EditProduct(int id)
        {
            Product product = _productsRepository.GetProduct(id);

            ProductEditViewModel productEditViewModel = new ProductEditViewModel
            {
                Id                = product.Id,
                Name              = product.Name,
                Description       = product.Description,
                Price             = product.Price,
                Availability      = product.Availability,
                ExistingPhotoPath = product.ImageURL
            };

            return(View(productEditViewModel));
        }
Ejemplo n.º 26
0
 public IActionResult ProductEdit(ProductEditViewModel viewModel, int Id)
 {
     if (ModelState.IsValid)
     {
         var dbProduct = _dbContext.Products.Include(p => p.Category).First(r => r.Id == Id);
         dbProduct.Name        = viewModel.Name;
         dbProduct.Category    = _dbContext.ProductCategories.FirstOrDefault(r => r.Id == viewModel.SelectedCategoryId);
         dbProduct.Image       = viewModel.Image;
         dbProduct.Price       = viewModel.Price;
         dbProduct.Description = viewModel.Description;
         _dbContext.SaveChanges();
         return(RedirectToAction("Index", "Home"));
     }
     viewModel.AllCategories = GetAllCategoriesAsListItems();
     return(View(viewModel));
 }
Ejemplo n.º 27
0
        public async Task <IActionResult> Edit(ProductEditViewModel product)
        {
            if (ModelState.IsValid)
            {
                Product prod = await productRepository.EditItemAsync(product);

                if (prod != null)
                {
                    TempData["Message"] = $"Product {prod.Name} has been successfully changed";
                }
                return(RedirectToAction(nameof(List)));
            }
            ViewBag.Categories = await categoryRepository.GetAllItemsAsync();

            return(View(nameof(Create), product));
        }
Ejemplo n.º 28
0
        public IActionResult Edit(int id)
        {
            var product = _context.Products.Include(p => p.Supplier).SingleOrDefault(p => p.Id == id);

            if (product == null)
            {
                return(NotFound());
            }
            // var person = new { FirstName = "Bill", LastName = "Gates" };
            var model = new ProductEditViewModel()
            {
                Product = product, Suppliers = _context.Suppliers
            };

            return(View(model));
        }
 private Product CreateProduct(ProductEditViewModel viewModel)
 {
     return(new Product
     {
         Id = viewModel.Id,
         Title = viewModel.Title,
         Company = _companyRepository.GetById(viewModel.SelectedCompanyId),
         SubCategory = _subCategoryRepository.GetById(viewModel.SelectedSubCategoryId),
         Price = viewModel.Price,
         Warranty = viewModel.WarrantyYears,
         Color = _colorRepository.GetById(viewModel.SelectedColorId),
         InStock = viewModel.InStock,
         ShortDescription = viewModel.ShortDescription,
         LongDescription = viewModel.LongDescription
     });
 }
Ejemplo n.º 30
0
        public async Task <IActionResult> Edit(ProductEditViewModel model, IFormFile thumbimage, List <IFormFile> files)
        {
            if (model.Product.CategoryID != null)
            {
                model.Product.Category = _catRepo.Categories.FirstOrDefault(p => p.CategoryID == model.Product.CategoryID);
            }

            if (ModelState.IsValid)
            {
                files.Insert(0, thumbimage);

                if (files != null)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        if (files[i] != null && files[i].Length > 0)
                        {
                            var fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Path.GetFileName(files[i].FileName);
                            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\images\\products", fileName);

                            if (i == 0)
                            {
                                model.Product.ThumbImage = fileName;
                            }
                            else
                            {
                                model.Product.AddImage(fileName);
                            }

                            using (var fileSteam = new FileStream(filePath, FileMode.Create)) {
                                await files[i].CopyToAsync(fileSteam);
                            }
                        }
                    }
                }

                _prodRepo.SaveProduct(model.Product);
                TempData["message"] = $"{model.Product.Name} has been saved";
                return(RedirectToAction("Index"));
            }
            else
            {
                TempData["error"] = "The are something error in following fields. Please check.";
                model.Categories  = _catRepo.Categories;
                return(View(model));
            }
        }
Ejemplo n.º 31
0
        public IActionResult EditProduct(ProductEditViewModel ProductEditViewModel)
        {
            ProductEditViewModel.Product.CategoryId = ProductEditViewModel.CategoryId;
            ProductEditViewModel.Product.BrandId    = ProductEditViewModel.BrandId;
            if (ModelState.GetValidationState("Product.Price") == ModelValidationState.Valid && ProductEditViewModel.Product.Price < 0)
            {
                ModelState.AddModelError(nameof(ProductEditViewModel.Product.Price), "invalid price");
            }
            if (ModelState.IsValid)
            {
                if (ProductEditViewModel.Photo != null)
                {
                    ProductEditViewModel.Product.Image = uploadFile.ProcessUploadedFile(ProductEditViewModel.Photo, "Products");
                    //ProcessUploadedFile(ProductEditViewModel);
                }
                ProductEditViewModel.Product.BrandId    = ProductEditViewModel.BrandId;
                ProductEditViewModel.Product.CategoryId = ProductEditViewModel.CategoryId;

                _productRepository.UpdateProduct(ProductEditViewModel.Product);
                return(RedirectToAction("Index"));
            }

            var categories = _categoryRepository.AllCategories;
            var brands     = _brandRepository.AllBrands;

            ProductEditViewModel = new ProductEditViewModel
            {
                Categories = categories.Select(c => new SelectListItem()
                {
                    Text = c.Cat_Name, Value = c.Cat_Id.ToString()
                }).ToList(),
                Brands = brands.Select(c => new SelectListItem()
                {
                    Text = c.Brand_Name, Value = c.Brand_Id.ToString()
                }).ToList(),

                CategoryId = ProductEditViewModel.Product.CategoryId,
                BrandId    = ProductEditViewModel.Product.BrandId
            };
            var item = ProductEditViewModel.Categories.FirstOrDefault(c => c.Value == ProductEditViewModel.CategoryId.ToString());

            item.Selected = true;
            item          = ProductEditViewModel.Brands.FirstOrDefault(c => c.Value == ProductEditViewModel.BrandId.ToString());
            item.Selected = true;

            return(View(ProductEditViewModel));
        }
Ejemplo n.º 32
0
        public IActionResult Edit(int id)
        {
            var product = _context.Products.Include(p => p.Supplier).SingleOrDefault(p => p.Id == id);

            if (product == null)
            {
                return(NotFound());
            }

            var vm = new ProductEditViewModel
            {
                Product   = product,
                Suppliers = _context.Suppliers.OrderBy(s => s.CompanyName).ToList()
            };

            return(View(vm));
        }
Ejemplo n.º 33
0
        public ActionResult ProductsJson(HttpPostedFileBase file)
        {
            if (file.ContentLength <= 0) return View();

            var rootPath = Server.MapPath("~/Import");
            var guid = Guid.NewGuid().ToString();
            var path = Path.Combine(rootPath, guid);
            Directory.CreateDirectory(path);
            file.SaveAs(Path.Combine(rootPath, guid + ".zip"));
            using (var zip = new ZipFile(Path.Combine(rootPath, guid + ".zip")))
            {
                zip.FlattenFoldersOnExtract = true;
                zip.ExtractAll(path);
            }
            System.IO.File.Delete(Path.Combine(rootPath, guid + ".zip"));

            var imgIdMap = new Dictionary<Guid, Guid>();
            foreach (var imgFile in Directory.GetFiles(path, "*.jpg"))
            {
                var imgId = Guid.Parse(Path.GetFileNameWithoutExtension(imgFile));
                var dbUpl = db.Uploads.FirstOrDefault(u => u.Id == imgId);
                if (dbUpl == null)
                {
                    dbUpl = new Upload { Type = UploadType.ProductImage };
                    db.Uploads.Add(dbUpl);
                    db.SaveChanges();

                    System.IO.File.Copy(imgFile, Path.Combine(Server.MapPath("~/Storage"), dbUpl.Id.ToString()), true);
                }
                imgIdMap.Add(imgId, dbUpl.Id);
            }

            if (System.IO.File.Exists(Path.Combine(path, "export.json")))
            {
                // TODO: Use text reader for very large jsons
                // Import json
                /*
                using (var sr = new StreamReader(Path.Combine(path, "export.json")))
                using (var reader = new JsonTextReader(sr))
                {
                    while (reader.Read())
                    {
                        if ()
                    }
                }
                */

                dynamic json = JObject.Parse(System.IO.File.ReadAllText(Path.Combine(path, "export.json")));

                var categoryidMap = new Dictionary<int, int>();
                var optCategoryidMap = new Dictionary<int, int>();
                var optMap = new Dictionary<int, int>();
                var prodMap = new Dictionary<int, int>();

                foreach (var category in json.categories)
                {
                    int? parentId = category.parentId;
                    if (parentId != null) parentId = categoryidMap[(int)category.parentId];
                    string name = category.name;
                    var dbCategory = categoryService.FindAll()
                        .FirstOrDefault(c => c.Name == name && c.ParentId == parentId);
                    if (dbCategory == null)
                    {
                        var categoryModel = new CategoryEditViewModel
                                            {
                                                Name = category.name,
                                                Description = category.description,
                                                IsVisible = category.isVisible ?? true,
                                                SortOrder = category.sortOrder ?? 0
                                            };
                        if (category.parentId != null)
                            categoryModel.ParentId = categoryidMap[(int)category.parentId];
                        dbCategory = categoryService.AddOrUpdate(categoryModel);
                    }
                    categoryidMap.Add((int)category.id, dbCategory.Id);
                }

                foreach (var optCategory in json.optionCategories)
                {
                    string name = optCategory.name;
                    var dbOptCategory = db.OptionCategories.FirstOrDefault(c => c.Name == name);
                    if (dbOptCategory == null)
                    {
                        dbOptCategory = new OptionCategory
                                            {
                                                Name = optCategory.name,
                                                Description = optCategory.description,
                                                Type = optCategory.type,
                                                IncludeInFilters = optCategory.includeInFilters
                                            };
                        db.OptionCategories.Add(dbOptCategory);
                        db.SaveChanges();
                    }
                    optCategoryidMap.Add((int)optCategory.id, dbOptCategory.Id);
                }

                foreach (var option in json.options)
                {
                    string name = option.name;
                    int catId = optCategoryidMap[(int)option.optionCategoryId];
                    var dbOpt = db.Options.FirstOrDefault(o => o.Name == name && o.OptionCategoryId == catId);
                    if (dbOpt == null)
                    {
                        dbOpt = new Option
                                {
                                    Name = option.name,
                                    Description = option.description,
                                    OptionCategoryId = catId,
                                };
                        db.Options.Add(dbOpt);
                        db.SaveChanges();
                    }
                    optMap.Add((int)option.id, dbOpt.Id);
                }

                foreach (var product in json.products)
                {
                    string name = product.name;
                    var dbProd = productFinder.FindAll().FirstOrDefault(p => p.Name == name);
                    if (dbProd == null)
                    {
                        var prodModel = new ProductEditViewModel();
                        prodModel.Sku = product.sku;
                        prodModel.Name = product.name;
                        prodModel.Description = product.description;
                        prodModel.Price = product.price ?? 0;
                        prodModel.RetailPrice = product.retailPrice;
                        prodModel.CostPrice = product.costPrice;
                        prodModel.SalePrice = product.salePrice;
                        prodModel.IsFeatured = product.isFeatured;
                        prodModel.IsVisible = product.isVisible;
                        prodModel.CategoryIds = string.Join(",", ((JArray)product.categories).Select(
                            i => categoryidMap[(int)i].ToString()));
                        prodModel.Keywords = product.keywords;
                        prodModel.Quantity = product.quantity;
                        prodModel.TaxClassId = product.taxClassid;
                        prodModel.Weight = product.weight ?? 0;
                        prodModel.OptionIds = string.Join(",", ((JArray)product.options).Select(
                            i => optMap[(int)i].ToString()));
                        if (product.sections != null)
                        {
                            foreach (var sect in product.sections)
                            {
                                var sectModel = new ProductSectionEditViewModel
                                                {
                                                    Title = sect.title,
                                                    Type = sect.type,
                                                    Position = sect.position,
                                                    Settings = sect.settings,
                                                    Priority = sect.priority,
                                                    Text = sect.text
                                                };
                                prodModel.Sections.Add(sectModel);
                            }
                        }
                        if (product.uploads != null)
                        {
                            foreach (var upl in product.uploads)
                            {
                                if (prodModel.UploadIds == null)
                                    prodModel.UploadIds = "";
                                else
                                    prodModel.UploadIds += ",";
                                prodModel.UploadIds += imgIdMap[(Guid)upl.id];
                            }
                        }
                        if (product.skus != null)
                        {
                            foreach (var sku in product.skus)
                            {
                                var optIds = new List<int>();
                                if (sku.options != null)
                                {
                                    foreach (int optId in sku.options)
                                    {
                                        optIds.Add(optMap[optId]);
                                    }
                                }
                                var uploadIds = new List<Guid>();
                                if (sku.uploads != null)
                                {
                                    foreach (var uplId in sku.uploads)
                                    {
                                        uploadIds.Add(imgIdMap[(Guid)uplId]);
                                    }
                                }
                                prodModel.Skus.Skus.Add(
                                    new ProductSkuEditViewModel
                                    {
                                        Sku = sku.sku,
                                        Price = sku.price,
                                        Quantity = sku.quantity,
                                        UPC = sku.upc,
                                        Weight = sku.weight,
                                        OptionIds = JsonConvert.SerializeObject(optIds.ToArray()),
                                        UploadIds = JsonConvert.SerializeObject(uploadIds.ToArray())
                                    });
                            }
                        }
                        dbProd = productService.CreateOrUpdate(prodModel);
                    }
                    prodMap.Add((int)product.id, dbProd.Id);
                }
            }

            return View().WithInfo(
                "Data import has been initiated. You will receive notification as soon as the import is completed".TA());
        }
Ejemplo n.º 34
0
        public ActionResult Edit(Product product)
        {
            if (_captchaTasks.Validate(ConfigurationManager.AppSettings["ReCaptchaPrivate"]))
            {
                if (ModelState.IsValid && product.IsValid())
                {
                    _productTasks.CreateOrUpdate(product);
                    return this.RedirectToAction(x => x.Index(null));
                }
            }
            else
                ModelState.AddModelError("ReCaptcha", "ReCaptcha failed!");

            var model = new ProductEditViewModel
            {
                Categories = _categoryTasks.GetAll(),
                Product = product,
                SelectedCategoryId = product.Category.Id
            };

            if (product.Id == 0)
                return View("Create", model);
            return View(model);
        }
Ejemplo n.º 35
0
        public Product CreateOrUpdate(ProductEditViewModel productEditViewModel)
        {
            // Add or update product domain object
            Product product;
            if (productEditViewModel.Id > 0)
            {
                product = productFinder.Find(productEditViewModel.Id);
                product = Mapper.Map(productEditViewModel, product);
            }
            else
            {
                product = Mapper.Map<Product>(productEditViewModel);
                db.Products.Add(product);
            }

            // Set categories
            var categoryIds = string.IsNullOrEmpty(productEditViewModel.CategoryIds)
                ? new int[0]
                : productEditViewModel.CategoryIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(c => Convert.ToInt32(c)).ToArray();

            if (product.Id > 0)
            {
                foreach (var category in product.Categories.ToList())
                {
                    if (!categoryIds.Contains(category.Id))
                    {
                        product.Categories.Remove(category);
                    }
                }
            }
            foreach (int categoryId in categoryIds)
            {
                if (!product.Categories.Any(c => c.Id == categoryId))
                {
                    Category category = categoryService.Find(categoryId);
                    product.Categories.Add(category);
                }
            }

            // Add photos
            string[] uploadIds = string.IsNullOrEmpty(productEditViewModel.UploadIds)
                ? new string[0]
                : productEditViewModel.UploadIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if (product.Id > 0)
            {
                foreach (Upload upload in product.Uploads.ToList())
                {
                    if (!uploadIds.Contains(upload.Id.ToString()))
                    {
                        db.Uploads.Remove(upload);
                    }
                }
            }
            foreach (string uploadId in uploadIds)
            {
                if (string.IsNullOrWhiteSpace(uploadId)) continue;
                Guid id = Guid.Parse(uploadId);
                Upload upload = db.Uploads.First(u => u.Id == id);
                upload.Product = product;
            }

            // Set options
            var optionIds = string.IsNullOrEmpty(productEditViewModel.OptionIds)
                ? new int[0]
                : productEditViewModel.OptionIds.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                    .Select(c => Convert.ToInt32(c)).ToArray();

            if (product.Id > 0)
            {
                foreach (var option in product.Options.ToList())
                {
                    if (!optionIds.Contains(option.Id))
                    {
                        product.Options.Remove(option);
                    }
                }
            }
            foreach (int optionId in optionIds)
            {
                if (!product.Options.Any(o => o.Id == optionId))
                {
                    Option option = db.Options.Find(optionId);
                    product.Options.Add(option);
                }
            }

            if (product.Id > 0)
            {
                // Delete removed sections
                var sectionIds = productEditViewModel.Sections.Where(s => s.Id > 0).Select(s => s.Id).ToArray();
                foreach (var sectionToDelete in product.Sections.Where(s => !sectionIds.Contains(s.Id)).ToList())
                {
                    db.ProductSections.Remove(sectionToDelete);
                }
            }

            // Add/update sections
            foreach (var sectionViewModel in productEditViewModel.Sections)
            {
                var section = sectionViewModel.Id != 0
                    ? product.Sections.First(s => s.Id == sectionViewModel.Id)
                    : new ProductSection();
                Mapper.Map(sectionViewModel, section);

                if (section.Id == 0)
                    product.Sections.Add(section);
            }

            if (product.Id > 0)
            {
                // Delete removed skus
                var skus = productEditViewModel.Skus.Skus.Where(s => s.Id > 0).Select(s => s.Id).ToArray();
                foreach (var skusToDelete in product.Skus.Where(s => !skus.Contains(s.Id)).ToList())
                {
                    productSkuService.Delete(skusToDelete.Id);
                }
            }

            // Add/update skus
            foreach (var skuViewModel in productEditViewModel.Skus.Skus)
            {
                var sku = skuViewModel.Id != 0
                    ? product.Skus.FirstOrDefault(s => s.Id == skuViewModel.Id)
                    : new ProductSku();
                if (sku == null) continue;

                Mapper.Map(skuViewModel, sku);

                var skuOptionIds = JsonConvert.DeserializeObject<int[]>(skuViewModel.OptionIds);
                var skuUploadIds = JsonConvert.DeserializeObject<Guid[]>(skuViewModel.UploadIds);

                if (sku.Id > 0)
                {
                    foreach (var upload in sku.Uploads.ToList())
                    {
                        if (!skuUploadIds.Contains(upload.Id))
                        {
                            sku.Uploads.Remove(upload);
                        }
                    }
                }
                else
                {
                    product.Skus.Add(sku);
                }

                foreach (var optionId in skuOptionIds)
                {
                    var option = db.Options.Find(optionId);
                    if (option != null && !sku.Options.Any(o => o.Id == optionId))
                        sku.Options.Add(option);
                }
                foreach (var uploadId in skuUploadIds)
                {
                    var upload = db.Uploads.Find(uploadId);
                    if (upload != null && !sku.Uploads.Any(u => u.Id == uploadId))
                        sku.Uploads.Add(upload);
                }

            }

            db.SaveChanges();

            cacheService.Invalidate("products");

            return product;
        }
Ejemplo n.º 36
0
 public ActionResult Edit(int id)
 {
     var product = _productTasks.Get(id);
     var model = new ProductEditViewModel
     {
         Categories = _categoryTasks.GetAll(),
         Product = product,
         SelectedCategoryId = product.Category.Id
     };
     return View(model);
 }
Ejemplo n.º 37
0
        public ActionResult Edit(ProductEditViewModel productEditViewModel)
        {
            if (ModelState.IsValid)
            {
                var product = productService.CreateOrUpdate(productEditViewModel);

                return RedirectToAction("Index")
                    .WithSuccess(string.Format("Product \"{0}\" have been updated".TA(), product.Name));
            }

            ViewBag.TaxClassId = new SelectList(taxClassService.FindAll().ToList().OrderBy(r => r.Name), "Id", "Name");
            return View(productEditViewModel);
        }