コード例 #1
0
        public async Task <IActionResult> Create(/*[Bind("ProductId,Name,ExpiryDate,Category,ShelfNumber,CupboardName")]*/ ProductDetailsViewModel productDetailsViewModel)
        {
            if (ModelState.IsValid)
            {
                _context.Add(ProductHelper.MapToProduct(productDetailsViewModel));
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(productDetailsViewModel));
        }
コード例 #2
0
ファイル: ProductController.cs プロジェクト: mrkhangtran/TaTa
        public async Task <IActionResult> Details(ProductDetailsViewModel model)
        {
            if (!ModelState.IsValid)
            {
                ViewBag.Categories = await BuildProductCategoriesSelectList();

                ViewBag.Currencies = BuildCurrenciesSelectList();
                return(View(model));
            }

            var product = Mapper.Instance.Map <ProductDetailsViewModel, Product>(model);

            // clear the placeholder rows
            product.Properties.RemoveAll(x => string.IsNullOrEmpty(x.Name));
            product.Prices.RemoveAll(x => string.IsNullOrEmpty(x.Name));

            using (IUnitOfWork uow = _uowProvider.CreateUnitOfWork())
            {
                var propertyRepo = uow.GetRepository <ProductProperty>();
                var priceRepo    = uow.GetRepository <ProductPrice>();
                var productRepo  = uow.GetRepository <Product>();

                if (product.Id > 0)
                {
                    foreach (var propertyModel in model.Properties)
                    {
                        if (propertyModel.NeedDelete)
                        {
                            product.Properties.Remove(product.Properties.SingleOrDefault(x => x.Id == propertyModel.Id));
                            var property = await propertyRepo.GetAsync(propertyModel.Id);

                            if (property != null)
                            {
                                propertyRepo.Remove(property);
                            }
                        }
                    }

                    foreach (var priceModel in model.Prices)
                    {
                        if (priceModel.NeedDelete)
                        {
                            product.Prices.Remove(product.Prices.SingleOrDefault(x => x.Id == priceModel.Id));
                            var price = await priceRepo.GetAsync(priceModel.Id);

                            if (price != null)
                            {
                                priceRepo.Remove(price);
                            }
                        }
                    }

                    productRepo.Update(product);
                }
                else
                {
                    productRepo.Add(product);
                }

                await uow.SaveChangesAsync();
            }

            return(RedirectToAction("Index"));
        }
コード例 #3
0
        public ViewResult ViewProductMaker(string id)
        {
            var productMaker = _context.ProductMakers.Find(id);
            var model = new ProductDetailsViewModel
            {
                Id = productMaker.Id,
                Name = productMaker.Name
            };

            return View(model);
        }
コード例 #4
0
 public CartLineViewModel(ProductDetailsViewModel model, int quantity)
 {
     this.Model     = model;
     this.Quantity  = quantity;
     this.ProductId = this.Model.Id;
 }
コード例 #5
0
 public ProductDetailsController()
 {
     _productService          = new ProductsService();
     _productDetailsViewModel = new ProductDetailsViewModel();
 }
コード例 #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ProviderDetailsView"/> class.
 /// </summary>
 public ProviderDetailsView()
 {
     InitializeComponent();
     DataContext = new ProductDetailsViewModel();
 }
コード例 #7
0
        public IActionResult Delete(ProductDetailsViewModel model)
        {
            this.productService.DeleteProductById(model.Id);

            return(this.RedirectToAction("/"));
        }
