예제 #1
0
        public async Task CreatePayment_ValidRequest_CreatesPayment()
        {
            // Arrange
            IsValidationSuccess(true);

            var command = new CreatePaymentCommand()
            {
                Amount          = 100,
                CardNumber      = "1111 0000 0000 0000",
                Currency        = "EUR",
                Cvv             = "123",
                ExpirationMonth = 10,
                ExpirationYear  = 20
            };

            // Act
            var response = await _paymentService.Create(command);

            // Assert
            Assert.IsFalse(response.IsError);
            Assert.AreEqual(command.Amount, response.Result.Amount);
            Assert.AreEqual(command.CardNumber, response.Result.CardNumber);
            Assert.AreEqual(command.Currency, response.Result.Currency);
            Assert.AreEqual(command.Cvv, response.Result.Cvv);
            Assert.AreEqual(command.ExpirationMonth, response.Result.ExpirationMonth);
            Assert.AreEqual(command.ExpirationYear, response.Result.ExpirationYear);
        }
예제 #2
0
 public async Task <IActionResult> UpdatebyId(int Id, [FromBody] CreatePaymentCommand payload)
 {
     return(Ok(await _mediator.Send(new UpdatePaymentCommand()
     {
         id = Id, data = payload.data
     })));
 }
        public async Task ShouldSendPaymentToAcquiringBankAndSaveInDB()
        {
            var acquiringBankResult = Result.Ok(Guid.NewGuid());

            _mockAcquiringBankService.Setup(a => a.ProcessPayment(It.IsAny <Payment>())).ReturnsAsync(acquiringBankResult);
            _mockPaymentHistoryRepository.Setup(p => p.InsertPayment(It.IsAny <Payment>())).ReturnsAsync(Result.Ok(Guid.NewGuid()));

            var sut = new CreatePaymentCommandHandler(_mockAcquiringBankService.Object,
                                                      _mockPaymentHistoryRepository.Object, _mockMetrics.Object,
                                                      _mockLogger.Object, _mockEventStoreClient.Object);

            var command = new CreatePaymentCommand()
            {
                Amount      = 4404.44M,
                Currency    = Currency.GBP.ToString(),
                CardNumber  = "1234-5678-8765-4321",
                CVV         = 321,
                ExpiryMonth = 10,
                ExpiryYear  = 20,
                FirstName   = "Jim",
                Surname     = "Jimson"
            };

            var result = await sut.Handle(command, default);

            _mockAcquiringBankService.Verify(a => a.ProcessPayment(It.IsAny <Payment>()), Times.Once());
            _mockPaymentHistoryRepository.Verify(p => p.InsertPayment(It.IsAny <Payment>()), Times.Once());
            Assert.True(result.IsSuccess);
        }
 public CreatePaymentHandlerTests()
 {
     _eventStore            = new Mock <IEventStore <Payment> >();
     _eventDispatcher       = new Mock <IEventDispatcher <Payment> >();
     _abApiClient           = new Mock <IAcquiringBankHttpClient>();
     _sut                   = new CreatePaymentHandler(_eventStore.Object, _eventDispatcher.Object, _abApiClient.Object);
     _mockCommand           = new CreatePaymentCommand(default, default, default, default, default, default, default);
        public async Task ShouldSavePaymentToDatabaseEvenIfBankAcquirerDoesNotSucceed()
        {
            var acquiringBankResult = Result.Failure <Guid>(FakeAcquiringBankErrors.AmountMustBeLessThan10000);

            _mockAcquiringBankService.Setup(a => a.ProcessPayment(It.IsAny <Payment>())).ReturnsAsync(acquiringBankResult);

            var sut = new CreatePaymentCommandHandler(_mockAcquiringBankService.Object,
                                                      _mockPaymentHistoryRepository.Object, _mockMetrics.Object, _mockLogger.Object,
                                                      _mockEventStoreClient.Object);

            var command = new CreatePaymentCommand()
            {
                Amount      = 44044.44M,
                Currency    = Currency.GBP.ToString(),
                CardNumber  = "1234-5678-8765-4321",
                CVV         = 321,
                ExpiryMonth = 10,
                ExpiryYear  = 20,
                FirstName   = "Jim",
                Surname     = "Jimson"
            };

            var result = await sut.Handle(command, default);

            _mockAcquiringBankService.Verify(a => a.ProcessPayment(It.IsAny <Payment>()), Times.Once());
            _mockPaymentHistoryRepository.Verify(p => p.InsertPayment(It.IsAny <Payment>()), Times.Once());
            Assert.False(result.IsSuccess);
        }
        public async Task <IActionResult> Post([FromBody] PaymentRequest request)
        {
            var command = new CreatePaymentCommand(
                request.Id,
                _httpContext.HttpContext.User.Identity.Name,
                request.Amount.Value,
                request.CardNumber,
                request.ExpiryMonth.Value,
                request.ExpiryYear.Value,
                request.Cvv,
                request.Currency);

            try
            {
                // The mediator routes this command to the CreatePaymentCommandHandler.cs
                var result = await _mediator.Send(command, HttpContext.RequestAborted);

                if (result.Success)
                {
                    return(Created($"/api/v1/payments/{result.Id}", result));
                }

                return(UnprocessableEntity("Payment could not be processed."));
            }
            catch (IdempotencyViolationException) // TODO - Extract this to a middleware
            {
                return(new StatusCodeResult(429));
            }
        }
예제 #7
0
        public void ShouldRequireMinimumFields()
        {
            var command = new CreatePaymentCommand();

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <ValidationException>();
        }
예제 #8
0
        public async Task CreatePayment_GivenInvalidInput_ShouldThrowAValidationException()
        {
            var command = new CreatePaymentCommand();
            var sut     = new CreatePaymentCommand.Handler(Context);

            await sut.Invoking(async h => await h.Handle(command, CancellationToken.None))
            .Should().ThrowAsync <ValidationException>();
        }
예제 #9
0
        public void Should_have_error_when_CardNumber_is_NotCorrect()
        {
            var model = new CreatePaymentCommand {
                CreditCardNumber = "3344234"
            };
            var result = validator.TestValidate(model);

            result.ShouldHaveValidationErrorFor(person => person.CreditCardNumber);
        }
예제 #10
0
        public void Should_not_have_error_when_CardExipyDate_HasNot_Expired()
        {
            var model = new CreatePaymentCommand {
                ExpirationDate = DateTime.Now.AddDays(20)
            };
            var result = validator.TestValidate(model);

            result.ShouldNotHaveValidationErrorFor(person => person.ExpirationDate);
        }
예제 #11
0
        public void Should_Nothave_error_when_SecurityNumber_isNot_GreaterThanThree()
        {
            var model = new CreatePaymentCommand {
                SecurityCode = "223"
            };
            var result = validator.TestValidate(model);

            result.ShouldNotHaveValidationErrorFor(person => person.SecurityCode);
        }
예제 #12
0
        public void Should_not_have_error_when_CardNumber_is_Correct()
        {
            var model = new CreatePaymentCommand {
                CreditCardNumber = "370867823381128"
            };
            var result = validator.TestValidate(model);

            result.ShouldNotHaveValidationErrorFor(person => person.CreditCardNumber);
        }
예제 #13
0
        public void Should_not_have_error_when_name_is_specified()
        {
            var model = new CreatePaymentCommand {
                CardHolder = "Andrew"
            };
            var result = validator.TestValidate(model);

            result.ShouldNotHaveValidationErrorFor(person => person.CardHolder);
        }
예제 #14
0
        public void Should_have_error_when_CardHolder_is_null()
        {
            var model = new CreatePaymentCommand {
                CardHolder = null
            };
            var result = validator.TestValidate(model);

            result.ShouldHaveValidationErrorFor(person => person.CardHolder);
        }
예제 #15
0
        public void Should_Nothave_error_when_Amount_is_GreaterThanZero()
        {
            var model = new CreatePaymentCommand {
                Amount = 200
            };
            var result = validator.TestValidate(model);

            result.ShouldNotHaveValidationErrorFor(person => person.Amount);
        }
        public void SetUp()
        {
            paymentService = new Mock <IPaymentService>();
            var httpContextReader = new Mock <IHttpContextReader>();

            paymentService.Setup(ps => ps.CreatePayment(It.IsAny <PaymentUnit[]>()))
            .ReturnsAsync(new PaymentResult());

            createPaymentCommand = new CreatePaymentCommand(paymentService.Object, httpContextReader.Object);
        }
예제 #17
0
        public PaymentController()
        {
            PaymentFactory                paymentFactory       = new PaymentFactory();
            BalanceSheetServices          balanceSheetServices = new BalanceSheetServices();
            GetBalanceUnpaidQuery         unpaidsListQuery     = new GetBalanceUnpaidQuery(new DatabaseService());
            CreatePaymentViewModelFactory factory = new CreatePaymentViewModelFactory(unpaidsListQuery);
            CreatePaymentCommand          createPaymentCommand = new CreatePaymentCommand(new DatabaseService(), paymentFactory, balanceSheetServices);

            _factory = factory;
            _createPaymentCommand = createPaymentCommand;
        }
        public async Task Then_a_payment_is_created()
        {
            //Arrange
            var command = new CreatePaymentCommand(_incentive.Id, _incentive.PendingPayments.First().Id,
                                                   _firstCollectionPeriod.AcademicYear, _firstCollectionPeriod.PeriodNumber);

            _mockIncentiveDomainRespository.Setup(x => x.Find(command.ApprenticeshipIncentiveId)).ReturnsAsync(_incentive);

            // Act
            await _sut.Handle(command);

            // Assert
            _incentive.Payments.Count.Should().Be(1);
        }
예제 #19
0
        public async Task <IActionResult> Index(BookViewModel bookViewModel)
        {
            if (ModelState.IsValid)
            {
                string paxId = HttpContext.Session.GetString(SessionDataKeys.PaxId);

                //Calculate Product Price
                ProductPriceDTO productPrice = await getProductPricing(bookViewModel.ProductId, bookViewModel.CheckInDate, bookViewModel.CheckInTime);

                bookViewModel.CalculateFinalPrice(productPrice);

                //Create Booking
                CreateBookingCommand createBookingCommand = new CreateBookingCommand
                {
                    Name = bookViewModel.ProductName
                };
                CreateBookingCommandItem bookingItem = new CreateBookingCommandItem()
                {
                    ProductId   = bookViewModel.ProductId,
                    DateCheckIn = bookViewModel.CheckInDate.ToJsonDateTime(bookViewModel.CheckInTime),
                };
                bookingItem.PaxId.Add(paxId);
                createBookingCommand.BookingProducts.Add(bookingItem);
                BookingProductDTO bookingProductDTO = await _heroService.BookingApi.CreateBookingAsync(createBookingCommand);

                //Validate Booking
                BookingValidationResultDTO bookResult = await _heroService.BookingApi.ValidateBookingAsync(bookingProductDTO.Id);

                if (bookResult.IsValid)
                {
                    //Create the payment
                    CreatePaymentCommand createPaymentCommand = new CreatePaymentCommand()
                    {
                        Amount    = bookViewModel.FinalPrice,
                        BookingId = bookingProductDTO.Id,
                        IsFinal   = true,
                        Method    = PaymentMethod.Cash,
                        PaxId     = paxId
                    };
                    await _heroService.PaymentApi.CreatePaymentAsync(createPaymentCommand);

                    return(RedirectToAction("Index", "Voucher", new { bookingId = bookingProductDTO.Id, paxId }));
                }
                else
                {
                    this.ModelState.AddModelError("BookValidation", "Book validation failed please retry");
                }
            }
            return(View(bookViewModel));
        }
        public async Task ShouldDeletePayment()
        {
            var command = new CreatePaymentCommand
            {
                Name = "Do yet another thing for delete."
            };

            var paymentId = await SendAsync(command);

            await SendAsync(new DeletePaymentCommand { Id = paymentId });

            var payment = await FindAsync <Payment>(paymentId);

            payment.Should().BeNull();
        }
예제 #21
0
        public async Task <Guid> GeneratePayment(HttpClient client)
        {
            var command = new CreatePaymentCommand()
            {
                Amount   = 10,
                Currency = "EUR",
                OrderID  = Guid.NewGuid().ToString()
            };

            var createPaymentResponse = await client.PostAsync($"/api/create-payment", Utils.GetRequestContent(command));

            var createdPayment = await Utils.GetResponseContent <CreatePaymentResultWm>(createPaymentResponse);

            return(createdPayment.OrderID);
        }
예제 #22
0
        public async Task create_payment_returns_created()
        {
            var command = new CreatePaymentCommand {
                Amount = 5, Date = new DateTime(2020, 3, 1)
            };
            var content = new StringContent(JsonConvert.SerializeObject(command), Encoding.UTF8, "application/json");

            var httpResponse = await _client.PostAsync($"{PaymentsUrlBase}/payments", content);

            httpResponse.EnsureSuccessStatusCode();

            Assert.Equal(HttpStatusCode.Created, httpResponse.StatusCode);

            //httpResponse.Headers.Location.Query.Replace("?id=", "")
        }
예제 #23
0
        public async Task GivenCreatePaymentCommand_ReturnsSuccessCode()
        {
            var client  = _factory.CreateClient();
            var command = new CreatePaymentCommand
            {
                Date   = DateTime.Now,
                Amount = 300
            };

            var content = Helper.GetRequestContent(command);

            var response = await client.PostAsync("/payment/create", content);

            response.EnsureSuccessStatusCode();
        }
예제 #24
0
        public async Task GivenDuplicateCreatePaymentCommand_ReturnsBadRequest()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            var command = new CreatePaymentCommand
            {
                Name = "Do this thing."
            };

            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PostAsync(_paymentBaseUri, content);

            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
예제 #25
0
        public async Task GivenInvalidCreatePaymentCommand_ReturnsBadRequest()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            var command = new CreatePaymentCommand
            {
                Name = "This description of this thing will exceed the maximum length. This description of this thing will exceed the maximum length. This description of this thing will exceed the maximum length. This description of this thing will exceed the maximum length."
            };

            var content = IntegrationTestHelper.GetRequestContent(command);

            var response = await client.PostAsync(_paymentBaseUri, content);

            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);
        }
