public IActionResult Create([FromForm] ProductInputModel inputModel) { if (!ModelState.IsValid) { return(View(inputModel)); } var product = inputModel.ToEntity(); product = _store.Create(product); var outputModel = ProductOutputModel.FromEntity(product); return(RedirectToAction(nameof(Index))); }
public ActionResult <long> AddProduct([FromBody] ProductInputModel productInputModel) { var validationResult = _productValidator.ValidateProductInputModelUponCreation(productInputModel); if (!string.IsNullOrEmpty(validationResult)) { return(UnprocessableEntity(validationResult)); } var result = _productManager.AddProduct(productInputModel); if (!result.ContainsData) { return(Problem(detail: result.ResponseMessage, statusCode: 520)); } return(Created($"id/{result.Data}", result.Data)); }
public virtual ActionResult Edit(int productId, ProductInputModel productInputs) { var userId = 1; var command = new EditProductCommand { ProductId = productInputs.ProductId, UserId = CurrentUserId(), ProductName = productInputs.ProductName, ProductNotes = productInputs.ProductNotes }; var result = mediator.Send(command); return(RedirectToAction("View", new { productId = productInputs.ProductId })); }
private Product Map(ProductInputModel productInput) { Product product = new Product(); product.IdProduct = productInput.IdProduct; product.Type = productInput.Type; product.SalePrice = productInput.SalePrice; product.PurchasePrice = productInput.PurchasePrice; product.Quantity = productInput.Quantity; product.Iva = productInput.Iva; product.Image = productInput.Image; product.Description = productInput.Description; product.Category = productInput.Category; return(product); }
public ActionResult SearchProduct(ProductInputModel input) { var products = this.products.GetAllProducts() .To <ProductViewModel>() .ToList(); if (!String.IsNullOrEmpty(input.Title)) { products = products.Where(p => p.Title.Contains(input.Title)).ToList(); } var viewModel = new IndexViewModel() { Products = products }; return(View(viewModel)); }
public async Task ProductIntpuModelIsValidAndProductExistAtDb_ProductUpdated_ReturnsProductUpdatedAsSuccessMessage() { //arrange var productDb = new Product("Skol lata", 2.39M) { Id = Guid.NewGuid() }; var company = new Company("Vendinha da esquina"); var product = new Product("Skol latão", 2.50M) { Id = Guid.NewGuid() }; var productInputModel = new ProductInputModel("Skol lata", 2.39M, Guid.NewGuid()) { CompanyId = Guid.NewGuid() }; var productOutput = new ProductOutputModel(Guid.NewGuid(), "Skol lata", 2.39M) { Type = "Cerveja" }; mockMapper.Setup(x => x.Map(It.IsAny <ProductInputModel>(), It.IsAny <Product>())).Returns(product); mockMapper.Setup(x => x.Map <ProductOutputModel>(It.IsAny <Product>())).Returns(productOutput); mockProductRepository.Setup(x => x.Get(It.IsAny <Expression <Func <Product, bool> > >(), It.IsAny <CancellationToken>())).ReturnsAsync(productDb); mockProductRepository.Setup(x => x.Update(It.IsAny <Product>(), It.IsAny <CancellationToken>())) .ReturnsAsync(product); mockUserService.Setup(x => x.Get(It.IsAny <Expression <Func <Company, bool> > >(), It.IsAny <CancellationToken>())).ReturnsAsync(company); var productService = GenerateProductServiceIntance(); //Act var result = await productService.UpdateProduct(Guid.NewGuid(), productInputModel, new CancellationToken()); //assert Assert.NotNull(result); Assert.Equal(result.Name, productOutput.Name); Assert.Equal(result.Price, productOutput.Price); Assert.Equal(result.Type, productOutput.Type); }
public void UpdateProduct(ProductInputModel productInputModel) { using (var productRepository = _container.Resolve <IProductRepository>()) using (var searchWordRepository = _container.Resolve <ISearchWordRepository>()) { var product = productRepository.Read(productInputModel.ProductId); product.ProductName = productInputModel.ProductName; product.ServiceStartDate = productInputModel.ServiceStartDate; product.ServiceEndDate = productInputModel.ServiceEndDate; productRepository.Update(product); if (product.SearchWords == null || product.SearchWords.Count() == 0) { foreach (var searchWord in productInputModel.SearchWords) { searchWordRepository.Create(product, searchWord); } } else if (productInputModel.SearchWords == null || productInputModel.SearchWords.Count() == 0) { foreach (var searchWord in product.SearchWords) { searchWordRepository.Delete(searchWord.SearchWordId); } } else { foreach (var existingSearchWord in product.SearchWords) { if (!productInputModel.SearchWords.Any(s => s == existingSearchWord.Word)) { searchWordRepository.Delete(existingSearchWord.SearchWordId); } } foreach (var inputSearchWord in productInputModel.SearchWords) { if (!product.SearchWords.Any(s => s.Word == inputSearchWord)) { searchWordRepository.Create(product, inputSearchWord); } } } } }
public async Task <IHttpActionResult> Put(int id, ProductInputModel model) { Product Product = await _ProductRepository.GetProduct(id); if (Product == null) { NotFound(); } Product.Name = model.Name; var result = await _ProductRepository.SaveProductAsync(Product); if (!result) { return(InternalServerError()); } return(Ok()); }
private Product MapearProducto(ProductInputModel productoInputModel) { var product = new Product { Name = productoInputModel.Name, Unit_Price = productoInputModel.Unit_Price, Category = _CategoryService.Find(int.Parse(productoInputModel.CategoryId)).Object, QuantityStock = productoInputModel.QuantityStock, Image = productoInputModel.Image, State = productoInputModel.State, Description = productoInputModel.Description, Presentations = _PresentationService.SelectPresentations(productoInputModel.PresentationsIds).List }; return(product); }
public ActionResult AddProduct(ProductInputModel input) { var userId = this.User.Identity.GetUserId(); var product = new Product { Title = input.Title, Content = input.Content, Category = input.Category, Price = input.Price, SellerId = userId }; this.products.Add(product); this.products.SaveChanges(); return(this.RedirectToAction("Index", new { id = product.Id, url = "new" })); }
/// <summary> /// Delete a product /// </summary> /// <param name="productInputModel">Product input model</param> /// <returns>delete status</returns> public Task <bool> DeleteProduct(ProductInputModel productInputModel) { var product = _productRepository.FindByFilter(c => c.Id.Equals(productInputModel.Id)).FirstOrDefault(); if (product == null) { throw new GalvException("Woops! this product does not exist", StatusCodes.Status400BadRequest); } if (product.Deleted) { throw new GalvException("You are smart! Trying to delete this product again?", StatusCodes.Status400BadRequest); } product.Deleted = true; _productRepository.Update(product); _productRepository.SaveChanges(); return(Task.FromResult(true)); }
public async Task <ActionResult <Product> > Post( [FromServices] DataContext context, [FromBody] ProductInputModel model) { if (ModelState.IsValid) { Product product = new Product(model.Title, model.Description, model.Price, model.CategoryId); context.Products.Add(product); await context.SaveChangesAsync(); return(Ok(model)); } else { return(BadRequest(ModelState)); } }
public ActionResult Update(int productId) { using (var productRepository = new ProductRepository()) { var product = productRepository.ReadAll() .Include(p => p.SearchWords) .FirstOrDefault(p => p.ProductId == productId); var model = new ProductInputModel(); model.ProductId = product.ProductId; model.ProductName = product.ProductName; model.ServiceStartDate = product.ServiceStartDate; model.ServiceEndDate = product.ServiceEndDate; model.SearchWords = product.SearchWords.Select(s => s.Word).ToArray(); return(View(model)); } }
public HttpResponse Add(ProductInputModel model) { if (!this.User.IsAuthenticated) { return(this.Redirect("/Users/Login")); } var errors = this.validator.ValidateProduct(model); if (errors.Any()) { return(this.Error(errors)); } this.productService.Add(model.Name, model.Description, model.ImageUrl, model.Price, model.Category, model.Gender); return(this.Redirect("/")); }
public async Task <IActionResult> AddProduct(ProductInputModel input) { try { await this.administrationService.AddProduct(input); } catch (Exception e) { this.ModelState.AddModelError("admin", e.Message); } if (!this.ModelState.IsValid) { return(this.View()); } return(this.Redirect("/")); }
public bool UpdateProduct(int id, ProductInputModel model) { var existedProd = _context.Products.FirstOrDefault(c => c.ProductId == id); var existedProdName = _context.Products.FirstOrDefault(c => c.Name.Equals(model.Name) && c.ProductId != id); if (existedProdName != null || existedProd == null) { return(false); } Mapper.Map <ProductInputModel, Product>(model, existedProd); _context.SaveChanges(); return(true); }
public IActionResult Edit(string id) { var product = this.productsService.GetProductById(id); var inputModel = new ProductInputModel { Id = id, Name = product.Name, Manifacturer = product.Мanifacturer, Description = product.Description, Price = product.Price, Quantity = product.Quantity, Image = product.Image, }; ViewBag.Data = inputModel; return(View()); }
private Product MapProduct(ProductInputModel productModel) { Product product = new Product(); product.IdProduct = productModel.IdProduct; product.Name = productModel.Name; product.Status = productModel.Status; product.PurchasePrice = productModel.PurchasePrice; product.SalePrice = productModel.SalePrice; product.UnitMeasure = productModel.UnitMeasure; product.QuantityStock = productModel.QuantityStock; product.Iva = productModel.Iva; product.Description = productModel.Description; product.Supplier = null; return(product); }
public async Task ProdutoValido_Add_RetornaProdutoVmComMesmosCampos() { // Arrange var productRepositoryMock = new Mock <IProductRepository>(); var productInputModel = new ProductInputModel("Um chinelo", "Um chinelo tamanho 42", 10); productRepositoryMock.Setup(pr => pr.Add(It.IsAny <Product>())).Verifiable(); var productService = new ProductService(productRepositoryMock.Object); // Act var product = await productService.Add(productInputModel); // Assert Assert.Equal(productInputModel.Title, product.Title); productRepositoryMock.Verify(pr => pr.Add(It.IsAny <Product>()), Times.Once); }
public async Task ProductInputModelIsValidAndProductExistAtDb_ProductNotAdded_ReturnsAlreadyExistExceptionError() { //arrange var product = new Product("Skol lata", 2.39M); var company = new Company("Vendinha da esquina"); var productInputModel = new ProductInputModel("Skol lata", 2.39M, Guid.NewGuid()) { CompanyId = Guid.NewGuid() }; mockProductRepository.Setup(x => x.Any(It.IsAny <Expression <Func <Product, bool> > >(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(true)); mockUserService.Setup(x => x.Get(It.IsAny <Expression <Func <Company, bool> > >(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(company)); var productService = GenerateProductServiceIntance(); //assert await Assert.ThrowsAsync <Exception>(async() => await productService.AddProduct(productInputModel, new CancellationToken())); }
public async Task ProductUpdateModelIsValid_TryToGetProductButReturnsNull_ReturnsNotFoundExceptionAsResultMessage() { //arrange Product product = null; var company = new Company("Vendinha da esquina"); var productInputModel = new ProductInputModel("Skol lata", 2.39M, Guid.NewGuid()) { CompanyId = Guid.NewGuid() }; mockProductRepository.Setup(x => x.Get(It.IsAny <Expression <Func <Product, bool> > >(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(product)); mockUserService.Setup(x => x.Get(It.IsAny <Expression <Func <Company, bool> > >(), It.IsAny <CancellationToken>())).Returns(Task.FromResult(company)); var productService = GenerateProductServiceIntance(); //assert await Assert.ThrowsAsync <NotFoundException>(async() => await productService.UpdateProduct(Guid.NewGuid(), productInputModel, new CancellationToken())); }
public IActionResult Create([FromBody] ProductInputModel inputModel) { if (inputModel == null) { return(BadRequest()); } var product = inputModel.ToEntity(); product = _store.Create(product); var outputModel = ProductOutputModel.FromEntity(product); var result = CreatedAtRoute("ViewProduct", new { id = outputModel.Id }, outputModel); return(result); }
public async Task <ActionResult <ProductViewModel> > Post(ProductInputModel productInput) { Product product = Map(productInput); var response = productService.Save(product); if (response.Error) { ModelState.AddModelError("Guardar Producto", response.Message); var problemDetails = new ValidationProblemDetails(ModelState) { Status = StatusCodes.Status400BadRequest, }; return(BadRequest(problemDetails)); } var productViewModel = new ProductViewModel(response.Product); await _hubContext.Clients.All.SendAsync("ProductoRegistrado", productViewModel); return(Ok(productViewModel)); }
public string ValidateProductInputModelUponCreation(ProductInputModel model) { var validationResult = string.Empty; validationResult += model.Name == null ? $"{ResponseMessages.NameFieldMissing} \n" : ValidateName(model.Name); validationResult += model.Price == null ? $"{ResponseMessages.PriceFieldMissing} \n" : ValidatePrice((decimal)model.Price); validationResult += model.Manufacturer == null ? $"{ResponseMessages.ManufacturerFieldMissing} \n" : ValidateName(model.Manufacturer); validationResult += model.ManufacturingYear == null ? $"{ResponseMessages.ManufacturingYearFieldMissing} \n" : ValidateYear((int)model.ManufacturingYear); validationResult += model.Depth == null ? $"{ResponseMessages.DepthFieldMissing} \n" : ValidateValueNotZeroOrNegative((decimal)model.Depth); validationResult += model.Width == null ? $"{ResponseMessages.WidthFieldMissing} \n" : ValidateValueNotZeroOrNegative((decimal)model.Width); validationResult += model.Height == null ? $"{ResponseMessages.HeightFieldMissing} \n" : ValidateValueNotZeroOrNegative((decimal)model.Weight); validationResult += model.Weight == null ? $"{ResponseMessages.WeightFieldMissing} \n" : ValidateValueNotZeroOrNegative((decimal)model.Weight); validationResult += model.Wattage == null ? $"{ResponseMessages.WattageFieldMissing} \n" : ValidateValueNotZeroOrNegative((int)model.Wattage); validationResult += model.Voltage == null ? $"{ResponseMessages.VoltageFieldMissing} \n" : ValidateValueNotZeroOrNegative((int)model.Voltage); return(validationResult); }
public IActionResult Edit(int id) { var product = this.dbContext.Products.FirstOrDefault(p => p.Id == id); if (product == null) { return(this.BadRequest("Invalid product id.")); } var viewModel = new ProductInputModel { Name = product.Name, Description = product.Description, Price = product.Price, ProductType = (int)product.Type }; return(this.View(viewModel)); }
public async Task <IActionResult> PostAsync([FromBody] ProductInputModel value) { try { if (!ModelState.IsValid) { return(BadRequest()); } return(await productCommandsHandler.CreateAsync(value) ? (IActionResult)StatusCode(201) : BadRequest(true)); } catch (Exception exp) { logger?.LogException(exp); return(StatusCode(500)); } }
public HttpResponse Add(ProductInputModel inputModel) { if (!this.IsUserLoggedIn()) { return(this.Redirect("/Users/Login")); } if (string.IsNullOrEmpty(inputModel.Name) || inputModel.Name.Length < 4 || inputModel.Name.Length > 20) { return(this.View()); } if (inputModel.Description.Length > 10) { return(this.View()); } this.productsService.Add(inputModel); return(this.Redirect("/")); }
public IActionResult Edit(int id, [FromForm] ProductInputModel inputModel) { if (inputModel == null) { return(View()); } if (!ModelState.IsValid) { return(View(inputModel.ToEntity())); } int productId = id; try { var product = _store.GetById(productId); if (null == product) { return(NotFound()); } product.Name = inputModel.Name; product.Description = inputModel.Description; product.Price = inputModel.Price; _store.Update(product); productId = product.Id; } catch (DbUpdateConcurrencyException) { if (!_store.Exists(productId)) { return(NotFound()); } throw; } return(RedirectToAction(nameof(Index))); }
public async Task <IActionResult> Update(int id, [FromBody] ProductInputModel model) { var oldProduct = this.ctx.Products.FirstOrDefault(m => m.Id == id); if (oldProduct == null) { return(NotFound()); } oldProduct.Description = model.Description; oldProduct.MeasureId = model.MeasureId; oldProduct.PricePerUnit = model.PricePerUnit; oldProduct.Title = model.Title; if (await this.ctx.SaveChangesAsync() > 0) { return(Ok(oldProduct)); } return(BadRequest()); }
public ICollection <string> ValidateProduct(ProductInputModel model) { var errors = new List <string>(); if (string.IsNullOrWhiteSpace(model.Name) || model.Name.Length < 4 || model.Name.Length > 20) { errors.Add($"Name '{model.Name}' is not valid. It must be between {4} and {20} characters long."); } if (string.IsNullOrWhiteSpace(model.Description) || model.Description.Length > 10) { errors.Add($"Name '{model.Description}' is not valid. It must be less than {10} characters long."); } if (string.IsNullOrWhiteSpace(model.ImageUrl)) { errors.Add($"ImageUrl is required"); } return(errors); }
public ActionResult addProductAjax(ProductInputModel p) { return Json(this._app.products().add(p)); }
public ActionResult editProductAjax(ProductInputModel p) { return Json(this._app.products().edit(p)); }
public ActionResult DeleteProduct(ProductInputModel p) { return Json(this._app.products().delete((long)p.prodId)); }