コード例 #8
0
        public ResponseModel CreateProductDetails(ProductDetailsViewModel aObj)
        {
            using (var transaction = _db.Database.BeginTransaction())
            {
                try
                {
                    DateTime   aDate    = DateTime.Now;
                    InvProduct aProduct = new InvProduct()
                    {
                        ProductId             = aObj.ProductId,
                        ProductCode           = aObj.ProductCode,
                        ProductName           = aObj.ProductName,
                        ProductMainBarcode    = aObj.ProductMainBarcode,
                        ProductFactoryBarcode = aObj.ProductFactoryBarcode,
                        FactoryId             = aObj.FactoryId,
                        ItemId            = aObj.ItemId,
                        SizeId            = aObj.SizeId,
                        ColorId           = aObj.ColorId,
                        UoMId             = aObj.UoMId,
                        MinimumStock      = aObj.MinimumStock,
                        ProductFrontImage = aObj.ProductFrontImage,
                        ProductBackImage  = aObj.ProductBackImage,

                        CreatedDate = aDate,
                        IsActive    = aObj.ProductIsActive,
                    };

                    if ((aObj.ProductId == 0)) //this is new
                    {
                        var statusProductCode =
                            _aRepository.SelectAll().Where((pc => pc.ProductCode == aObj.ProductCode));
                        var statusProductMainBarcode =
                            _aRepository.SelectAll().Where((pc => pc.ProductMainBarcode == aObj.ProductMainBarcode)).ToList();
                        //    List<InvProduct> statusProductFactoryBarcode = null;
                        if (aObj.ProductFactoryBarcode != null)
                        {
                            var statusProductFactoryBarcode =
                                _aRepository.SelectAll()
                                .Where((pc => pc.ProductFactoryBarcode == aObj.ProductFactoryBarcode))
                                .ToList();
                            if (statusProductFactoryBarcode.Any())
                            {
                                return(_aModel.Respons(true, "Product Factory Bar Code Already Exist."));
                            }
                        }

                        if ((aObj.ProductCode == null) || (aObj.ProductMainBarcode == null) || (aObj.RetailPrice == null) || (aObj.CostPrice == null) || (aObj.WholeSalePrice == null) || (aObj.ProductCode == null))
                        {
                            return(_aModel.Respons(true, "Plese Fill All the Required Field(s)"));
                        }
                        else if (statusProductCode.Any())
                        {
                            return(_aModel.Respons(true, "Product Code Already Exist."));
                        }
                        else if (statusProductMainBarcode.Any())
                        {
                            return(_aModel.Respons(true, "Product Main Bar Code Already Exist."));
                        }
                        else if ((aObj.ProductCode != null) && (aObj.ProductMainBarcode != null) && (aObj.CostPrice != null) && (aObj.WholeSalePrice != null) &&
                                 (aObj.RetailPrice != null))
                        {
                            _db.InvProducts.Add(aProduct);
                            _db.SaveChanges();

                            InvProductPrice aProductPrice = new InvProductPrice()
                            {
                                ProductPriceId = aObj.ProductPriceId,
                                ProductId      = aProduct.ProductId,
                                CostPrice      = aObj.CostPrice,
                                WholeSalePrice = aObj.WholeSalePrice,
                                RetailPrice    = aObj.RetailPrice,
                                CreatedDate    = aDate,
                                IsActive       = true
                            };
                            _db.InvProductPrices.Add(aProductPrice);
                            _db.SaveChanges();
                            transaction.Commit();
                            return(_aModel.Respons(true, "New Product Successfully Saved"));
                        }
                        else
                        {
                            _db.SaveChanges();
                            transaction.Commit();
                            return(_aModel.Respons(true, "Failed to  Save New Product"));
                        }
                    }
                    else if ((aObj.ProductId > 0) && ((aObj.ProductMainBarcode != null) || (aObj.ProductFactoryBarcode != null)) && (aObj.ProductCode != null) && (aObj.CostPrice != null) &&
                             (aObj.WholeSalePrice != null) && (aObj.RetailPrice != null))
                    {
                        _db.InvProducts.Attach(aProduct);
                        _db.Entry(aProduct).State = EntityState.Modified;
                        _db.SaveChanges();

                        //start price checking logic

                        var invProductPrice = _db.InvProductPrices.Find(aObj.ProductPriceId);

                        if ((invProductPrice.CostPrice != aObj.CostPrice) || (invProductPrice.WholeSalePrice != aObj.WholeSalePrice) || (invProductPrice.RetailPrice != aObj.RetailPrice))
                        {
                            //inactive previous price
                            invProductPrice.IsActive     = false;
                            invProductPrice.ModifiedDate = aDate;

                            _db.InvProductPrices.Attach(invProductPrice);
                            _db.Entry(invProductPrice).State = EntityState.Modified;
                            _db.SaveChanges();

                            //creaete new price
                            InvProductPrice aProductPrice = new InvProductPrice()
                            {
                                ProductPriceId = aObj.ProductPriceId,
                                ProductId      = aObj.ProductId,
                                CostPrice      = aObj.CostPrice,
                                WholeSalePrice = aObj.WholeSalePrice,
                                RetailPrice    = aObj.RetailPrice,
                                CreatedDate    = aDate,
                                IsActive       = true
                            };
                            _db.InvProductPrices.Add(aProductPrice);
                            _db.SaveChanges();
                        }
                        transaction.Commit();
                        return(_aModel.Respons(true, "New Product Successfully Updated"));
                    }
                    else
                    {
                        transaction.Commit();
                        return(_aModel.Respons(true, "Failed to Updated a Product"));
                    }
                } // end of Try section
                catch (Exception e)
                {
                    transaction.Rollback();
                    return(_aModel.Respons(false, "Sorry! Some  Error Happned"));
                }
            }
        }
