Пример #1
0
        public async Task Update_WhenDoesntHaveAuthenticationToken_ShouldReturn401Code()
        {
            // Arrange
            var updateProductData = new UpdateProductCommand
            {
                Id    = Guid.NewGuid(),
                Name  = "",
                Price = 0
            };
            var client = _factory.CreateClient();

            // Act
            var response = await client.PutAsync($"{TestConstants.ProductApiBaseUrl}/{updateProductData.Id}", updateProductData.SerializeToStringContent());

            // Assert
            Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
        }
        public Task <HttpResponseMessage> Put(int id, [FromBody] dynamic body)
        {
            var command = new UpdateProductCommand(
                id: id,
                title: (string)body.title,
                category: (int)body.category,
                description: (string)body.description,
                weight: (string)body.weight,
                price: (decimal)body.price,
                image: (string)body.image,
                quantityOnHand: (int)body.quantityOnHand
                );

            var product = _service.Update(command);

            return(CreateResponse(HttpStatusCode.OK, product));
        }
        public ActionResult <UpdateProductResponse> UpdateProduct(Guid id, Product product)
        {
            try
            {
                var command = new UpdateProductCommand {
                    Id = id, Product = product
                };
                var response = _mediator.Send(command);

                return(Ok(response));
            }
            catch (Exception e)
            {
                _logger.LogInformation(e.Message);
                return(BadRequest(e.Message));
            }
        }
        public async Task Handle_GivenValidId_ShouldUpdatePersistedProduct()
        {
            var command = new UpdateProductCommand
            {
                Id    = 1,
                Title = "This thing is also done.",
            };

            var handler = new UpdateProductCommand.UpdateProductCommandHandler(Context);

            await handler.Handle(command, CancellationToken.None);

            var entity = Context.Products.Find(command.Id);

            entity.ShouldNotBeNull();
            entity.Title.ShouldBe(command.Title);
        }
Пример #5
0
        public async Task OnGetAsync()
        {
            var detail = await _productQuery.GetProductDetailAsync(Id);

            Command = new UpdateProductCommand
            {
                Id          = detail.Id,
                Description = detail.Description,
                Name        = detail.Name,
                CategoryId  = detail.CategoryId,
                BrandId     = detail.BrandId,
                StoreId     = detail.StoreId,
                UnitPrice   = detail.UnitPrice
            };

            await LoadData();
        }
        public async Task <ICommandResult> HandleAsync(UpdateProductCommand command)
        {
            command.Validate();
            if (command.Invalid)
            {
                return(new GenericCommandResult <ProductEntity>(false, command.Notifications));
            }

            var product = await _repository.GetAsync(command.Id);

            product.SetName(command.Name);
            product.SetPrice(command.Price);

            await _repository.UpdateAsync(product);

            return(new GenericCommandResult <ProductEntity>(true, product));
        }
        public async Task <IActionResult> Edit(int id, [Bind("Id,Name,Price,Category,Description,PhotoUrl")]
                                               UpdateProductCommand command)
        {
            if (id != command.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                await Mediator.Send(command);

                return(RedirectToAction(nameof(Index)));
            }

            return(View(command));
        }
Пример #8
0
        public async Task <(ProductViewModel Model, List <string> Errors)> ExceuteUpdate(ProductViewModel model)
        {
            UpdateProductCommand command = new UpdateProductCommand()
            {
                Id           = model.Id,
                Name         = model.Name,
                NoOfUnit     = model.NoOfUnit,
                ReOrderLevel = model.ReOrderLevel,
                UnitPrice    = model.UnitPrice
            };

            var result = await _bus.Send(command);

            return(model, !string.IsNullOrEmpty(result.ErrorMessage) ? new List <string> {
                result.ErrorMessage
            } : new List <string>());
        }
Пример #9
0
        public async Task Should_UpdateProduct_Returns200()
        {
            //arrange
            var command        = GetCreateProductCommand();
            var createdProduct = await CreateProductAsync(command);

            var updateCommand = new UpdateProductCommand(createdProduct.Id,
                                                         "testName",
                                                         123,
                                                         "testDescription",
                                                         new DimensionsDto
            {
                Height = 1.0M,
                Length = 2.0M,
                Weight = 3.0M,
                Width  = 4.0M
            });

            //act
            var path        = $"{ProductController.Update()}/{createdProduct.Id}";
            var putResponse = await Client.PutAsJsonAsync(path, updateCommand);

            var getResponse = await GetProductAsync(createdProduct.Id);

            var stringResult = await getResponse.Content.ReadAsStringAsync();

            var responseProduct = JsonConvert.DeserializeObject <ProductViewModel>(stringResult);

            //assert
            putResponse.StatusCode.Should().Be(HttpStatusCode.OK);
            getResponse.StatusCode.Should().Be(HttpStatusCode.OK);

            command.Should().NotBeNull();
            command.Name.Should().Be(createdProduct.Name);
            command.Description.Should().Be(createdProduct.Description);
            command.BarCode.Should().Be(createdProduct.BarCode);
            command.Price.Should().Be(createdProduct.Price);
            command.Dimensions.Should().Be(createdProduct.Dimensions);
            command.ManufacturerId.Should().Be(createdProduct.ManufacturerId);

            responseProduct.Id.Should().Be(updateCommand.Id);
            responseProduct.Name.Should().Be(updateCommand.Name);
            responseProduct.Price.Should().Be(updateCommand.Price);
            responseProduct.Description.Should().Be(updateCommand.Description);
            responseProduct.Dimensions.Should().Be(updateCommand.Dimensions);
        }
