public HttpResponseMessage Update([FromBody] InvoiceModel invoiceModel) { var command = new UpdateInvoiceCommand(invoiceModel); _commandDispatcher.Handle(command); return(Request.CreateResponse(HttpStatusCode.OK)); }
public async Task Given_TheCallIsCancelledByUser_When_HandlerIsCalled_Then_TheHandlerShouldThrowOperationCancelledException() { using (var cancellationTokenSource = new CancellationTokenSource()) { var cancellationToken = cancellationTokenSource.Token; cancellationTokenSource.Cancel(); var setupInvoice = new Invoice { Amount = 100, Identifier = "TEST-100" }; await _applicationDbContext.Invoices.AddAsync(setupInvoice); await _applicationDbContext.SaveChangesAsync(); var setupUpdateInvoiceDto = new UpdateInvoiceDto() { Amount = 200, Identifier = "TEST-200", InvoiceId = setupInvoice.InvoiceId }; var setupUpdateInvoiceCommand = new UpdateInvoiceCommand(setupUpdateInvoiceDto); Func <Task <UpdateInvoiceCommandResponse> > func = async() => await _systemUnderTest.Handle(setupUpdateInvoiceCommand, cancellationToken); await func.Should().ThrowAsync <OperationCanceledException>(); } }
public async Task Handle_UpdateInvoiceCommand_Failed_DuplicateInvoice() { //arrange var command = new UpdateInvoiceCommand() { Id = Guid.NewGuid(), Name = "Name", Description = "Description" }; _mocker.GetMock <IInvoiceRepository>() .Setup(m => m.GetById(It.IsAny <Guid>())) .Returns(new Invoice()) .Verifiable("IInvoiceRepository.GetById should have been called"); _mocker.GetMock <IInvoiceRepository>() .Setup(m => m.GetByName(It.IsAny <string>())) .Returns(new Invoice() { Id = Guid.NewGuid(), Name = command.Name }) .Verifiable("IInvoiceRepository.GetByName should have been called"); //act var result = await _invoiceCommandHandler.Handle(command, new CancellationToken()); //assert _mocker.GetMock <IInvoiceRepository>().Verify(); Assert.False(result); }
public async Task <UpdateInvoiceByIdResponse> Handle(UpdateInvoiceByIdRequest request, CancellationToken cancellationToken) { var query = new GetInvoiceQuery() { Id = request.Id }; var getInvoice = await this.queryExecutor.Execute(query); if (getInvoice == null) { return(new UpdateInvoiceByIdResponse() { Error = new ErrorModel(ErrorType.NotFound) }); } var mappedCommand = this.mapper.Map <DataAccess.Entities.Invoice>(request); var command = new UpdateInvoiceCommand() { Parameter = mappedCommand }; var created = await this.commandExecutor.Execute(command); var response = new UpdateInvoiceByIdResponse() { Data = this.mapper.Map <API.Domain.Models.Invoice>(created) }; return(response); }
public async Task Handle_UpdateInvoiceCommand_InvoiceNotFound() { //arrange var command = new UpdateInvoiceCommand() { Id = Guid.NewGuid(), Name = "Name", Description = "Description" }; _mocker.GetMock <IInvoiceRepository>() .Setup(m => m.GetById(It.IsAny <Guid>())) .Returns(value: null) .Verifiable("IInvoiceRepository.GetById should have been called"); _mocker.GetMock <IMediatorHandler>() .Setup(m => m.RaiseEvent(It.IsAny <NotFoundEvent>())) .Verifiable("An event NotFoundEvent should have been raised"); //act var result = await _invoiceCommandHandler.Handle(command, new CancellationToken()); //assert _mocker.GetMock <IMediatorHandler>().Verify(); Assert.False(result); }
public async Task Given_ThereIsAnInvoiceUpdate_When_HandlerIsCalled_Then_TheInvoiceIsUpdatedAndOkStatusReturned() { //arrange var setupInvoice = new Invoice { Amount = 100, Identifier = "TEST-100" }; await _applicationDbContext.Invoices.AddAsync(setupInvoice); await _applicationDbContext.SaveChangesAsync(); var setupUpdateInvoiceDto = new UpdateInvoiceDto() { Amount = 200, Identifier = "TEST-200", InvoiceId = setupInvoice.InvoiceId }; var setupUpdateInvoiceCommand = new UpdateInvoiceCommand(setupUpdateInvoiceDto); //act var response = await _systemUnderTest.Handle(setupUpdateInvoiceCommand, default); //assert response.StatusCode.Should().Be(HttpStatusCode.OK); response.Error.Should().BeNull(); response.HasError.Should().BeFalse(); var databaseInvoice = await _applicationDbContext.Invoices .SingleOrDefaultAsync(invoice => invoice.InvoiceId == setupInvoice.InvoiceId); databaseInvoice.Should().NotBeNull(); databaseInvoice.Amount.Should().Be(setupUpdateInvoiceDto.Amount); databaseInvoice.Identifier.Should().Be(setupUpdateInvoiceDto.Identifier); }
public Task Consume(ConsumeContext <UpdateInvoiceCommand> context) { try { UpdateInvoiceCommand updateInvoice = context.Message; List <Item> items = new List <Item>(); updateInvoice.Items.ToList().ForEach(x => { Item item = new Item( new IsDeliveried(x.Deliveried), new Quantity(x.DeliveriedQuantity), new Price(x.Price), new Name(x.ProductName), new Quantity(x.Quantity), new Price(x.TotalPrice), new Unit(x.UnitName), new Weight(Convert.ToDouble(x.Weight)) ); items.Add(item); }); Model.Entity.Invoice invoice = new Model.Entity.Invoice( new Code(updateInvoice.Code), new Price(updateInvoice.TotalPrice), new Weight(updateInvoice.WeightTotal), items); return(_invoiceRepository.Update(invoice)); } catch (Exception ex) { Console.Write(ex.Message); throw; } }
public async Task <ActionResult> Update([FromRoute] Guid id, UpdateInvoiceCommand command, CancellationToken cancellationToken) { command.SetInvoiceId(id); await Mediator.Send(command, cancellationToken); return(NoContent()); }
public async Task <ApiResponse> UpdateInvoice([FromBody] UpdateInvoiceCommand command) { var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value; command.ModifiedById = userId; command.ModifiedDate = DateTime.UtcNow; return(await _mediator.Send(command)); }
public async Task Given_TheUpdateInvoiceFailsInDatabase_When_HandlerIsCalled_Then_ItShouldReturnInternalServerError() { using (var cancellationTokenSource = new CancellationTokenSource()) { //arrange var cancellationToken = cancellationTokenSource.Token; var setupException = new Exception("test update exception"); var setupInvoice = new Invoice { Amount = 100, Identifier = "TEST-100" }; await _applicationDbContext.Invoices.AddAsync(setupInvoice); await _applicationDbContext.SaveChangesAsync(); var setupUpdateInvoiceDto = new UpdateInvoiceDto() { Amount = 200, Identifier = "TEST-200", InvoiceId = setupInvoice.InvoiceId }; var setupUpdateInvoiceCommand = new UpdateInvoiceCommand(setupUpdateInvoiceDto); var mockRepositoryOutput = new Queue <Invoice>(new[] { setupInvoice, null }); var mockApplicationUnitOfWork = _mockRepository.Create <IApplicationUnitOfWork>(); var mockInvoiceRepository = _mockRepository.Create <IApplicationRepository <Invoice> >(); mockInvoiceRepository.Setup(x => x.SingleOrDefaultAsync(It.IsAny <Expression <Func <Invoice, bool> > >(), It.IsAny <CancellationToken>())) .ReturnsAsync(() => mockRepositoryOutput.Dequeue()); mockInvoiceRepository.Setup(x => x.Update(It.IsAny <Invoice>())); mockApplicationUnitOfWork.Setup(x => x.CommitAsync(cancellationToken)).ThrowsAsync(setupException); mockApplicationUnitOfWork.Setup(x => x.Invoices).Returns(mockInvoiceRepository.Object); _systemUnderTest = new UpdateInvoiceCommandHandler(mockApplicationUnitOfWork.Object, _logger.Object, _authenticatedUserService.Object); //act var response = await _systemUnderTest.Handle(setupUpdateInvoiceCommand, cancellationToken); //assert response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); response.Error.Should().NotBeNull(); response.Error.ErrorCode.Should().Be(ApplicationConstants.ErrorCodes.UpdateInvoiceError); response.Error.ErrorMessage.Should().Be(setupException.Message); var databaseInvoice = await _applicationDbContext.Invoices .SingleOrDefaultAsync(invoice => invoice.InvoiceId == setupInvoice.InvoiceId); databaseInvoice.Should().NotBeNull(); databaseInvoice.Amount.Should().Be(setupInvoice.Amount); databaseInvoice.Identifier.Should().Be(setupInvoice.Identifier); } }
public async Task <IActionResult> UpdateInvoice([FromRoute] long id, [FromBody] UpdateInvoiceCommand command) { command.Id = id; var response = await _mediator.Send <ResultResponse <InvoiceDTO> >(command); if (response.IsSuccess) { return(Ok(response.Result)); } return(BadRequest(response.ErrorMessage)); }
public async Task <IActionResult> UpdateInvoice([FromBody] UpdateInvoiceCommand command) { if (command == null) { throw new ArgumentNullException(nameof(command)); } if (!ModelState.IsValid) { return(BadRequest(400)); } var updated = await _mediator.Send(command); return(Ok(updated)); }
public async Task Given_ThereIsAnInvoiceUpdateAndAnotherInvoiceHasTheSameIdentifier_When_HandlerIsCalled_Then_BadRequestResponseIsReturned() { //arrange var setupInvoice1 = new Invoice { Amount = 100, Identifier = "TEST-100" }; var setupInvoice2 = new Invoice { Amount = 200, Identifier = "TEST-200" }; await _applicationDbContext.Invoices.AddAsync(setupInvoice1); await _applicationDbContext.Invoices.AddAsync(setupInvoice2); await _applicationDbContext.SaveChangesAsync(); var setupUpdateInvoiceDto = new UpdateInvoiceDto() { Amount = 200, Identifier = "TEST-200", InvoiceId = setupInvoice1.InvoiceId }; var setupUpdateInvoiceCommand = new UpdateInvoiceCommand(setupUpdateInvoiceDto); //act var response = await _systemUnderTest.Handle(setupUpdateInvoiceCommand, default); //assert response.StatusCode.Should().Be(HttpStatusCode.BadRequest); response.Error.Should().NotBeNull(); response.HasError.Should().BeTrue(); response.Error.ErrorCode.Should().Be(ApplicationConstants.ErrorCodes.BusinessValidationError); response.Error.ErrorMessage.Should().Be(string.Format(ApplicationConstants.ErrorMessages.DuplicateInvoiceIdentifier, setupUpdateInvoiceDto.Identifier)); var databaseInvoice1 = await _applicationDbContext.Invoices .SingleOrDefaultAsync(invoice => invoice.InvoiceId == setupInvoice1.InvoiceId); databaseInvoice1.Amount.Should().Be(setupInvoice1.Amount); databaseInvoice1.Identifier.Should().Be(setupInvoice1.Identifier); var databaseInvoice2 = await _applicationDbContext.Invoices .SingleOrDefaultAsync(invoice => invoice.InvoiceId == setupInvoice2.InvoiceId); databaseInvoice2.Amount.Should().Be(setupInvoice2.Amount); databaseInvoice2.Identifier.Should().Be(setupInvoice2.Identifier); }
public Task <object> Handle(UpdateInvoiceCommand command, CancellationToken cancellationToken) { if (!command.IsValid()) { NotifyValidationErrors(command); } else { List <InvoiceItem> items = new List <InvoiceItem>(); foreach (InvoiceItemModel invoiceItem in command.Items) { InvoiceItem item = new InvoiceItem ( new Identity((uint)invoiceItem.ID), new Entities.Product(new Identity((uint)invoiceItem.ProductID), null, null, null, null, null, null, null), new Entities.Unit(new Identity((uint)invoiceItem.UnitID), null), new Price(invoiceItem.Price), new Note(invoiceItem.Note), new Quantity(invoiceItem.Quantity), new Weight(invoiceItem.Weight), new Price(invoiceItem.TotalPrice), new Deliveried(false), new Quantity(0) ); items.Add(item); } Entities.Invoice Invoice = new Entities.Invoice ( new Identity((uint)command.ID), new Entities.Customer((uint)command.CustomerID, null, null, null, null, null, null, null, null), new DeliveryTime(command.DeliveryTime), new Price(command.TotalPrice), new Note(command.Note), new Weight(command.WeightTotal), new Code(command.Code), items ); bool result = _InvoiceRepository.Update(Invoice); return(Task.FromResult(result as object)); } return(Task.FromResult(null as object)); }
public async Task Handle_UpdateInvoiceCommand_Failed_Validation() { //arrange var command = new UpdateInvoiceCommand() { Id = Guid.Empty, // invalid value, should failed validation Name = "Name", Description = "Description" }; _mocker.GetMock <IMediatorHandler>() .Setup(m => m.RaiseEvent(It.IsAny <DomainValidationEvent>())) .Verifiable("An event InvoiceUpdatedEvent should have been raised"); //act var result = await _invoiceCommandHandler.Handle(command, new CancellationToken()); //assert _mocker.GetMock <IMediatorHandler>().Verify(); Assert.False(result); }
public async Task Given_ThereIsAnInvoiceUpdateForAnInvoiceCreatedByOtherUser_When_HandlerIsCalled_Then_ForbidenResponseIsReturned() { //arrange var setupInvoice = new Invoice { Amount = 100, Identifier = "TEST-100" }; await _applicationDbContext.Invoices.AddAsync(setupInvoice); await _applicationDbContext.SaveChangesAsync(); var setupUpdateInvoiceDto = new UpdateInvoiceDto() { Amount = 200, Identifier = "TEST-200", InvoiceId = setupInvoice.InvoiceId }; var setupUpdateInvoiceCommand = new UpdateInvoiceCommand(setupUpdateInvoiceDto); _authenticatedUserService.Setup(x => x.GetUserId()).Returns(200); //act var response = await _systemUnderTest.Handle(setupUpdateInvoiceCommand, default); //assert response.StatusCode.Should().Be(HttpStatusCode.Forbidden); response.Error.Should().NotBeNull(); response.HasError.Should().BeTrue(); response.Error.ErrorCode.Should().Be(ApplicationConstants.ErrorCodes.AuthorizationError); response.Error.ErrorMessage.Should().Be(string.Format(ApplicationConstants.ErrorMessages.InvoiceCreatedByDifferentUser, setupUpdateInvoiceDto.InvoiceId)); var databaseInvoice = await _applicationDbContext.Invoices .SingleOrDefaultAsync(invoice => invoice.InvoiceId == setupInvoice.InvoiceId); databaseInvoice.Should().NotBeNull(); databaseInvoice.Amount.Should().Be(setupInvoice.Amount); databaseInvoice.Identifier.Should().Be(setupInvoice.Identifier); }
public async Task Handle_UpdateInvoiceCommand_Return_True() { //arrange var command = new UpdateInvoiceCommand() { Id = Guid.NewGuid(), Name = "Name", Description = "Description" }; _mocker.GetMock <IInvoiceRepository>() .Setup(m => m.GetById(It.IsAny <Guid>())) .Returns(new Invoice()) .Verifiable("IInvoiceRepository.GetById should have been called"); _mocker.GetMock <IInvoiceRepository>() .Setup(m => m.GetByName(It.IsAny <string>())) .Returns(new Invoice() { Id = command.Id, Name = command.Name }) .Verifiable("IInvoiceRepository.GetByName should have been called"); _mocker.GetMock <IInvoiceRepository>() .Setup(m => m.Update(It.IsAny <Invoice>())) .Verifiable("IInvoiceRepository.Update should have been called"); _mocker.GetMock <IMediatorHandler>() .Setup(m => m.RaiseEvent(It.IsAny <InvoiceUpdatedEvent>())) .Verifiable("An event InvoiceUpdatedEvent should have been raised"); //act var result = await _invoiceCommandHandler.Handle(command, new CancellationToken()); //assert _mocker.GetMock <IInvoiceRepository>().Verify(); _mocker.GetMock <IMediatorHandler>().Verify(); Assert.True(result); }
public async Task <bool> Handle(UpdateInvoiceCommand request, CancellationToken cancellationToken) { if (!request.IsValid()) { await _mediatorHandler.RaiseEvent(new DomainValidationEvent(request.ValidationResult.ToString())); return(false); } var oldInvoice = _invoiceRepository.GetById(request.Id); if (oldInvoice == null) { await _mediatorHandler.RaiseEvent(new NotFoundEvent(request.Id, "Invoice", "Invoice not found")); return(false); } var getByName = _invoiceRepository.GetByName(request.Name); if (getByName != null && getByName.Id != request.Id) { await _mediatorHandler.RaiseEvent(new DuplicatedRecordEvent("Name", "Invoice", "{0} is already present. Please select another Invoice Name")); return(false); } var model = _mapper.Map <Invoice>(request); _invoiceRepository.Update(model); await _mediatorHandler.RaiseEvent(new InvoiceUpdatedEvent() { Old = oldInvoice, New = model }); return(true); }
public Task <UpdateInvoiceResponse> updateInvoice(UpdateInvoiceRequest request) { List <InvoiceItem> items = new List <InvoiceItem>(); int totalPrice = 0; decimal totalWeight = 0; foreach (InvoiceItemModel invoiceItem in request.Items) { totalPrice += invoiceItem.TotalPrice; decimal weightPerUnit = _ProductRepository.GetWeightPerUnit(invoiceItem.ProductID, invoiceItem.UnitID); invoiceItem.Weight = weightPerUnit * invoiceItem.Quantity; totalWeight += invoiceItem.Weight; } UpdateInvoiceCommand command = new UpdateInvoiceCommand() { ID = request.ID, Address = request.Address, CustomerCode = request.CustomerCode, CustomerID = request.CustomerID, CustomerName = request.CustomerName, TotalPrice = totalPrice, WeightTotal = totalWeight, Note = request.Note, Code = request.Code, Items = request.Items }; Task <object> Invoice = (Task <object>)Bus.SendCommand(command); RabbitMQBus.Publish(command); UpdateInvoiceResponse response = new UpdateInvoiceResponse(); response = Common <UpdateInvoiceResponse> .checkHasNotification(_notifications, response); response.OK = response.Success; response.Content = ""; return(Task.FromResult(response)); }
public UpdateInvoiceCommandTests() { _command = new UpdateInvoiceCommand(); }