コード例 #9
0
        public ActionResult Product(int?id, string model)
        {
            if (id == null)
            {
                return(RedirectToAction("Index", "Shop"));
            }

            ProductDetailsViewModel productDetails = new ProductDetailsViewModel();

            productDetails.isEligibleToAddOpinion = true;

            Item product = db.Items.Find(id);

            if (product == null)
            {
                return(View("Index"));
            }

            if (model != null)
            {
                if (model != "")
                {
                    Session["productModel"] = model;
                }
            }

            List <Item> lastViewedItems = new List <Item>();

            if (Session["lastViewedItems"] != null)
            {
                lastViewedItems = (List <Item>)(Session["lastViewedItems"]);
            }

            if (lastViewedItems.Where(itemId => itemId.idItem == product.idItem).ToList().Count() <= 0)
            {
                lastViewedItems = lastViewedItems.Append(product).ToList();
            }
            else
            {
                int index = lastViewedItems.FindIndex(itemId => itemId.idItem == product.idItem);
                lastViewedItems.RemoveAt(index);
                lastViewedItems = lastViewedItems.Append(product).ToList();
            }

            if (lastViewedItems.Count() >= 10)
            {
                lastViewedItems = lastViewedItems.Skip(lastViewedItems.Count() - 10).Take(10).ToList();
            }

            Session["lastViewedItems"] = lastViewedItems;

            productDetails.FeaturesList = new List <Tuple <string, List <string>, bool> >();

            productDetails.product = product;
            List <FeatureValueOfItem> featuresOfItem = db.FeatureValueOfItems.Where(item => item.Item_idItem1 == id).ToList();

            List <string> featuresList = featuresOfItem.Select(feat => feat.Feature.feature1).Distinct().ToList();

            foreach (var feat in featuresList)
            {
                List <string> featVal      = featuresOfItem.Where(feature => feature.Feature.feature1 == feat).Select(fe => fe.FeatureValue.featureValue1).ToList();
                bool          isSelectable = (featuresOfItem.Where(feature => feature.Feature.feature1 == feat).Select(fe => fe.Feature.selectable).First() != null) ? (bool)(featuresOfItem.Where(feature => feature.Feature.feature1 == feat).Select(fe => fe.Feature.selectable).First()) : false;

                Tuple <string, List <string>, bool> featureValues = new Tuple <string, List <string>, bool>(feat, featVal, isSelectable);

                productDetails.FeaturesList.Add(featureValues);
            }

            //productDetails.productDetail.FeaturesList = db.FeatureValueOfItems.Where(item => item.Item_idItem1 == id).ToList();
            productDetails.opinions = db.Opinions.Where(opinion => opinion.Item_idItem == id).ToList();

            if (User.Identity.IsAuthenticated)
            {
                List <Customer> c = db.Customers.Where(user => user.AspNetUser.UserName == User.Identity.Name).ToList();

                int?customerId = null;
                if (c != null)
                {
                    if (c.Count() > 0)
                    {
                        customerId = c.First().idCustomer;
                    }
                }

                if (customerId == null)
                {
                    productDetails.isEligibleToAddOpinion = false;
                }

                int stateRealised = db.SaleStates.Where(i => i.state == "zrealizowane").First().idSaleState;

                List <SaleDetail> isEligibleToAddOpinion = db.SaleDetails.Include(d => d.Sale).Where(item => item.Item_idItem == (int)id).Where(cust => cust.Sale.Customer_idCustomer == customerId).Where(state => state.Sale.SaleState_idSaleState == stateRealised).ToList();

                if (isEligibleToAddOpinion.Count() <= 0)
                {
                    productDetails.isEligibleToAddOpinion = false;
                }
            }
            else
            {
                productDetails.isEligibleToAddOpinion = false;
            }

            return(View(productDetails));
        }