Пример #10
0
        public void ShouldThrowProductNotFoundException()
        {
            // Update Product Command
            var updateProductCommand = new UpdateProductCommand
            {
                AvailableToSell = false,
                // created brand id
                BrandId = Guid.NewGuid().ToString(),
                // created product category id
                ProductCategoryId = Guid.NewGuid().ToString(),
                Name     = "Test Product Name Update",
                PhotoUrl = "Test Product PhotoUrl Update",
                Barcode  = "Test Product Barcode Update",
                Id       = Guid.NewGuid().ToString()
            };

            FluentActions.Invoking(() => SendAsync(updateProductCommand)).Should().Throw <ProductNotFoundException>();
        }
        public async Task <IActionResult> UpdateProduct(Guid prodid, Product product)
        {
            var query  = new UpdateProductCommand(product, prodid);
            var output = await _mediator.Send(query);

            if (!String.IsNullOrEmpty(output.Name))
            {
                ModelState.AddModelError("product", output.Name);
                return(BadRequest(ModelState));
            }
            else if (output.ID == Guid.Empty)
            {
                ModelState.AddModelError("product", "Product deos not exist");
                return(BadRequest(ModelState));
            }

            return(CreatedAtAction(nameof(GetProductByID), new { categid = output.ID }, output));
        }
Пример #12
0
        public async Task <IActionResult> UpdateProduct([FromRoute] Guid id, [FromBody] UpdateProductCommand command)
        {
            if (id != command.Id)
            {
                return(BadRequest("Product id in route not match id in payload"));
            }

            try
            {
                var productDto = await Mediator.Send(command);

                return(CreatedAtAction("GetProduct", new { id = productDto.Id }, productDto));
            }
            catch (NotFoundException e)
            {
                return(NotFound(e.Message));
            }
        }
Пример #13
0
        public async Task GivenUpdateProductCommand_ReturnsSuccessStatusCode()
        {
            var command = new UpdateProductCommand
            {
                ProductId    = 77,
                ProductName  = "Original Frankfurter grüne Soße",
                SupplierId   = 12,
                CategoryId   = 2,
                UnitPrice    = 15.00m,
                Discontinued = false
            };

            var content = Utilities.GetRequestContent(command);

            var response = await _client.PutAsync($"/api/products/update", content);

            response.EnsureSuccessStatusCode();
        }
        public async Task <IActionResult> Put(Guid id, [FromBody] UpdateProductCommand command)
        {
            command.Id = id;
            try
            {
                await _updateHandler.HandleAsync(command);
            }
            catch (ArgumentException ex)
            {
                return(NotFound(ex.Message));
            }
            catch (ModelException ex)
            {
                return(BadRequest(ex.Message));
            }

            return(Ok());
        }
Пример #15
0
        public void Should_Update_Product_When_Command_Is_Valid()
        {
            var products = _fakeProductRepository.GetAllAsync();
            var product  = products.Result.FirstOrDefault();

            var command = new UpdateProductCommand
            {
                Id          = product.Id,
                Name        = "Produto teste",
                Description = "Descrição produto teste",
                Price       = 100
            };

            var result = _handler.Handle(command);

            Assert.AreNotEqual(null, result);
            Assert.AreEqual(true, _handler.Valid);
        }
Пример #16
0
        public ICommandResult Handle(UpdateProductCommand command)
        {
            command.Validate();
            if (command.Invalid)
            {
                return(new GenericCommandResult(false, "Ocorreu um erro na atualização do produto, verifique os dados...", command.Notifications));
            }

            Product product = _repository.GetById(command.Id);

            product.Name  = command.Name;
            product.Value = command.Value;
            product.Image = command.Image;

            _repository.Update(product);

            return(new GenericCommandResult(true, "Produto atualizado com sucesso", product));
        }
