public IActionResult CreateProduct([FromBody] ProductForCreationDto product)
        {
            try
            {
                if (product == null)
                {
                    _logger.LogError("product object sent from client is null.");
                    return(BadRequest("product object is null"));
                }
                if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid product object sent from client.");
                    return(BadRequest("Invalid model object"));
                }

                var productEntity = _mapper.Map <Product>(product);

                _repository.Product.CreateProduct(productEntity);
                _repository.Save();

                var createdProduct = _mapper.Map <ProductDto>(productEntity);

                return(CreatedAtRoute("ProductTypeById", new { id = createdProduct.ProductId }, createdProduct));
            }
            catch (Exception ex)
            {
                _logger.LogError($"Something went wrong inside CreateProduct action: {ex.InnerException.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
        public async Task <IActionResult> Post([FromBody] ProductForCreationDto product)
        {
            if (product == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var newProduct = _mapper.Map <ProductForCreationDto, Product>(product);

            _productRepository.Add(newProduct);

            if (!await _productRepository.SaveAsync())
            {
                return(StatusCode(500, "Something goes wrong... in Save method :("));
            }

            var productToReturn = _mapper.Map <ProductDto>(newProduct);

            return(CreatedAtRoute(nameof(ProductController.Get), new { id = productToReturn.Id }, productToReturn));
        }
Beispiel #3
0
        public async Task <IActionResult> CreateProduct([FromBody] ProductForCreationDto productForCreation)
        {
            if (productForCreation == null)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var product = Mapper.Map <Entities.Product>(productForCreation);

            product.Id = Guid.NewGuid();

            repository.AddProduct(product);
            if (!await repository.Save())
            {
                logger.LogCritical($"Error when saving new Product. Product.Name: {product.Name}");
                return(StatusCode(500, $"Error when saving new Product. Product.Name: {product.Name}"));
            }

            return(NoContent());
        }
Beispiel #4
0
        public IActionResult CreateProduct(int productId, [FromBody] ProductForCreationDto saleItem)
        {
            //productID is actually the product model id, and saleItem is the product
            if (saleItem == null)
            {
                return(BadRequest());
            }

            //productID is actually the product model id, and salesitem is the product id
            if (!_productInfoRepository.ProductModelExists(productId))
            {
                return(NotFound());
            }

            var finalProduct = Mapper.Map <Entities.Product>(saleItem);

            _productInfoRepository.AddProductForModel(productId, finalProduct);
            if (!_productInfoRepository.Save())
            {
                return(StatusCode(500, "A problem occured while handling your request."));
            }
            var productToReturn = Mapper.Map <Models.ProductDto>(finalProduct);

            return(CreatedAtRoute("GetProduct", new { productId = productId, saleItemId = productToReturn.Id }, productToReturn));
        }
        public IActionResult CreateProduct([FromBody] ProductForCreationDto product)
        {
            try
            {
                if (product == null)
                {
                    _logger.LogError("Product object sent from client is null.");
                    return(BadRequest("Product object is null"));
                }

                if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid product object sent from client.");
                    return(BadRequest("Invalid model object"));
                }

                var productEntity = _mapper.Map <Product>(product);

                _repository.Product.CreateProduct(productEntity);
                _repository.Save();

                var createdProduct = _mapper.Map <ProductDto>(productEntity);
                _logger.LogInfo($"Created new product with id {createdProduct.Id}");

                return(Ok(createdProduct));
            }
            catch (Exception ex)
            {
                _logger.LogError($"createproduct post api products -> {ex}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Beispiel #6
0
        public async Task <ActionResult <int> > AddProduct([FromBody] ProductForCreationDto entity)
        {
            var user = await _userRepo.GetUserByUserClaims(HttpContext.User);

            if (user == null)
            {
                return(Unauthorized("User is Unauthorized"));
            }

            var product = new Product()
            {
                Name             = entity.Name.ToLower(),
                Price            = entity.Price,
                LongDescription  = entity.LongDescription,
                ShortDescription = entity.ShortDescription,
                DateAdded        = entity.DateAdded,
                CategoryId       = entity.CategoryId,
                UserId           = user.Id
            };

            if (await _productRepo.Add(product) == true)
            {
                return(Ok(product.Id));
            }

            throw new Exception("Error happen when Add product");
        }
        public Product AddProduct(ProductForCreationDto product)
        {
            // copy to save photo
            string newName = GetImageName();
            string desFile = GetFullPath(newName);

            try
            {
                File.Copy(product.Photo, desFile, true);
            }
            catch
            {
                System.Windows.MessageBox.Show("Đã xảy ra lỗi khi lưu file!");
                return(null);
            }

            // save products
            var newProduct = Mapper.Map <Product>(product);

            product.Photo = newName;
            if (newProduct.ReturnRate != null)
            {
                newProduct.PriceOut = Helper.CalculatePriceout(newProduct.PriceIn, (float)newProduct.ReturnRate);
            }
            else
            {
                var category = _categoryRepository.Get(product.CategoryId);
                newProduct.PriceOut = Helper.CalculatePriceout(newProduct.PriceIn, (float)category.ReturnRate);
            }

            return(_productRepository.Create(newProduct));
        }
Beispiel #8
0
        public async Task <IActionResult> CreateProduct(ProductForCreationDto productForCreationDto)
        {
            if (productForCreationDto == null)
            {
                return(BadRequest("Sended null product"));
            }

            if (productForCreationDto.CategoryId < 1)
            {
                return(BadRequest("Category wasn't passed or passed bad CategoryId"));
            }

            var selectedCategory = await _unitOfWork.Category.GetAsync(productForCreationDto.CategoryId);

            var requirementsForProduct = _mapper.Map <Requirements>(productForCreationDto.Requirements);

            var productToCreate = await _unitOfWork.Product.ScaffoldProductForCreationAsync(productForCreationDto, requirementsForProduct, selectedCategory);

            if (productToCreate == null)
            {
                return(BadRequest("Something went wrong during creating Product"));
            }

            _unitOfWork.Product.Add(productToCreate);

            if (await _unitOfWork.SaveAsync())
            {
                return(CreatedAtRoute("GetProduct", new { id = productToCreate.Id }, productToCreate));
            }

            return(BadRequest("Error occured during Saving Product"));
        }
Beispiel #9
0
        public IActionResult CreateProduct(ProductForCreationDto product)
        {
            if (null == product)
            {
                return(BadRequest());
            }

            if (product.Name == product.Description)
            {
                ModelState.AddModelError(nameof(ProductForCreationDto), "El nombre y la descripción no pueden ser iguales");
            }

            if (!ModelState.IsValid)
            {
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var productEntity = Mapper.Map <Product>(product);

            _unitOfWork.Products.AddProduct(productEntity);

            if (!_unitOfWork.Complete())
            {
                throw new Exception($"Error guardando el producto {productEntity.Id}");
            }

            var productToReturn = Mapper.Map <ProductDto>(productEntity);

            return(CreatedAtAction("GetProduct", new { id = productToReturn.Id }, productToReturn));
        }
Beispiel #10
0
        public IActionResult CreateProduct(int categoryId, [FromBody] ProductForCreationDto payload)
        {
            //could be added in a validator or service ?
            if (payload.Label == payload.Description)
            {
                ModelState.AddModelError(
                    "Description",
                    "Label product must be different from description.");
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var finalProduct = _mapper.Map <Product>(payload);

            finalProduct = _productservice.CreateProductForCategory(categoryId, finalProduct);

            if (finalProduct is null)
            {
                return(NotFound());
            }

            var createdProductToReturn = _mapper
                                         .Map <ProductDto>(finalProduct);

            return(CreatedAtRoute(
                       "GetProduct",
                       new { categoryId, productId = createdProductToReturn.Id },
                       createdProductToReturn));
        }
Beispiel #11
0
        public ActionResult <Product> CreateProduct(ProductForCreationDto product)
        {
            var productEntity = _mapper.Map <Entities.Product>(product);

            _productRepository.AddProduct(productEntity);
            _productRepository.Save();
            return(CreatedAtRoute("GetProduct", new { productId = productEntity.Id }, productEntity));
        }
Beispiel #12
0
        public async Task CreateAsync(ProductForCreationDto element)
        {
            var supplier = _context.Suppliers.Where(v => v.SupplierCode.Equals(element.SupplierCode)).FirstOrDefault();
            var product  = new Product(element.Name, element.Description, supplier);

            _context.Products.Add(product);
            await _context.SaveChangesAsync();
        }
        public async Task <IActionResult> AddProduct(ProductForCreationDto productForCreationDto)
        {
            var productToCreate = _mapper.Map <Product>(productForCreationDto);

            _repo.Add <Product>(productToCreate);
            await _repo.SaveAll();

            return(CreatedAtAction("GetProducts", new { id = productToCreate.IDProduct }, productToCreate));
        }
Beispiel #14
0
        public async Task <ActionResult> CreateProduct(ProductForCreationDto productCreateRequestDto)
        {
            var product = _mapper.Map <ProductForCreationDto, Product>(productCreateRequestDto);

            await _productService.AddAsync(product);

            var response = _mapper.Map <Product, ProductToReturnDto>(product);

            return(CreatedAtRoute("GetProductById", new { id = product.Id }, response));
        }
Beispiel #15
0
        public ProductDto CreateProduct(ProductForCreationDto productDto)
        {
            var product = _mapper.Map <Entities.Data.Product>(productDto);

            product.Created     = DateTime.Now;
            product.LastUpdated = DateTime.Now;
            _productRepository.CreateProduct(product);

            return(_mapper.Map <ProductDto>(product));
        }
Beispiel #16
0
        public async void CreateProduct_Incorrect_NewProductValue_Returns_BadRequest()
        {
            // Arrange
            ProductForCreationDto productDto = null;

            // Act
            var result = await sut.CreateProduct(productDto);

            // Assert
            Assert.IsType <BadRequestResult>(result);
        }
Beispiel #17
0
 public async Task <ProductDto> CreateProduct(ProductForCreationDto product)
 {
     try
     {
         return(await httpClient.PostJsonAsync <ProductDto>("api/products", product));
     }
     catch
     {
         return(null);
     }
 }
        public async Task <IActionResult> CreateProduct([FromBody] ProductForCreationDto productForCreationDto)
        {
            var productModel = _mapper.Map <Product>(productForCreationDto);

            _productRepository.AddProduct(productModel);
            await _productRepository.SaveAsync();

            var productToReturn = _mapper.Map <ProductDto>(productModel);

            return(CreatedAtRoute("GetProductById", new { productId = productToReturn.Id }, productToReturn));
        }
        public async Task <IActionResult> CreateProduct([FromBody] ProductForCreationDto product)
        {
            var productEntity = _mapper.Map <Product>(product);

            _repository.Product.CreateProduct(productEntity);
            await _repository.SaveAsync();

            var createdProduct = _mapper.Map <ProductDto>(productEntity);

            return(CreatedAtRoute("ProductById", new { id = createdProduct.Id }, createdProduct));
        }
Beispiel #20
0
        public void IntegrationTest_Given_ProductForCreationDtoWithoutLanguageSubCategoryRequirements_When_CreateProduct_Then_Return_RouteToCreatedProduct_WithCreatedStatus()
        {
            //Arrange
            int numberOfProductsBeforeAct = 7;

            var httpContext = new DefaultHttpContext();

            var expected = new ProductForCreationDto()
            {
                Name           = "TEST GAME",
                Description    = "Nulla amet commodo minim esse adipisicing commodo sint esse laboris adipisicing. Officia Lorem laboris ipsum labore mollit ipsum est enim elit exercitation quis deserunt. Nostrud dolore ut sint est ut officia voluptate consequat mollit. Nulla cupidatat mollit dolore non consequat amet Lorem. Magna dolor veniam anim aliquip aliquip esse consequat velit veniam tempor in.\r\n",
                Pegi           = 18,
                Price          = 50.82M,
                IsDigitalMedia = false,
                CategoryId     = 1,
                ReleaseDate    = DateTime.Parse("2020-03-31"),
            };

            var controllerContext = new ControllerContext()
            {
                HttpContext = httpContext
            };

            var sut = new AdminController(_mockedUserManager.Object, _mapper, _cloudinaryConfig, _unitOfWork)
            {
                ControllerContext = controllerContext
            };

            //Act
            var result = sut.CreateProduct(expected).Result;


            //Assert
            result.Should().BeOfType(typeof(CreatedAtRouteResult));

            result.As <CreatedAtRouteResult>().Value.Should().BeOfType(typeof(Product));

            result.As <CreatedAtRouteResult>().Value.As <Product>()
            .Should()
            .BeEquivalentTo(expected, options => options.ExcludingMissingMembers());

            result.As <CreatedAtRouteResult>().Value.As <Product>()
            .Category.Should().NotBeNull();

            result.As <CreatedAtRouteResult>().Value.As <Product>()
            .Languages.Should().BeEmpty();

            result.As <CreatedAtRouteResult>().Value.As <Product>()
            .SubCategories.Should().BeEmpty();

            result.As <CreatedAtRouteResult>().RouteValues.Values.FirstOrDefault().Should().Be(numberOfProductsBeforeAct + 1);
            result.As <CreatedAtRouteResult>().RouteName.Should().Be("GetProduct");
        }
Beispiel #21
0
        public async Task <ApiResult <string> > PostProductAsync(ProductForCreationDto forCreationDto)
        {
            var httpClient = _httpClientFactory.CreateClient("APIClient");
            var response   = await httpClient.GetAsync($"api/products");

            if (response.IsSuccessStatusCode)
            {
                return(JsonConvert.DeserializeObject <ApiResult <string> >(await response.Content.ReadAsStringAsync()
                                                                           ));
            }
            return(new ApiResult <string>(response.StatusCode, await response.Content.ReadAsStringAsync()));
        }
Beispiel #22
0
        public IActionResult Post([FromBody] ProductForCreationDto productForCreation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //var product = _mapper.Map<Entities.Data.Product>(productForCreation);

            var result = _productService.CreateProduct(productForCreation);

            return(CreatedAtRoute("GetProductById", new { id = result.Id }, result));
        }
Beispiel #23
0
        public async Task <IActionResult> Create(ProductForCreationDto ProductDto)
        {
            var user = Mapper.Map <Product>(ProductDto);

            UnitOfWork.Products.Add(user);

            if (await UnitOfWork.Complete())
            {
                return(CreatedAtRoute("ProductLink", new { ProductId = user.Id }, ProductDto));
            }

            throw new Exception($"Something went wrong trying to create an product");
        }
Beispiel #24
0
        public async Task <Product> ScaffoldProductForCreationAsync(ProductForCreationDto productForCreationDto, Requirements requirements, Category selectedCategory)
        {
            if (productForCreationDto == null)
            {
                throw new ArgumentException("Product that was passed to CreateAsync method is null");
            }

            var product = new Product
            {
                Name           = productForCreationDto.Name,
                Description    = productForCreationDto.Description,
                Pegi           = productForCreationDto.Pegi,
                Price          = productForCreationDto.Price,
                IsDigitalMedia = productForCreationDto.IsDigitalMedia,
                ReleaseDate    = productForCreationDto.ReleaseDate,
                Category       = selectedCategory,
                Requirements   = requirements,
                Languages      = new List <ProductLanguage>(),
                SubCategories  = new List <ProductSubCategory>(),
                Stock          = new Stock()
            };

            if (productForCreationDto.LanguagesId != null)
            {
                foreach (var languageId in productForCreationDto.LanguagesId)
                {
                    var selectedLanguages = await _ctx.Languages.FirstOrDefaultAsync(l => l.Id == languageId);

                    var pl = new ProductLanguage {
                        Product = product, Language = selectedLanguages
                    };
                    product.Languages.Add(pl);
                }
            }

            if (productForCreationDto.SubCategoriesId != null)
            {
                foreach (var subCategoryId in productForCreationDto.SubCategoriesId)
                {
                    var selectedSubCategory = await _ctx.SubCategories.FirstOrDefaultAsync(sc => sc.Id == subCategoryId);

                    var psc = new ProductSubCategory {
                        Product = product, SubCategory = selectedSubCategory
                    };
                    product.SubCategories.Add(psc);
                }
            }

            return(product);
        }
        public async Task <ActionResult <ProductDto> > CreateProduct([FromBody] ProductForCreationDto productForCreationDto)
        {
            if (productForCreationDto is null)
            {
                return(BadRequest());
            }
            var product = _mapper.Map <Product>(productForCreationDto);
            await _productService.AddProductAsync(product);

            _productService.Commit();
            var productDto = _mapper.Map <ProductDto>(product);

            return(CreatedAtRoute("GetProduct", new { id = product.Id }, productDto));
        }
        public void IntegrationTest_Given_ProductForCreationDtoWithoutCategoryLanguageSubCategoryRequirements_When_ScaffoldProductForCreationAsync_ThenReturn_Product()
        {
            //Arrange
            var productForCreationDto = new ProductForCreationDto()
            {
                Name           = "Test Name",
                Description    = "Test Description",
                Pegi           = 12,
                Price          = 55.02M,
                IsDigitalMedia = true,
                ReleaseDate    = DateTime.Parse("2020-07-20"),
            };

            var requirements = _mapper.Map <Requirements>(productForCreationDto.Requirements);

            var selectedCategory = _context.Categories.Where(c => c.Id == productForCreationDto.CategoryId).FirstOrDefault();

            var expected = new Product()
            {
                Name           = productForCreationDto.Name,
                Description    = productForCreationDto.Description,
                Pegi           = productForCreationDto.Pegi,
                Price          = productForCreationDto.Price,
                IsDigitalMedia = productForCreationDto.IsDigitalMedia,
                ReleaseDate    = productForCreationDto.ReleaseDate,
                Languages      = new List <ProductLanguage>(),
                SubCategories  = new List <ProductSubCategory>(),
                Stock          = new Stock()
            };


            var sut = new ProductRepository(_context);


            //Act
            var result = sut.ScaffoldProductForCreationAsync(productForCreationDto, requirements, selectedCategory).Result;

            //Assert
            result.Should().NotBeNull();
            result.Should().BeOfType <Product>();

            result.As <Product>().Category.Should().BeNull();

            result.As <Product>().SubCategories.Should().BeEmpty();

            result.As <Product>().Languages.Should().BeEmpty();

            result.Should().BeEquivalentTo(expected, option => option.IgnoringCyclicReferences());
        }
        public async Task <IActionResult> AddProduct([FromBody] ProductForCreationDto productForCreationDto)
        {
            var productExists = await _context.Products
                                .FirstOrDefaultAsync(x => x.Brand.Name.ToLower().Replace(" ", String.Empty) == productForCreationDto.Brand.ToLower().Replace(" ", String.Empty) &&
                                                     x.Name.ToLower().Replace(" ", String.Empty) == productForCreationDto.Name.ToLower().Replace(" ", String.Empty));

            if (productExists == null)
            {
                Product product     = productForCreationDto.Adapt <Product>();
                Brand   brandExists = _context.Brands.FirstOrDefault(x => x.Name == productForCreationDto.Brand);
                Brand   brand;

                if (brandExists == null)
                {
                    brand = new Brand()
                    {
                        Name = productForCreationDto.Brand
                    }
                }
                ;
                else
                {
                    brand = brandExists;
                }

                product.Brand = brand;

                product.AdminApproved = false;

                _context.Add(product);
                // May have to save here.
                _context.SaveChanges();

                // var locationProduct = new LocationProduct() {
                //     LocationId = productForCreationDto.LocationId,
                //     ProductId = product.Id
                // };

                // _context.Add(locationProduct);
                // _context.SaveChanges();

                return(Ok(product));
            }
            else
            {
                return(BadRequest("Product already exists"));
            }
        }
        public async Task <IActionResult> CreateProduct(ProductForCreationDto productForCreationDto)
        {
            var product = _mapper.Map <Product>(productForCreationDto);

            if (_productService.ProductExist(productForCreationDto.Title))
            {
                return(Conflict("Product title already exist"));
            }

            _productService.Add(product);
            if (await _productService.SaveAll())
            {
                var productToReturn = _mapper.Map <ProductForDetailsDto>(product);
                return(CreatedAtRoute("GetProduct", new { controller = "Products", productId = product.ProductId }, productToReturn));
            }
            return(BadRequest($"Error while saving {productForCreationDto.Title}"));
        }
        public ActionResult <ProductDto> CreateProduct(ProductForCreationDto product)
        {
            if (product == null)
            {
                return(BadRequest());
            }

            var productEntity = _mapper.Map <Entities.Products>(product);

            _productRepository.AddProduct(productEntity);
            _productRepository.Save();

            var productToReturn = _mapper.Map <ProductDto>(productEntity);

            return(CreatedAtRoute("GetProduct",
                                  new { productId = productToReturn.productId },
                                  productToReturn));
        }
        public async Task <IActionResult> CreateNewProduct(string userId, [FromBody] ProductForCreationDto productForCreationDto)
        {
            if (userId != User.FindFirst(ClaimTypes.NameIdentifier).Value)
            {
                return(Unauthorized());
            }

            var product = _mapper.Map <Product>(productForCreationDto);

            _unitOfWork.Products.Add(product);

            if (await _unitOfWork.Products.SaveAll())
            {
                return(CreatedAtAction(nameof(GetProductById), new { id = product.Id }, product));
            }

            throw new Exception("Creating product failed on save.");
        }