Exemplo n.º 1
0
        public IActionResult Post([FromBody] ProductDetailsDTO prod)
        {
            if (prod == null)
            {
                return(BadRequest());
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var mappedProduct = Mapper.Map <Product>(prod);

            //This is make DTO simple for this example
            //Adding values for properties not present in ProductDetailsDTO
            //It errors out if NOT NUll values are not supplied
            mappedProduct.MakeFlag          = true;
            mappedProduct.FinishedGoodsFlag = true;
            mappedProduct.SafetyStockLevel  = 200;
            mappedProduct.SellStartDate     = DateTime.Now;
            mappedProduct.rowguid           = Guid.NewGuid();
            _productRepository.AddProduct(mappedProduct);
            if (!_productRepository.Save())
            {
                return(StatusCode(500, "A problem happened while handling your request."));
            }
            else
            {
                return(StatusCode(201, "Created Successfully"));
            }
        }
Exemplo n.º 2
0
        public ProductDetailsDTO GetProductDetails(int productId)
        {
            products            selectedProduct = db.products.Include("categories").Include("vendors").Include("vendors.regions").Include("vendors.regions.countries").Include("appellation").FirstOrDefault(x => x.id == productId);
            List <user_rates>   userRates       = db.user_rates.Where(x => x.product_id_id == productId).ToList();
            List <expert_rates> expertRates     = db.expert_rates.Where(x => x.product_id_id == productId).ToList();
            List <expert_product_characteristic> prodCharacteristics = db.expert_product_characteristic.Where(x => x.product_id_id == productId).ToList();

            var sweetnessCharacteristics = prodCharacteristics.Where(x => x.c_header_id_id == 1);
            var acidityCharacteristics   = prodCharacteristics.Where(x => x.c_header_id_id == 2);
            var tanninCharacteristics    = prodCharacteristics.Where(x => x.c_header_id_id == 3);
            var alcoholCharacteristics   = prodCharacteristics.Where(x => x.c_header_id_id == 4);
            var bodyCharacteristics      = prodCharacteristics.Where(x => x.c_header_id_id == 5);

            ProductDetailsDTO newDTO = new ProductDetailsDTO();

            newDTO.ProdID        = selectedProduct.id;
            newDTO.ProdName      = selectedProduct.name;
            newDTO.VendorName    = selectedProduct.vendors.name;
            newDTO.CategoryName  = selectedProduct.categories.name;
            newDTO.RegionName    = selectedProduct.vendors.regions.name;
            newDTO.CountryName   = selectedProduct.vendors.regions.countries.name;
            newDTO.PhotoPath     = selectedProduct.photo_path;
            newDTO.UserAvgRate   = userRates.Count > 0 ? userRates.Sum(x => x.rate) / userRates.Count : 0;
            newDTO.ExpertAvgRate = expertRates.Count > 0 ? expertRates.Sum(x => x.rate) / expertRates.Count : 0;
            newDTO.SweetnessRate = sweetnessCharacteristics.Count() > 0 ? sweetnessCharacteristics.Sum(x => x.characteristic_values) / sweetnessCharacteristics.Count() : 0;
            newDTO.AcidityRate   = acidityCharacteristics.Count() > 0 ? acidityCharacteristics.Sum(x => x.characteristic_values) / acidityCharacteristics.Count() : 0;
            newDTO.TanninRate    = tanninCharacteristics.Count() > 0 ? tanninCharacteristics.Sum(x => x.characteristic_values) / tanninCharacteristics.Count() : 0;
            newDTO.AlcoholRate   = alcoholCharacteristics.Count() > 0 ? alcoholCharacteristics.Sum(x => x.characteristic_values) / alcoholCharacteristics.Count() : 0;
            newDTO.BodyRate      = bodyCharacteristics.Count() > 0 ? bodyCharacteristics.Sum(x => x.characteristic_values) / bodyCharacteristics.Count() : 0;
            newDTO.Apellation    = selectedProduct.appellation != null ? selectedProduct.appellation.name : string.Empty;

            return(newDTO);
        }
Exemplo n.º 3
0
        public IQueryable <ProductDetailsDTO> GetProductDetailsDTOes(int productId, string opType)
        {
            List <ProductDetailsDTO> res = new List <ProductDetailsDTO>();

            switch (opType)
            {
            case "prodDetails":
                ProductDetailsDTO prod = service.GetProductDetails(productId);
                res = new List <ProductDetailsDTO>();
                res.Add(prod);
                break;

            case "userSuggestions": res = service.GetRecommendedProductsByProductCategory(productId);
                break;

            case "expertSuggestions": res = service.GetRecommendedProductsByCharacteristics(productId);
                break;

            default:
                break;
            }

            if (res == null)
            {
                return(null);
            }
            return(res.AsQueryable());
        }
Exemplo n.º 4
0
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string currentUrl = HttpContext.Current.Request.Url.AbsolutePath;
                if (currentUrl.Contains("product-details"))
                {
                    string    productID = currentUrl.Split('/').Last();
                    string    apiUrl    = WebConfigurationManager.AppSettings["WebApiUrl"] + "Product/GetProductById/" + productID;
                    WebClient client    = new WebClient();
                    client.Headers["Content-type"] = "application/json";
                    client.Encoding = Encoding.UTF8;
                    string json = client.DownloadString(apiUrl);

                    ProductDetailsDTO data = (new JavaScriptSerializer()).Deserialize <ProductDetailsDTO>(json);
                    if (data != null)
                    {
                        if (data.CurrentProduct != null)
                        {
                            this.AddMetaTagsToFacebook(data.CurrentProduct.name,
                                                       data.CurrentProduct.description, data.CurrentProduct.images.FirstOrDefault().imageUrl);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemplo n.º 5
0
        public ProductDetailsDTO GetProductById(int id)
        {
            var product = _db.ProductRepository.FindById(id);

            if (product == null)
            {
                return(null);
            }
            var productList = _db.ProductRepository.Get(i => i.Name == product.Name && i.Color == product.Color).ToList();

            List <IdSizeDTO> sizes = new List <IdSizeDTO>();

            foreach (var item in productList)
            {
                sizes.Add(new IdSizeDTO
                {
                    ProductId = item.Id,
                    Size      = item.Size,
                });
            }
            ProductDetailsDTO productDTO = new ProductDetailsDTO
            {
                Id             = product.Id,
                Category       = product.Category,
                Color          = product.Color,
                Name           = product.Name,
                PhotoUrl       = product.PhotoUrl,
                Price          = product.Price,
                ProductDetails = product.ProductDetails,
                Sizes          = sizes,
                Gender         = (GenderDTO)(int)product.Gender,
            };

            return(productDTO);
        }
Exemplo n.º 6
0
        public void GetProductById_ProductExist_ReturnProductDTO()
        {
            mock.Setup(i => i.ProductRepository.FindById(It.IsAny <int>())).Returns(new Product
            {
                Id             = 3,
                Category       = "a",
                Color          = "a",
                Date           = DateTimeOffset.Now,
                Gender         = Gender.Men,
                Name           = "a",
                PhotoUrl       = "a",
                Price          = 454,
                ProductDetails = "a",
                Size           = "L",
            });

            var productDTO = new ProductDetailsDTO
            {
                Category       = "a",
                Color          = "a",
                Name           = "a",
                PhotoUrl       = "a",
                Price          = 454,
                ProductDetails = "a",
            };
            var result = service.GetProductById(3);

            Assert.IsNotNull(result);
            Assert.AreEqual(result.Name, productDTO.Name);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> RentDetail()
        {
            ViewBag.CategoryMenuHeader = await GetCategoryMenu();

            var url       = RouteData.Values["url"];
            int productId = Utils.RegexRouteIdFromUrl(url.ToString());

            ViewBag.MetaTags = await _repoWrapper.Setting.GetSetting();

            var productTypeId = 4;

            ProductDetailsDTO model = await _repoWrapper.Service.GetProductDetails(productId);

            ViewBag.ListProductAds = await _repoWrapper.Product.GetSponsorBannerProduct(model.ProductDetails.ProductCategory_ID ?? 654, productTypeId, 5);

            ViewBag.ListProductByCate = await _repoWrapper.Product.GetListProductPagging(new ProductFilter { Page = 1, PageSize = 10, StatusTypeId = 4, ProductCategoryId = model.ProductDetails.ProductCategory_ID ?? 654, ProductTypeId = productTypeId });

            ViewBag.ListProductByProductBrand = await _repoWrapper.Product.GetListProductPagging(new ProductFilter { Page = 1, PageSize = 10, StatusTypeId = 4, ProductBrandId = model.ProductDetails.ProductBrand_ID, ProductTypeId = productTypeId });

            ViewBag.ProductCategoryCurrent = await _repoWrapper.ProductCategory.GetDetailProductCategory((int)model.ProductDetails.ProductCategory_ID);

            var profileBuyer = await _repoWrapper.Profile.ProfilersByUserId(model.ProductDetails.CreateBy);

            ViewBag.Buyer = profileBuyer.FullName;
            ViewBag.Phone = profileBuyer.Phone;
            return(View(model));
        }
Exemplo n.º 8
0
        public async Task <IActionResult> SellingProductDetails()
        {
            ViewBag.CategoryMenuHeader = await GetAllProductCategory();

            var url       = RouteData.Values["url"];
            int productId = Utils.RegexRouteIdFromUrl(url.ToString());

            ViewBag.MetaTags = await _repoWrapper.Setting.GetSetting();

            var productTypeId = 1;

            ProductDetailsDTO model = await _repoWrapper.Service.GetProductDetails(productId);

            if (model.ErrorCode == "00" || model.ErrorCode == "0")
            {
                ViewBag.ListProductAds = await _repoWrapper.Product.GetSponsorBannerProduct(model.ProductDetails.ProductCategory_ID ?? 654, productTypeId, 5);

                ViewBag.ListProductByCate = await _repoWrapper.Product.GetListProductPagging(new ProductFilter { Page = 1, PageSize = 10, StatusTypeId = 4, ProductCategoryId = model.ProductDetails.ProductCategory_ID ?? 654, ProductTypeId = productTypeId });

                ViewBag.ListProductByProductBrand = await _repoWrapper.Product.GetListProductPagging(new ProductFilter { Page = 1, PageSize = 10, StatusTypeId = 4, ProductBrandId = model.ProductDetails.ProductBrand_ID, ProductTypeId = productTypeId });

                ViewBag.ProductCategoryCurrent = await _repoWrapper.ProductCategory.GetDetailProductCategory((int)model.ProductDetails.ProductCategory_ID);

                return(View(model));
            }
            else
            {
                return(Redirect("/Error/404"));
            }
        }
Exemplo n.º 9
0
        public IActionResult Put(int id, [FromBody] ProductDetailsDTO prod)
        {
            if (prod == null)
            {
                return(BadRequest());
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (!_productRepository.ProductExists(id))
            {
                return(NotFound());
            }
            var saveprodrecord = _productRepository.GetProduct(id);

            Mapper.Map(prod, saveprodrecord);
            if (!_productRepository.Save())
            {
                return(StatusCode(500, "A problem happened while handling your request."));
            }
            else
            {
                return(StatusCode(202, "Updated Successfully"));
            }
        }
Exemplo n.º 10
0
        public ActionResult ProductDetails()
        {
            ProductDetailsDTO product = new ProductDetailsDTO();

            product.Photo  = @"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcSzl__tEa_WO_OcHIGgiwMk6vNNBRZ4DF2Zjm2BcPgQt8x_NRhL&usqp=CAU";
            product.Name   = "Варежки 'Бабушка-рукодельница'";
            product.Number = "123456";
            product.Sizes.Add("XS");
            product.Sizes.Add("S");
            product.Sizes.Add("M");
            product.Sizes.Add("L");
            product.Price       = 1555;
            product.Composition = "Шерсть";
            product.Color       = "Белый";
            product.Description = "Очень теплые варежки из натуральной бараньей  шерсти, заботливо связанные бабушкой Зиной из заснеженной Сибири.Эти варежки согреют вас холодной зимой, а запах прелого барана убережёт Вас от любой напасти: мужиков, детей, медведей, продавцов Oriflame и свидетелей Иеговы.";
            IndexDTO reviews1 = new IndexDTO();

            reviews1.NameCustomer = "Василий Петров";
            reviews1.DateReview   = new DateTime(2008, 02, 05);
            reviews1.TextReview   = "Варежки прекрасные!";
            IndexDTO reviews2 = new IndexDTO();

            reviews2.NameCustomer = "Мария Ситникова";
            reviews2.DateReview   = new DateTime(2008, 02, 06);
            reviews2.TextReview   = "Говно ваши варежки!";
            IndexDTO reviews3 = new IndexDTO();

            reviews3.NameCustomer = "Ольга Иванова";
            reviews3.DateReview   = new DateTime(2008, 02, 07);
            reviews3.TextReview   = "На разок пойдут…";
            IndexDTO reviews4 = new IndexDTO();

            reviews4.NameCustomer = "Василий Муравьев";
            reviews4.DateReview   = new DateTime(2008, 02, 05);
            reviews4.TextReview   = "Моя бабушка лучше вяжет. Обращайтесь!";
            IndexDTO reviews5 = new IndexDTO();

            reviews5.NameCustomer = "Петр Кошкин";
            reviews5.DateReview   = new DateTime(2008, 02, 05);
            reviews5.TextReview   = "В -30 в них холодно. Отморозила руки!";
            IndexDTO reviews6 = new IndexDTO();

            reviews6.NameCustomer = "Алла Пугачева";
            reviews6.DateReview   = new DateTime(2008, 02, 05);
            reviews6.TextReview   = "На зимнюю рыбалку вообще отлично!";
            IndexDTO reviews7 = new IndexDTO();

            reviews7.NameCustomer = "Вася Пупкин";
            reviews7.DateReview   = new DateTime(2008, 02, 05);
            reviews7.TextReview   = "Варежки пришли поеденные молью!";
            product.Reviews.Add(reviews1);
            product.Reviews.Add(reviews2);
            product.Reviews.Add(reviews3);
            product.Reviews.Add(reviews4);
            product.Reviews.Add(reviews5);
            product.Reviews.Add(reviews6);
            product.Reviews.Add(reviews7);
            return(View(product));
        }
Exemplo n.º 11
0
        public IQueryable <ProductDetailsDTO> GetProductById(int productId)
        {
            ProductDetailsDTO        prod = service.GetProductDetails(productId);
            List <ProductDetailsDTO> res  = new List <ProductDetailsDTO>();

            res.Add(prod);
            return(res.AsQueryable());
        }
        public async Task <ProductDetailsDTO> GetProductDetailsAsync(int productId)
        {
            ProductDetailsDTO product = await this.Where(p => p.Id == productId)
                                        .ProjectTo <ProductDetailsDTO>()
                                        .FirstOrDefaultAsync();

            return(product);
        }
Exemplo n.º 13
0
        public async Task <ProductDetailsDTO> GetShopmanProductDetails(int productId)
        {
            //var pr = hanomaContext.Product.FirstOrDefault();
            //var oktest = hanomaContext.Product
            //    .FromSqlRaw($"SELECT TOP 3 B.* " +
            //    $"FROM ProductBlockProduct A " +
            //    $"JOIN Product B ON A.Product_ID = B.Product_ID WHERE A.ProductBlock_ID = 1 ORDER BY B.LastEditDate")
            //    .AsNoTracking()
            //    .ToList();

            var output        = new ProductDetailsDTO();
            var productDetail = _repoWrapper.Product.FirstOrDefault(x => x.Product_ID == productId);

            if (productDetail == null)
            {
                output.ErrorCode = "P001";
                output.Message   = "Sản phẩm không tồn tại";
                return(output);
            }
            var productPicture = await _repoWrapper.ProductPicture.ShopmanGetByProductId(productId);

            var productBrand = _repoWrapper.Brand.FirstOrDefault(x => x.ProductBrand_ID == productDetail.ProductBrand_ID);

            output.ProductDetails = _mapper.Map <ProductDTO>(productDetail);
            ///output.ProductPictures = _mapper.Map<IEnumerable<ProductPictureDTO>>(productPicture);
            output.ProductPictures = productPicture;

            output.ProductBrand = _mapper.Map <BrandDTO>(productBrand);
            output.ProductDetails.ProductModelName       = _repoWrapper.ProductModel.FirstOrDefault(x => x.ProductModel_ID == productDetail.ProductModel_ID)?.Name;
            output.ProductDetails.ProductManufactureName = _repoWrapper.ProductManufacture.FirstOrDefault(x => x.ProductManufacture_ID == productDetail.ProductManufacture_ID)?.Name;
            output.ProductDetails.SaleLocationName       = _repoWrapper.Location.FirstOrDefault(x => x.Location_ID == productDetail.SaleLocation_ID)?.Name;
            output.ProductDetails.ProductCategoryName    = _repoWrapper.ProductCategory.FirstOrDefault(x => x.ProductCategory_ID == productDetail.ProductCategory_ID)?.Name;
            output.ProductDetails.CountryName            = _repoWrapper.Country.FirstOrDefault(x => x.Country_ID == productDetail.Country_ID)?.Name;
            output.ProductDetails.Content = HttpUtility.HtmlDecode(output.ProductDetails.Content);
            if (output.ProductDetails.ProductType_ID == 11) //Dịch vụ lấy trong bảng Unit
            {
                try
                {
                    var minor = await _repoWrapper.Unit.GetMinorByMinorId(Convert.ToInt32(productDetail.Unit));

                    output.ProductDetails.UnitName = minor?.MinorName;
                }
                catch (Exception ex)
                {
                }
            }
            else
            {
                output.ProductDetails.UnitName = _repoWrapper.Unit.FirstOrDefault(x => x.Id.ToString() == productDetail.Unit)?.Name;
            }

            output.ProductDetails.RelatedCategoryName     = _repoWrapper.ProductCategory.FirstOrDefault(x => x.ProductCategory_ID == productDetail.RelatedCategoryId)?.Name;
            output.ProductDetails.AccessoriesCategoryName = _repoWrapper.ProductCategory.FirstOrDefault(x => x.ProductCategory_ID == productDetail.AccessoriesCategoryId)?.Name;



            return(output);
        }
Exemplo n.º 14
0
        public List <ProductDetailsDTO> GetRecommendedProductsByCharacteristics(int productId)
        {
            products selectedProduct = db.products.FirstOrDefault(x => x.id == productId);
            List <expert_product_characteristic> productsCharacteristics = db.expert_product_characteristic.ToList();
            Dictionary <int, double>             pCoeficient             = new Dictionary <int, double>();

            int[] productIds = db.Database.SqlQuery <int>(@"  select distinct ur.product_id_id from expert_product_characteristic ur                                                         
                                                          inner join products p on p.id = ur.product_id_id
                                                          where ur.product_id_id <> '" + productId + "' AND p.category_id_id = '" + selectedProduct.category_id_id + "'").ToArray();
            List <expert_product_characteristic> selectedProdChars = productsCharacteristics.Where(x => x.product_id_id == productId).ToList();

            foreach (int prodId in productIds)
            {
                double divisible  = 0;
                double divisorAi  = 0;
                double divisorBi  = 0;
                double coeficient = 0;
                for (int i = 1; i <= 5; i++)
                {
                    expert_product_characteristic ai = selectedProdChars.FirstOrDefault(x => x.c_header_id_id == i && x.product_id_id == productId);
                    expert_product_characteristic bi = productsCharacteristics.FirstOrDefault(x => x.c_header_id_id == i && x.product_id_id == prodId);
                    divisible += ai.characteristic_values * bi.characteristic_values;
                    divisorAi += ai.characteristic_values * ai.characteristic_values;
                    divisorBi += bi.characteristic_values * bi.characteristic_values;
                }
//                SUM(Ai*Bi) / SQRT(SUM(Ai*Ai)) / SQRT (SUM(Bi*Bi))

                coeficient = divisible / Math.Sqrt(divisorAi) / Math.Sqrt(divisorBi);
                if (Double.IsNaN(coeficient))
                {
                    coeficient = 0;
                }
                pCoeficient.Add(prodId, coeficient);
            }

            int[] topProducts = pCoeficient.OrderByDescending(x => x.Value).Take(10).Select(x => x.Key).ToArray();

            List <products> recommendedProducts = db.products.Include("categories").Include("vendors").Include("vendors.regions").Include("vendors.regions.countries").Include("appellation").Where(x => topProducts.Contains(x.id)).ToList();

            List <ProductDetailsDTO> result = new List <ProductDetailsDTO>();

            foreach (products prod in recommendedProducts)
            {
                ProductDetailsDTO newDTO = new ProductDetailsDTO();
                newDTO.ProdID       = prod.id;
                newDTO.ProdName     = prod.name;
                newDTO.VendorName   = prod.vendors.name;
                newDTO.CategoryName = prod.categories.name;
                newDTO.RegionName   = prod.vendors.regions.name;
                newDTO.CountryName  = prod.vendors.regions.countries.name;
                newDTO.PhotoPath    = prod.photo_path;
                newDTO.UserAvgRate  = (int)(pCoeficient[prod.id] * 100);
                result.Add(newDTO);
            }

            return(result);
        }
Exemplo n.º 15
0
        public async Task <ProductDetailsDTO> ProcessPhoneProduct()
        {
            var output = new ProductDetailsDTO();

            var s = await _repoWrapper.Product.ProcessPhoneNumber();


            return(output);
        }
Exemplo n.º 16
0
        public async Task <ActionResult> GetDetails(int productId)
        {
            ProductDetailsDTO model = new ProductDetailsDTO();

            using (var serviceClient = new ProductServiceClient())
            {
                model = await Task.Run(() => serviceClient.GetDetails(productId));
            }

            return(View(model));
        }
Exemplo n.º 17
0
        public ProductDetailsDTO GetProductById(Guid productID)
        {
            ProductDetailsDTO item = new ProductDetailsDTO();

            try
            {
                Product currentProduct = this.iUnitOfWork.ProductRepository.GetByID(productID);
                if (currentProduct != null)
                {
                    item.CurrentProduct = new ProductDTO()
                    {
                        ID                 = currentProduct.ID,
                        description        = currentProduct.description,
                        categoryID         = currentProduct.categoryID,
                        parentCategoryName = currentProduct.Category.name,
                        name               = currentProduct.name,
                        priceAfter         = currentProduct.priceAfter,
                        priceBefore        = currentProduct.priceBefore,
                        discountPercentage = (currentProduct.priceAfter != null && currentProduct.priceBefore != null) ? String.Format("{0:0.00}", (100 - ((currentProduct.priceAfter * 100) / currentProduct.priceBefore))) + " %" : 0 + " %",
                        productOptions     = currentProduct.productOptions,
                        rate               = (int)currentProduct.rate,
                        images             = currentProduct.Images.Select(i => new ImageDTO()
                        {
                            ID        = i.ID,
                            imageUrl  = WebConfigurationManager.AppSettings["WebApiUrl"].ToString() + i.imageUrl,
                            productID = currentProduct.ID
                        }).ToList(),

                        Comments = currentProduct.Comments.Select(c => new CommentDTO()
                        {
                            ID          = c.ID,
                            commentText = c.commentText,
                            ratingValue = c.ratingValue,
                            userID      = c.userID,
                            userName    = c.User.userName,
                            productID   = currentProduct.ID
                        }).ToList()
                    };

                    List <ProductDTO> relatedProducts = new List <ProductDTO>();
                    relatedProducts = this.GetProductsOFCategory(currentProduct.Category.parentCategoryID.ToString());
                    if (relatedProducts.Count > 0)
                    {
                        item.RelatedProducts = relatedProducts;
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLogger.LogDebug(ex.Message);
            }

            return(item);
        }
        private ProductDetailsDTO GetProductDetails()
        {
            var productDetailsDto = new ProductDetailsDTO
            {
                Price       = 5.35,
                Description = "Some short description",
                Name        = "Cappucino"
            };

            return(productDetailsDto);
        }
Exemplo n.º 19
0
        public IActionResult Edit(ProductDetailsDTO dto)
        {
            Product product = db.Products.Where(x => !x.IsDeleted).First(x => x.Id == dto.Id);

            product.Name        = dto.Name;
            product.Price       = dto.Price;
            product.Description = dto.Description;
            product.Type        = Enum.Parse <ProductType>(dto.Type);
            db.SaveChanges();
            return(RedirectToAction("Details", new { id = product.Id }));
        }
Exemplo n.º 20
0
 public IActionResult Create(ProductDetailsDTO dto)
 {
     if (ModelState.IsValid)
     {
         Product product = mapper.Map <Product>(dto);
         db.Products.Add(product);
         db.SaveChanges();
         return(RedirectToAction("Details", new { id = product.Id }));
     }
     return(RedirectToAction("Index", "Home"));
 }
Exemplo n.º 21
0
        public IActionResult Delete(ProductDetailsDTO dto)
        {
            Product product = db.Products.Where(x => !x.IsDeleted).FirstOrDefault(x => x.Id == dto.Id);

            if (product is null)
            {
                return(View("Error", new ErrorViewModel("Unfound Product")));
            }
            product.IsDeleted = true;
            db.SaveChanges();
            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 22
0
        public async Task AddAsync(ProductDetailsDTO product) // Dodaje nowy produkt
        {
            _logger.LogInformation(1, $"Tworze product o guid {product.Id}");

            //Sprawdzam czy ProductDefinition istnieje
            //Jak nie istnieje dodaje
            var productDefinition = await _productDefinitionRepository.CreateIfNullAsync(product.Name,
                                                                                         product.Description, product.Mark, product.Collection, product.IsAvaible);

            //Sprawdzam czy istnieje identyczny produkt
            //Jak tak podaj błąd
            var Product = await _productRepository.GetProductByDefinitionSizeAndColorAsync(productDefinition.Id,
                                                                                           product.SizeId, product.ColorId);

            if (Product != null)
            {
                _logger.LogError(1, $"Product named: '{product.Name}' and colorId : '{product.ColorId}' and sizeId : '{product.SizeId}' already exist");
                throw new Exception($"Product named: '{product.Name}' and colorId : '{product.ColorId}' and sizeId : '{product.SizeId}' already exist");
            }
            //Sprawdzam czy jest choć jedno zdjęcie
            if (product.ProductFotosDTO.Count == 0)
            {
                _logger.LogError(1, $"Product named: '{product.Name}' doesn't have any picture. Stop process of adding product.");
                throw new Exception($"Product named: '{product.Name}' doesn't have any picture");
            }
            //Dodaje product
            var ColorValue = await _colorRepository.GetByIdAsync(product.ColorId);

            var SizeValue = await _sizeRepository.GetByIdAsync(product.SizeId);

            Product = new Product(product.Id, product.IsAvaible, product.Discount, ColorValue.Name, SizeValue.Name, productDefinition.Id, product.SizeId, product.ColorId, product.CategoryId, product.Price);

            Task  AddProduct = _productRepository.AddAsync(Product);
            await AddProduct;

            //Dodaje dotepnosc produktu
            Task.WaitAll(AddProduct);
            var ProductAvailability = new ProductAvailability(Guid.NewGuid(), product.Quantity, product.Id);
            await _productAvailabilityRepository.AddAsync(ProductAvailability);

            //Dodaje zdjęcia
            int Index = 1;

            foreach (var productFoto in product.ProductFotosDTO)
            {
                var newFoto = new ProductFoto(Guid.NewGuid(), product.Id, productDefinition.Id, productFoto.FotoUrl, productFoto.Description, Index);
                Index++;
                await _productFotoRepository.AddAsync(newFoto);
            }
        }
Exemplo n.º 23
0
        public async Task <ProductDetailsDTO> GetProductDetails(int productId)
        {
            ProductDetailsDTO output       = new ProductDetailsDTO();
            string            apiUrl       = $"/api/v1/Product/GetShopmanProductDetails";
            string            paramRequest = $"?productId={productId}";
            var response = await _client.GetAsync(apiUrl + paramRequest);

            if (response.IsSuccessStatusCode)
            {
                string responseStream = await response.Content.ReadAsStringAsync();

                output = JsonConvert.DeserializeObject <ProductDetailsDTO>(responseStream);
            }
            return(output);
        }
        public async Task <ProductDetailsDTO> GetProductDetailsAsync(int productId)
        {
            try
            {
                var productsRepository = this._unitOfWork.GetRepository <IProductsRepository>();

                ProductDetailsDTO product = await productsRepository.GetProductDetailsAsync(productId);

                return(product);
            }
            catch (Exception ex)
            {
                throw new ArgumentException(ExceptionMessages.GetProductDetailsMessage, ex);
            }
        }
Exemplo n.º 25
0
        public async Task <IActionResult> ServiceDetail()
        {
            var url        = RouteData.Values["url"];
            int Service_ID = Utils.RegexRouteIdFromUrl(url.ToString());

            if (Service_ID == 0) // Error Redirect 301
            {
                //Response.StatusCode = 301;
                //Response.Headers("Location", "https://daninhbinhvinhquang.vn/may-de-ban");
                //Response.End();
            }
            ViewBag.MenuMachine = await _repoWrapper.ProductCategory.GetLstMenuByParentId(654);

            ViewBag.MenuMaterials = await _repoWrapper.ProductCategory.GetLstMenuByParentId(652);

            ViewBag.MenuServices = await _repoWrapper.ProductCategory.GetLstMenuByParentId(651);

            ViewBag.ListCategory = await _repoWrapper.Service.GetProdCateByParentID(651);

            ViewBag.MetaTags = await _repoWrapper.Setting.GetSetting();

            //Lấy ra ds dịch vụ được tài trợ và banner

            ProductDetailsDTO model = await _repoWrapper.Service.GetProductDetails(Service_ID);

            if (model.ErrorCode == "00" || model.ErrorCode == "0")
            {
                ViewBag.ListProductAds = await _repoWrapper.Service.GetSponsorBannerProduct((int)model.ProductDetails.ProductCategory_ID, 11, 5);

                ViewBag.ListProductByCate = await _repoWrapper.Service.GetListServiceByCate(1, 10, 4, 11, (int)model.ProductDetails.ProductCategory_ID, null, null);

                ViewBag.ListProductByProductBrand = await _repoWrapper.Service.GetListServiceByProductBrand(1, 10, 4, 11, (int)model.ProductDetails.ProductBrand_ID);

                var productCategoryDetail = await _repoWrapper.ProductCategory.GetDetailProductCategory((int)model.ProductDetails.ProductCategory_ID);

                ViewBag.ProductCateName = productCategoryDetail.Name;
                ViewBag.ProductCateUrl  = productCategoryDetail.URL;
                return(View(model));
            }
            else
            {
                return(Redirect("/Error/404"));
            }
        }
        public async Task <IActionResult> Index(int productId)
        {
            ProductDetailsDTO product = await this._productsService.GetProductDetailsAsync(productId);

            return(this.View(product));
        }
Exemplo n.º 27
0
        public async Task <ProductDetailsDTO> GetProductDetails(int productId)
        {
            //var pr = hanomaContext.Product.FirstOrDefault();
            //var oktest = hanomaContext.Product
            //    .FromSqlRaw($"SELECT TOP 3 B.* " +
            //    $"FROM ProductBlockProduct A " +
            //    $"JOIN Product B ON A.Product_ID = B.Product_ID WHERE A.ProductBlock_ID = 1 ORDER BY B.LastEditDate")
            //    .AsNoTracking()
            //    .ToList();

            var output = new ProductDetailsDTO();

            var productDetail = _repoWrapper.Product.FirstOrDefault(x => x.Product_ID == productId);

            if (productDetail == null)
            {
                output.ErrorCode = "P001";
                output.Message   = "Sản phẩm không tồn tại";
                return(output);
            }
            var productPicture = await _repoWrapper.ProductPicture.GetByProductId(productId);

            string pUser    = productDetail.CreateBy.ToString();
            var    profiles = await _repoWrapper.AspNetUserProfiles.FirstOrDefaultAsync(p => p.UserId == pUser);

            if (profiles != null)
            {
                output.Profiles = profiles;
            }



            output.ProductDetails = _mapper.Map <ProductDTO>(productDetail);
            ///output.ProductPictures = _mapper.Map<IEnumerable<ProductPictureDTO>>(productPicture);
            output.ProductPictures = productPicture;
            if (productDetail.ProductBrand_ID != 0)
            {
                var productBrand = _repoWrapper.Brand.FirstOrDefault(x => x.ProductBrand_ID == productDetail.ProductBrand_ID);
                output.ProductBrand = _mapper.Map <BrandDTO>(productBrand);
                //Get Năm tham gia
                output.ProductBrand.ProductBrandYearJoin = (int)(DateTime.Now.Year - productBrand.CreateDate?.Year) + 1;
                output.ProductBrand.LocationName         = _repoWrapper.Location.FirstOrDefault(p => p.Location_ID == productBrand.Location_ID)?.Name;
            }


            output.ProductDetails.ProductModelName       = _repoWrapper.ProductModel.FirstOrDefault(x => x.ProductModel_ID == productDetail.ProductModel_ID)?.Name;
            output.ProductDetails.ProductManufactureName = _repoWrapper.ProductManufacture.FirstOrDefault(x => x.ProductManufacture_ID == productDetail.ProductManufacture_ID)?.Name;
            output.ProductDetails.SaleLocationName       = _repoWrapper.Location.FirstOrDefault(x => x.Location_ID == productDetail.SaleLocation_ID)?.Name;
            output.ProductDetails.ProductCategoryName    = _repoWrapper.ProductCategory.FirstOrDefault(x => x.ProductCategory_ID == productDetail.ProductCategory_ID)?.Name;
            output.ProductDetails.CountryName            = _repoWrapper.Country.FirstOrDefault(x => x.Country_ID == productDetail.Country_ID)?.Name;
            output.ProductDetails.Content = HttpUtility.HtmlDecode(output.ProductDetails.Content);
            if (productDetail.ProductType_ID == 11 && productDetail.Unit != null)
            {
                try
                {
                    var resultUnit = await _repoWrapper.Unit.GetMinorByMinorId(Int32.Parse(productDetail.Unit));

                    if (resultUnit != null)
                    {
                        output.ProductDetails.UnitName = resultUnit.MinorName;
                    }
                }
                catch
                {
                }
            }
            else
            {
                output.ProductDetails.UnitName = _repoWrapper.Unit.FirstOrDefault(x => x.Id.ToString() == productDetail.Unit)?.Name;
            }

            output.ProductDetails.RelatedCategoryName     = _repoWrapper.ProductCategory.FirstOrDefault(x => x.ProductCategory_ID == productDetail.RelatedCategoryId)?.Name;
            output.ProductDetails.AccessoriesCategoryName = _repoWrapper.ProductCategory.FirstOrDefault(x => x.ProductCategory_ID == productDetail.AccessoriesCategoryId)?.Name;


            //Meta keyword
            output.MetaKeyword = _mapper.Map <IEnumerable <MetaKeywordDTO> >(await _repoWrapper.Product.GetListMetaKeyword(productId));

            return(output);
        }
Exemplo n.º 28
0
        public List <ProductDetailsDTO> GetRecommendedProductsByProductCategory(int productId)
        {
            products selectedProduct = db.products.FirstOrDefault(x => x.id == productId);

            int[] productIds = db.Database.SqlQuery <int>(@"  select distinct ur.product_id_id from user_rates ur
                                                          inner join inventory i on ur.product_id_id = i.product_id_id and i.in_stock > 0
                                                          inner join products p on p.id = ur.product_id_id
                                                          where ur.product_id_id <> '" + productId + "' AND p.category_id_id = '" + selectedProduct.category_id_id + "'").ToArray();

            List <user_rates>        userRates   = db.user_rates.Where(x => productIds.Contains(x.product_id_id)).ToList();
            Dictionary <int, double> uCoeficient = new Dictionary <int, double>();

            List <user_rates> spRates = db.user_rates.Where(x => x.product_id_id == productId).ToList();

            if (spRates.Count == 0)
            {
                return(null);
            }
            double avgSPRating = spRates.Sum(x => x.rate) / spRates.Count;

            if (avgSPRating % 1 == 0)
            {
                avgSPRating += 0.00001;
            }

            foreach (int prodID in productIds)
            {
                double            divisible  = 0;
                double            divisorSP  = 0;
                double            divisorP   = 0;
                double            coeficient = 0;
                List <user_rates> pRates     = userRates.Where(x => x.product_id_id == prodID).ToList();
                double            avgPRating = pRates.Sum(x => x.rate) / pRates.Count;
                if (avgPRating % 1 == 0)
                {
                    avgPRating += 0.00001;
                }
                foreach (int userID in pRates.Select(x => x.user_id_id))
                {
                    user_rates rate   = pRates.FirstOrDefault(x => x.user_id_id == userID);
                    user_rates spRate = spRates.FirstOrDefault(x => x.user_id_id == userID);
                    if (rate == null || spRate == null)
                    {
                        continue;
                    }
                    divisible += (spRate.rate - avgSPRating) * (rate.rate - avgPRating);
                    divisorSP += Math.Pow((double)(spRate.rate - avgSPRating), 2);
                    divisorP  += Math.Pow((double)(rate.rate - avgPRating), 2);
                }
                coeficient = divisible / (Math.Sqrt(divisorSP) * Math.Sqrt(divisorP));
                if (Double.IsNaN(coeficient))
                {
                    coeficient = 0;
                }
                uCoeficient.Add(prodID, coeficient);
            }

            int[] topProducts = uCoeficient.OrderByDescending(x => x.Value).Take(10).Select(x => x.Key).ToArray();

            List <inventory> inventory = db.inventory.ToList();

            inventory = inventory.Where(y => topProducts.Contains(y.product_id_id)).ToList();
            Dictionary <int, double> recrate = new Dictionary <int, double>();

            foreach (inventory inv in inventory)
            {
                int prodId = inv.product_id_id;
                List <user_rates> ratesByProduct = userRates.Where(x => x.product_id_id == prodId).ToList();
                double            totalRateValue = 0;
                foreach (user_rates rate in ratesByProduct)
                {
                    totalRateValue += uCoeficient[rate.product_id_id] * rate.rate;
                }

                recrate.Add(prodId, totalRateValue / ratesByProduct.Count);
            }

            int[]           topProductIds       = recrate.OrderByDescending(x => x.Value).Take(10).Select(x => x.Key).ToArray();
            List <products> recommendedProducts = db.products.Include("categories").Include("vendors").Include("vendors.regions").Include("vendors.regions.countries").Include("appellation").Where(x => topProductIds.Contains(x.id)).ToList();

            List <ProductDetailsDTO> result = new List <ProductDetailsDTO>();

            foreach (products prod in recommendedProducts)
            {
                ProductDetailsDTO newDTO = new ProductDetailsDTO();
                newDTO.ProdID       = prod.id;
                newDTO.ProdName     = prod.name;
                newDTO.VendorName   = prod.vendors.name;
                newDTO.CategoryName = prod.categories.name;
                newDTO.RegionName   = prod.vendors.regions.name;
                newDTO.CountryName  = prod.vendors.regions.countries.name;
                newDTO.PhotoPath    = prod.photo_path;
                newDTO.UserAvgRate  = (int)recrate[prod.id];
                result.Add(newDTO);
            }

            result = result.Where(x => x.UserAvgRate > 0).OrderByDescending(x => x.UserAvgRate).ToList();

            return(result);
        }
Exemplo n.º 29
0
        public ActionResult <Object> AddEditProduct(ProductDetailsDTO product)
        {
            var result = productService.AddEditProduct(product);

            return(Ok(result));
        }
Exemplo n.º 30
0
 // creation of the produt  && edit the produt
 public Object AddEditProduct(ProductDetailsDTO product)
 {
     try
     {
         bool   isSuccess;
         string result = string.Empty;
         int?   productId;
         bool   isNew      = product.ProductId != 0 ? false : true;
         var    addProduct = isNew ? new Product {
         } : context.Product.Find(product.ProductId);
         addProduct.Name            = product.Name == null ? null : product.Name;
         addProduct.Description     = product.Description == null ? null : product.Description;
         addProduct.UPC             = product.UPC == null ? null : product.UPC;
         addProduct.BoxId           = product.BoxId == null ? null : product.BoxId;
         addProduct.StatusId        = product.StatusId;
         addProduct.Length          = product.Length;
         addProduct.Width           = product.Width;
         addProduct.Height          = product.Height;
         addProduct.Weight          = product.Weight;
         addProduct.DimensionUnitId = product.DimensionUnitId;
         addProduct.WeightUnitId    = product.WeightUnitId;
         addProduct.ShipsAlone_FLG  = product.ShipsAlone_FLG;
         addProduct.ManufacturerId  = product.ManufacturerId;
         addProduct.ConditionId     = product.ConditionId;
         addProduct.CategoryId      = product.CategoryId;
         addProduct.ColorId         = product.ColorId;
         addProduct.Ref1            = product.Ref1;
         addProduct.Ref2            = product.Ref2;
         if (isNew)
         {
             //sku
             var addProductSku = new List <ProductSKU>();
             foreach (var item in product.ProductSku)
             {
                 ProductSKU addsku = new ProductSKU();
                 addsku.ProductId   = item.ProductId;
                 addsku.SKU         = item.SKU == null ? null : item.SKU;
                 addsku.StatusId    = item.StatusId;
                 addsku.Description = item.Description == null ? null : item.Description;
                 addsku.SKUTypeId   = item.SKUTypeId;
                 addProductSku.Add(addsku);
             }
             addProduct.ProductSKUs = addProductSku;
             //inventory
             var addProductInven = new List <ProductInventory>();
             foreach (var item in product.ProductInventory)
             {
                 ProductInventory addInventory = new ProductInventory();
                 addInventory.ProductVersionId = item.ProductVersionId;
                 addInventory.WarehouseId      = item.WarehouseId;
                 addInventory.Quantity         = item.Quantity;
                 addInventory.StatusId         = item.StatusId;
                 addProductInven.Add(addInventory);
             }
             //versions
             var addProductVersion = new List <ProductVersion>();
             foreach (var item in product.ProductVersion)
             {
                 ProductVersion addversion       = new ProductVersion();
                 var            matchedInventory = new List <ProductInventory>();
                 matchedInventory = addProductInven.FindAll(x => x.ProductVersionId == item.ProductVersionId);
                 addversion.ProductInventories = matchedInventory;
                 addversion.ProductId          = item.ProductId;
                 addversion.Description        = item.Description;
                 addversion.StatusId           = item.StatusId;
                 addProductVersion.Add(addversion);
             }
             addProduct.ProductVersions = addProductVersion;
             //tags
             var addProductTag = new List <ProductTag>();
             if (product.ProductTag != null)
             {
                 foreach (var item in product.ProductTag)
                 {
                     ProductTag addTag = new ProductTag();
                     addTag.ProductId = item.ProductId;
                     addTag.TagId     = item.TagId;
                     addProductTag.Add(addTag);
                 }
                 addProduct.ProductTags = addProductTag;
             }
             context.Product.Add(addProduct);
             context.SaveChanges();
             result    = _iconfiguration["PRODUCT_ADDED_SUCCESSFUL"];
             productId = addProduct.ProductId;
             isSuccess = true;
         }
         else
         {
             List <ProductSKU>     existingProductSku     = context.ProductSKU.Where(x => x.ProductId == product.ProductId).ToList();
             List <ProductVersion> existingProductVersion = context.ProductVersion.Where(x => x.ProductId == product.ProductId).ToList();
             List <ProductTag>     existingProductTag     = context.ProductTag.Where(x => x.ProductId == product.ProductId).ToList();
             var existingInventory = new List <ProductInventory>();
             foreach (var item in existingProductVersion)
             {
                 var existingmatchedInventory = new List <ProductInventory>();
                 existingmatchedInventory = context.ProductInventory.Where(x => x.ProductVersionId == item.ProductVersionId).ToList();
                 if (existingmatchedInventory.Count > 0)
                 {
                     existingInventory.AddRange(existingmatchedInventory);
                 }
             }
             //sku
             var newProductSku = new List <ProductSKU>();
             foreach (var item in product.ProductSku)
             {
                 ProductSKU addsku = new ProductSKU();
                 addsku.ProductId   = item.ProductId;
                 addsku.SKU         = item.SKU == null ? null : item.SKU;
                 addsku.StatusId    = item.StatusId;
                 addsku.Description = item.Description == null ? null : item.Description;
                 addsku.SKUTypeId   = item.SKUTypeId;
                 newProductSku.Add(addsku);
             }
             //inventory
             var newProductInven = new List <ProductInventory>();
             foreach (var item in product.ProductInventory)
             {
                 ProductInventory addInventory = new ProductInventory();
                 addInventory.ProductVersionId = item.ProductVersionId;
                 addInventory.WarehouseId      = item.WarehouseId;
                 addInventory.Quantity         = item.Quantity;
                 addInventory.StatusId         = item.StatusId;
                 newProductInven.Add(addInventory);
             }
             //versions
             var newProductVersion = new List <ProductVersion>();
             foreach (var item in product.ProductVersion)
             {
                 ProductVersion addversion       = new ProductVersion();
                 var            matchedInventory = new List <ProductInventory>();
                 matchedInventory = newProductInven.FindAll(x => x.ProductVersionId == item.ProductVersionId);
                 addversion.ProductInventories = matchedInventory;
                 addversion.ProductId          = item.ProductId;
                 addversion.Description        = item.Description;
                 addversion.StatusId           = item.StatusId;
                 newProductVersion.Add(addversion);
             }
             //tags
             var newProductTag = new List <ProductTag>();
             if (product.ProductTag != null)
             {
                 foreach (var item in product.ProductTag)
                 {
                     ProductTag addTag = new ProductTag();
                     addTag.ProductId = item.ProductId;
                     addTag.TagId     = item.TagId;
                     newProductTag.Add(addTag);
                 }
             }
             addProduct.ProductSKUs     = new List <ProductSKU>();
             addProduct.ProductVersions = new List <ProductVersion>();
             addProduct.ProductTags     = new List <ProductTag>();
             if (existingProductSku.Count > 0)
             {
                 context.ProductSKU.RemoveRange(existingProductSku);
             }
             if (existingInventory.Count > 0)
             {
                 context.ProductInventory.RemoveRange(existingInventory);
             }
             if (existingProductVersion.Count > 0)
             {
                 context.ProductVersion.RemoveRange(existingProductVersion);
             }
             if (existingProductTag.Count > 0)
             {
                 context.ProductTag.RemoveRange(existingProductTag);
             }
             context.ProductSKU.AddRange(newProductSku);
             context.ProductVersion.AddRange(newProductVersion);
             if (newProductTag.Count > 0)
             {
                 context.ProductTag.AddRange(newProductTag);
             }
             context.Product.Update(addProduct);
             context.SaveChanges();
             context.Dispose();
             result    = _iconfiguration["PRODUCT_EDITED_SUCCESSFUL"];
             productId = addProduct.ProductId;
             isSuccess = true;
         }
         return(new { status = isSuccess, productID = productId, message = result });
     }
     catch (Exception ex)
     {
         if (ex.InnerException != null)
         {
             return(new { status = false, productID = product.ProductId, message = ex.InnerException.Message });
         }
         else
         {
             return(new { status = false, productID = product.ProductId, message = ex.Message });
         }
         throw ex;
     }
 }