コード例 #10
0
 public ProductDetailsView(FoodItem foodItem)
 {
     InitializeComponent();
     BindingContext = new ProductDetailsViewModel(foodItem);
 }
コード例 #11
0
 public ProductDetails(Product Product)
 {
     NavigationPage.SetHasNavigationBar(this, false);
     InitializeComponent();
     BindingContext = new ProductDetailsViewModel(Navigation, Product);
 }
コード例 #12
0
 public OrderDetailViewModel(ProductDetailsViewModel product, int quantity, SizeViewModel size)
 {
     this.Product  = product;
     this.Quantity = quantity;
     this.Size     = size;
 }
コード例 #13
0
 public EditProductEventArgs(ProductDetailsViewModel model)
 {
     this.Model = model;
 }
コード例 #14
0
ファイル: SklepController.cs プロジェクト: Deena786/SukkuShop
        //[DonutOutputCache(Duration = 86400, VaryByParam = "id",Location = OutputCacheLocation.Server)]
        public virtual ActionResult SzczegółyProduktu(int id = 1)
        {
            var product = _appRepository.GetSingle <Products>(x => x.ProductId == id && x.Published && !x.WrongModel);

            if (product == null)
            {
                return(View(MVC.Sklep.Views.NoProducts));
            }

            var category      = _appRepository.GetSingle <Categories>(x => x.CategoryId == product.CategoryId);
            var subCategories = new List <int>();

            if (category.UpperCategoryId == 0)
            {
                subCategories =
                    _appRepository.GetAll <Categories>(m => m.UpperCategoryId == category.CategoryId)
                    .Select(x => x.CategoryId)
                    .ToList();
            }

            var similarProducts =
                _appRepository.GetAll <Products>(
                    x =>
                    (x.CategoryId == product.CategoryId || subCategories.Contains(x.CategoryId ?? -1)) &&
                    x.ProductId != product.ProductId && x.Published).Select(j => new SimilarProductModel
            {
                Id        = j.ProductId,
                ImageName = j.IconName ?? "NoPhoto_small",
                Name      = j.Name,
                Price     = j.Price ?? 0,
                Available = j.Quantity - j.ReservedQuantity > 0,
                Promotion = j.Promotion
            }).OrderBy(k => Guid.NewGuid()).Take(4).ToList();

            foreach (var itemSimilar in similarProducts)
            {
                var priceSimilar = (itemSimilar.Price - ((itemSimilar.Price * itemSimilar.Promotion) / 100)) ??
                                   itemSimilar.Price;
                var similarFloored = Math.Floor(priceSimilar * 100) / 100;
                itemSimilar.PriceAfterDiscount = similarFloored;
            }
            var price        = (product.Price - ((product.Price * product.Promotion) / 100)) ?? product.Price;
            var priceFloored = Math.Floor((price ?? 0) * 100) / 100;
            var model        = new ProductDetailsViewModel
            {
                Product = new ProductDetailModel
                {
                    Category           = category.Name,
                    Id                 = product.ProductId,
                    ImageName          = product.ImageName ?? "NoPhoto_normal",
                    Name               = product.Name,
                    Price              = product.Price ?? 0,
                    PriceAfterDiscount = priceFloored,
                    Promotion          = product.Promotion ?? 0,
                    QuantityInStock    = product.Quantity ?? 0,
                    Packing            = product.Packing,
                    Description        = product.Description,
                    ReservedQuantity   = product.ReservedQuantity,
                    IconName           = product.IconName ?? "NoPhoto_small"
                },
                SimilarProducts = similarProducts
            };

            return(View(model));
        }