예제 #26
0
        public async Task <IActionResult> ProcessPayment(CreatePaymentDto createPaymentDto)
        {
            var createpaymentcommand = new CreatePaymentCommand {
                Amount           = createPaymentDto.Amount,
                CardHolder       = createPaymentDto.CardHolder,
                CreditCardNumber = createPaymentDto.CreditCardNumber,
                ExpirationMonth  = createPaymentDto.ExpirationMonth,
                ExpirationYear   = createPaymentDto.ExpirationYear,
                SecurityCode     = createPaymentDto.SecurityCode
            };


            var response = await _mediator.Send(createpaymentcommand);

            return(Ok(response));
        }
예제 #27
0
        private CreatePaymentCommand CreatePaymentCommand(Order order)
        {
            var description    = "支付订单 " + order.OrderId;
            var paymentCommand = new CreatePaymentCommand
            {
                AggregateRootId = GuidUtil.NewSequentialId(),
                OrderId         = order.OrderId,
                Description     = description,
                TotalAmount     = order.Total,
                Lines           = order.Lines.Select(x => new PaymentLine {
                    Id = x.SpecificationId, Description = x.SpecificationName, Amount = x.LineTotal
                })
            };

            return(paymentCommand);
        }
예제 #28
0
        public async Task <ActionResult <bool> > CreateWalletAsync([FromBody] CreatePaymentCommand createPaymentCommand)
        {
            _logger.LogInformation(
                "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})",
                createPaymentCommand.GetGenericTypeName(),
                nameof(createPaymentCommand.UserId),
                createPaymentCommand.UserId,
                createPaymentCommand);

            var result = await Mediator.Send(createPaymentCommand);

            if (result)
            {
                return(Ok());
            }
            return(StatusCode(500, new { error = "Deposit can't be created." }));
        }