Пример #17
0
        public async Task GivenUpdateProductCommandWithInvalidId_ReturnsNotFoundStatusCode()
        {
            var invalidCommand = new UpdateProductCommand
            {
                ProductId    = 0,
                ProductName  = "Original Frankfurter grüne Soße",
                SupplierId   = 12,
                CategoryId   = 2,
                UnitPrice    = 15.00m,
                Discontinued = false
            };

            var content = Utilities.GetRequestContent(invalidCommand);

            var response = await _client.PutAsync($"/api/products/update", content);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
        public bool UpdateProduct(UpdateProductCommand updateProductCommand)
        {
            using (var db = new SqlConnection(_connectionString))
            {
                var sql = @"UPDATE [dbo].[Product]
                           SET [Title] = @Title
                              ,[Category] = @Category
                              ,[RentalPrice] = @RentalPrice
                              ,[SalesPrice] = @SalesPrice
                              ,[IsForSale] = @IsForSale
                              ,[IsRgb] = @IsRgb
                              ,[Description] = @Description
                              ,[ImageUrl] = @ImageUrl
                         WHERE [Id] = @Id";

                return(db.Execute(sql, updateProductCommand) == 1);
            }
        }
Пример #19
0
        public async Task <IActionResult> Put(int id, [FromBody] Product product)
        {
            try
            {
                //Log Information - Request
                _logger.LogInformation($"Received Request : HTTPPUT api/products");

                //Check if Product exists.
                Product productInDb = await _mediator.Send(new FindProductByIdQuery()
                {
                    ProductId = id
                });

                if (productInDb == null)
                {
                    // Log warning and return HTTP 404
                    _logger.LogWarning($"Not Found : HTTPPUT api/products/{id}");
                    return(NotFound());
                }

                //Create command object
                UpdateProductCommand updateCmd = new UpdateProductCommand
                {
                    ProductId    = product.ProductId,
                    Description  = product.Description,
                    Name         = product.Name,
                    UnitPrice    = product.UnitPrice,
                    UnitsInStock = product.UnitsInStock,
                    IsActive     = product.IsActive
                };

                //Send command
                await _mediator.Send(updateCmd);

                //Return
                return(NoContent());
            }
            catch (Exception ex)
            {
                // Log the failure and return HTTP 500
                _logger.LogError($"Error at HTTPPUT api/products/{id}:{ex}");
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Пример #20
0
        public UpdateProductHandlerTests()
        {
            _productRepository = Substitute.For <IProductRepository>();

            var productValid = _fixture.Create <ProductEntity>();

            _productRepository.GetAsync(productValid.Id).Returns(productValid);

            _handler = new ProductHandler(_productRepository);

            _commandWithoutName = _fixture
                                  .Build <UpdateProductCommand>()
                                  .Without(x => x.Name)
                                  .With(x => x.Id, productValid.Id)
                                  .Create();

            _commandWithName = _fixture
                               .Build <UpdateProductCommand>()
                               .With(x => x.Name, _fixture.Create <string>())
                               .With(x => x.Id, productValid.Id)
                               .Create();

            _commandWithPriceZero = _fixture
                                    .Build <UpdateProductCommand>()
                                    .With(x => x.Price, 0)
                                    .With(x => x.Id, productValid.Id)
                                    .Create();

            _commandWithPriceGreaterZero = _fixture
                                           .Build <UpdateProductCommand>()
                                           .With(x => x.Price, 450)
                                           .With(x => x.Id, productValid.Id)
                                           .Create();

            _commandWithInvalidId = _fixture
                                    .Build <UpdateProductCommand>()
                                    .Without(x => x.Id)
                                    .Create();

            _commandWithValidId = _fixture
                                  .Build <UpdateProductCommand>()
                                  .With(x => x.Id, productValid.Id)
                                  .Create();
        }
        public Task <bool> Handle(UpdateProductCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                return(Task.FromResult(false));
            }

            var produto = new Produto(request.id, request.nome, request.fornecedor, request.marca, request.valor);

            _repository.Update(produto);
            _repository.Save();

            if (produto == null)
            {
                throw new Exception("Valor não pode ser nulo");
            }

            return(Task.FromResult(true));
        }
        public Task <bool> Handle(UpdateProductCommand message, CancellationToken cancellationToken)
        {
            if (!message.IsValid())
            {
                NotifyValidationErrors(message);
                return(Task.FromResult(false));
            }

            var product = new Product(message.Id, message.Name);

            _productRepository.Update(product);

            if (Commit())
            {
                Bus.RaiseEvent(new ProductUpdatedEvent(product.Id, product.Name));
            }

            return(Task.FromResult(true));
        }
Пример #23
0
 public void HandleUpdate(UpdateProductCommand command, IAppUnitOfWorkFactory uowFactory)
 {
     using (IAppUnitOfWork uow = uowFactory.Create())
     {
         Product product = uow.ProductRepository.Get(command.ProductId, Product.IncludeAll);
         Company company = uow.CompanyRepository.Get(command.CompanyId);
         if (company == null)
         {
             throw new DomainException("The assigned company not found");
         }
         User updater = uow.Users.FirstOrDefault(u => u.Id == command.UpdatedByUserId);
         if (updater == null)
         {
             throw new DomainException("Can not find updater");
         }
         // Delete properties
         foreach (ProductProperty removedProperty in product.Properties.Where(oldP => !command.Properties.Any(newP => newP.Id == oldP.Id)).ToList())
         {
             product.Properties.Remove(removedProperty);
             uow.ProductPropertyRepository.Remove(removedProperty);
         }
         // Update existing properties
         foreach (ProductProperty existProperty in product.Properties)
         {
             ProductProperty updatedProperty = command.Properties.SingleOrDefault(pp => pp.Id == existProperty.Id);
             existProperty.Name  = updatedProperty.Name;
             existProperty.Value = updatedProperty.Value;
         }
         // Add new properties
         foreach (ProductProperty property in command.Properties.Where(pp => pp.Id == 0))
         {
             product.Properties.Add(property);
         }
         product.Company   = company;
         product.Name      = command.Name;
         product.Comment   = command.Comment;
         product.Quantity  = command.Quantity;
         product.Sku       = command.Sku;
         product.IsActive  = command.IsActive;
         product.UpdatedAt = DateTime.Now;
         uow.SaveChanges();
     }
 }
        public Task <bool> Handle(UpdateProductCommand request, CancellationToken cancellationToken)
        {
            var product = new Product(request.Id, request.Name, request.Description, request.ShortDescription, request.Price);

            if (!request.IsValid())
            {
                NotifyValidationErrors(request);
                return(Task.FromResult(false));
            }

            _repository.Update(product);

            if (Commit())
            {
                Bus.RaiseEvent(new ProductUpdatedEvent());
            }

            return(Task.FromResult(true));
        }
Пример #25
0
        public void Update(string name, string?description, decimal price, decimal deliveryPrice)
        {
            var command = new UpdateProductCommand
            {
                Name          = name,
                Description   = description,
                Price         = price,
                DeliveryPrice = deliveryPrice
            };

            var validator = new UpdateProductCommandValidator();

            validator.ValidateAndThrow(command);

            Name          = command.Name;
            Description   = command.Description;
            Price         = command.Price;
            DeliveryPrice = command.DeliveryPrice;
        }
Пример #26
0
        public Task <bool> Handle(UpdateProductCommand command, CancellationToken cancellationToken)
        {
            if (!command.IsValid())
            {
                NotifyErrors(command);
                return(Task.FromResult(false));
            }

            var product = new Product(command.Id, command.Name, command.Price, command.QuantityOnHand);

            _productRepository.Update(product);

            if (!Commit())
            {
                return(Task.FromResult(false));
            }

            return(Task.FromResult(true));
        }
Пример #27
0
        public Product Update(Product product)
        {
            // Execute Business validation

            var command = new UpdateProductCommand(UnitOfWork, product);

            DataBusManager.ExecuteCommand(command);

            if (command.Success)
            {
                // Success execution
            }
            else if (command.Fail)
            {
                // Fail Execution
            }

            return(command.Product);
        }
Пример #28
0
        public async Task <ActionResult> Update([FromServices] UpdateProductHandler handler,
                                                [FromBody] UpdateProductCommand command)
        {
            try
            {
                var result = (CommandResult)handler.handle(command);

                if (!result.Success)
                {
                    return(BadRequest(result));
                }

                return(Ok(result));
            }
            catch (Exception e)
            {
                return(BadRequest(e));
            }
        }
Пример #29
0
        public IHttpActionResult Update([FromBody] UpdateProductCommand command)
        {
            if (command == null)
            {
                return(BadRequest(DefaultMessages.InvalidBody));
            }
            ValidationError error = new UpdateProductCommandValidation().Validate(command);

            if (error.IsInvalid)
            {
                return(BadRequest(error.Error));
            }

            if (_repository.FindById(command.Id) == null)
            {
                return(BadRequest("Não existe um Produto com este código."));
            }
            _repository.Update(command);
            return(Ok());
        }
Пример #30
0
        public async Task <IActionResult> UpdateProduct([FromBody] Application.Models.Product product)
        {
            if (product == null)
            {
                throw new ArgumentNullException(nameof(product));
            }

            var command = new UpdateProductCommand(product);

            var result = await this._Mediator.Send(command);

            if (result.Status == CommandResultStatus.Success)
            {
                return(new OkObjectResult(result.Result));
            }
            else
            {
                return(new BadRequestObjectResult("Something went wrong"));
            }
        }