コード例 #15
0
        public async Task <IActionResult> Edit(long id, /*[Bind("ProductId,Name,ExpiryDate,Category,ShelfNumber,CupboardName,Price")]*/ ProductDetailsViewModel viewModel)
        {
            if (id != viewModel.ProductId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                Product product = ProductHelper.MapToProduct(viewModel);
                try
                {
                    _context.Update(product);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductExists(product.ProductId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(viewModel));
        }
コード例 #16
0
        public ActionResult Reserve(ProductDetailsViewModel moviemodel, DateTime?todaydate)
        {
            var product = db.Products.Find(moviemodel.ProductID);

            moviemodel.Product = product;
            if (todaydate.HasValue)
            {
                moviemodel.Month    = todaydate.Value;
                moviemodel.Calendar = product.GetCalendar(todaydate.Value.Year, todaydate.Value.Month);
                return(View(moviemodel));
            }
            if (ModelState.IsValid)
            {
                bool isvalid = true;
                //var user = db.Customers.Where(x => x.UserID == myUser).Select(c => c.Name);

                var    useridTest = User.Identity.GetUserId();
                var    user       = context.Users.FirstOrDefault(u => u.Id == useridTest);
                String em         = user.Email;
                EmailUtility.registerProduct(product.Name + " has been booked from " + moviemodel.StartDate + " until " + moviemodel.EndDate + " by " + em);
                //start date and end date validtions, ifs, startdate.hasvalue if null will be false, datetime.today=today's date
                //startdate must be at least today, if missing, if not today seperate errorr
                //enddate check if null,  along with or after startdate, must be later than start date


                for (DateTime d = moviemodel.StartDate ?? moviemodel.EndDate ?? DateTime.Today; d <= (moviemodel.EndDate ?? moviemodel.StartDate ?? DateTime.Today); d = d.AddDays(1))
                {
                    if (product.OpnInvDay(d) < moviemodel.Quantity)
                    {
                        //error, not enough available
                        ModelState.AddModelError("Quantity", "Sorry, we're out of stock on those days");
                        isvalid = false;
                        break;
                    }

                    if (DateTime.Now > moviemodel.StartDate)
                    {
                        ModelState.AddModelError("StartDate", "Select a present or future start date");
                        isvalid = false;
                        break;
                    }
                }
                if (moviemodel.StartDate < DateTime.Now /*|| moviemodel.EndDate > DateTime.Now*/)
                {
                    ModelState.AddModelError("EndDate", "End date must be after start date");
                    isvalid = false;
                }


                if (!isvalid)
                {
                    moviemodel.Calendar = product.GetCalendar(moviemodel.Month.Year, moviemodel.Month.Month);
                    return(View(moviemodel));
                }
                var userid = User.Identity.GetUserId();
                var cart   = db.Carts.FirstOrDefault(x => x.UserID == userid && x.OrderDate == null);


                if (cart == null)
                {
                    cart        = new Cart();
                    cart.UserID = userid;
                }

                var OLI = new OrderLineItem();
                OLI.Cart      = cart;
                OLI.EndDate   = moviemodel.EndDate.Value;
                OLI.StartDate = moviemodel.StartDate.Value;
                OLI.ProductID = moviemodel.ProductID;
                OLI.Quantity  = moviemodel.Quantity;
                db.OrderLineItems.Add(OLI);
                db.SaveChanges();

                return(RedirectToAction("Index"));
            }
            return(View(moviemodel));
        }
コード例 #17
0
        /// <summary>
        /// Adds product to cart
        /// </summary>
        /// <returns></returns>
        public ActionResult AddToCart(ProductDetailsViewModel model)
        {
            try
            {
                var userEmail = CookieManager.GetEmailFromUserCookie();

                AddToCartDTO addToCartDto;

                //This would mean that the user has logged in from the AddToCart page (using login link on top right of page).
                //Therefore, the ProductViewModel parameter quantity value will be zero in this exceptional case.
                //Just create AddToCartViewModel object and return View passing in AddToCartViewModel object without modify cart of user logging in
                if (model.SelectedQuantity == 0)
                {
                    var userCartItems = services.CartService.GetUserCartItems(userEmail);

                    //create associated viewmodel and pass into view
                    addToCartDto                = new AddToCartDTO();
                    addToCartDto.ProductID      = model.ProductID;
                    addToCartDto.ProductName    = model.ProductName;
                    addToCartDto.CartItemsCount = userCartItems.Count();
                    addToCartDto.SubTotal       = userCartItems.Sum(ci => ci.Product.Price * ci.Quantity);
                    return(View(addToCartDto));
                }

                // Get the matching cart and product instances
                var cartItem = services.CartService.GetCartItem(userEmail, model.ProductID);

                if (cartItem == null)
                {
                    // Create a new cart item if no cart item exists
                    cartItem = new CartItem
                    {
                        ProductID   = model.ProductID,
                        Email       = userEmail,
                        Quantity    = model.SelectedQuantity,
                        DateCreated = DateTime.Now,
                    };

                    services.CartService.AddCartItem(cartItem);
                }
                else
                {
                    // If the item does exist in the cart,
                    // then increase cart item quantity by quantity parameter amount
                    cartItem.Quantity += model.SelectedQuantity;
                    services.CartService.UpdateCartItem(cartItem);
                }

                var cartItems = services.CartService.GetUserCartItems(userEmail, Constants.DATABASE_TABLE_PRODUCTS);

                //create associated viewmodel and pass into view
                addToCartDto                = new AddToCartDTO();
                addToCartDto.ProductID      = cartItem.ProductID;
                addToCartDto.ProductName    = cartItem.Product.Name;
                addToCartDto.CartItemsCount = cartItems.Count();
                addToCartDto.SubTotal       = cartItems.Sum(ci => ci.Product.Price * ci.Quantity);

                return(View(addToCartDto));
            }
            catch (Exception ex)
            {
                ExceptionManager.LogException(ex, Path.GetFileName(Request.PhysicalPath));
                return(RedirectToAction(Constants.CONTROLLER_ACTION_INDEX, Constants.CONTROLLER_ERROR));
            }
        }
コード例 #18
0
 public async Task OnGet(int id)
 {
     this.productCountToBuy.Number = 1;
     this.ProductModel             = await this.productsService.GetDetails(id);
 }
コード例 #19
0
        public void Setup()
        {
            var products = new List <Product>
            {
                new Product {
                    ItemId = 100
                }, new Product {
                    ItemId = 101
                }, new Product {
                    ItemId = 102
                }
            };
            var productsResult = new ProductsViewModel()
            {
                Products = products
            };

            var productDetails = new List <ProductDetails>
            {
                new ProductDetails()
                {
                    ItemId = 1, Name = "Product A"
                },
                new ProductDetails()
                {
                    ItemId = 2,
                    Name   = "Product B"
                }
            };
            var productDetailsResult = new ProductDetailsViewModel()
            {
                ProductDetailsList = productDetails
            };

            var recommendations = new List <Product>
            {
                new Product {
                    ItemId = 11
                }, new Product {
                    ItemId = 22
                }, new Product {
                    ItemId = 33
                }, new Product {
                    ItemId = 44
                }
            };
            var productRecommendationResult = new ProductsViewModel()
            {
                Products = recommendations
            };

            _productService = new Mock <IProductService>();

            _productService.Setup(a => a.SearchProducts(It.IsAny <string>()))
            .Returns(Task.FromResult(productsResult));

            _productService.Setup(a => a.GetProductDetails(It.IsAny <string>()))
            .Returns(Task.FromResult(productDetailsResult));

            _productService.Setup(a => a.GetRecommendations(It.IsAny <int>()))
            .Returns(Task.FromResult(productRecommendationResult));
        }
コード例 #20
0
        public IActionResult Details(string id)
        {
            ProductDetailsViewModel productViewModel = this.productService.GetById(id).To <ProductDetailsViewModel>();

            return(View(productViewModel));
        }
コード例 #21
0
        public IActionResult Edit(ProductDetailsViewModel model)
        {
            this.productService.EditProduct(model);

            return(this.RedirectToAction($"/Products/Details?Id={model.Id}"));
        }
コード例 #22
0
 public ProductDetailsPage(Product product)
 {
     InitializeComponent();
     BindingContext = viewModel = new ProductDetailsViewModel(product);
 }