예제 #29
0
        public void Handle_GivenMoreThanBalanceAmount_ShouldCreateClosedPayment()
        {
            var sut     = new CreatePaymentCommandHandler(_context, _mediator.Object, CurrentUser);
            var request = new CreatePaymentCommand
            {
                Amount = 100000,
                Date   = DateTime.Now
            };

            var result = sut.Handle(request, CancellationToken.None).Result;

            Assert.AreNotEqual(Guid.Empty, result);
            var record = _context.Payments.SingleOrDefault(i => i.Id == result);

            Assert.IsNotNull(record);
            Assert.AreEqual(PaymentStatus.Closed, record.Status);
        }
예제 #30
0
        public async Task process_payment_returns_ok()
        {
            // add payment
            var command = new CreatePaymentCommand {
                Amount = 5, Date = new DateTime(2020, 3, 1)
            };
            var content      = new StringContent(JsonConvert.SerializeObject(command), Encoding.UTF8, "application/json");
            var httpResponse = await _client.PostAsync($"{PaymentsUrlBase}/payments", content);

            var id = GetIdFromLocationHeader(httpResponse);

            var cancelResponse = await _client.PostAsync($"{PaymentsUrlBase}/payments/{id}/process", null);

            cancelResponse.EnsureSuccessStatusCode();

            Assert.Equal(HttpStatusCode.OK, cancelResponse.StatusCode);
        }