Esempio n. 1
0
        public async Task Handle(CreatePaymentNotification notification, CancellationToken cancellationToken)
        {
            CustomerPayment customerPayment = new(notification.BasketCode, notification.Price, notification.PaidPrice, notification.CustomerCode,
                                                  notification.BasketItems, notification.ShippingAddress, notification.ShippingAddress, notification.SellerCode);

            await _paymentRepository.AddAsync(customerPayment, cancellationToken);
        }
Esempio n. 2
0
        public async Task ProcessPayment_ReturnsPayment()
        {
            //Arrange
            var request = new ProcessPaymentRequest
            {
                Amount     = 100,
                Currency   = "EUR",
                FullName   = "Dmitriy Purtseladze",
                CardNumber = "5555-5555-5555-5555",
                Cvv        = 123,
                Expiry     = "08/22"
            };

            _bankService.ProcessPaymentAsync(request).Returns(new BankServiceResponse
            {
                IsSuccessHttpStatusCode = true,
                HttpMessage             = "success",
                HttpStatusCode          = HttpStatusCode.OK,
                PaymentStatus           = "success",
                PaymentId = Guid.NewGuid().ToString()
            });
            const string encryptedCardNumber = "encrypted-card-number";
            const string decryptedCardNumber = "5555-5555-5555-5555";

            _aesHelper.Encrypt(decryptedCardNumber).Returns(encryptedCardNumber);

            var maskedCardNumber = "xxxx-xxxx-xxxx-5555";

            _creditCardMasker.MaskCreditCardNumber(Arg.Any <string>()).Returns(maskedCardNumber);

            var payment = new Payment
            {
                Id         = Guid.NewGuid(),
                Amount     = request.Amount,
                Currency   = request.Currency,
                FullName   = request.FullName,
                CardNumber = encryptedCardNumber,
                Expiry     = request.Expiry
            };

            _paymentRepository.AddAsync(Arg.Any <Payment>()).Returns(payment);

            var cmd = new ProcessPaymentCommand(request);

            //Act
            var response = await _subject.Handle(cmd);

            //Assert
            Assert.NotNull(response);
            Assert.NotEqual(Guid.Empty, response.Id);
            Assert.Equal(request.FullName, response.FullName);
            Assert.Equal(request.Amount, response.Amount);
            Assert.Equal(request.Currency, response.Currency);
            Assert.Equal(maskedCardNumber, response.CardNumber);
            Assert.Equal(request.Expiry, response.Expiry);

            await _bankService.Received().ProcessPaymentAsync(request);

            await _paymentRepository.Received().AddAsync(Arg.Any <Payment>());
        }
Esempio n. 3
0
        public async Task HandleAsync(PayOrder command)
        {
            if (command == null)
            {
                throw new ServiceException(ErrorCodes.PustyRequest, "Post request add/payment is empty");
            }

            var order = await _orderRepository.GetAsync(command.Order.OrderID);

            if (order == null)
            {
                throw new ServiceException(ErrorCodes.Nieznaleziono, $"Nie znaleziono zlecenia w bazie danych");
            }

            foreach (var teamID in command.Order.Teams)
            {
                var team = await _teamRepository.GetAsync(teamID.TeamID);

                if (team == null)
                {
                    throw new ServiceException(ErrorCodes.Nieznaleziono, $"Nie znaleziono zespołu w bazie danych");
                }

                var workers = (await _context.WorkerTeam.ToListAsync()).Where(x => x.TeamID == team.TeamID).ToList();

                if (!workers.Any())
                {
                    throw new ServiceException(ErrorCodes.Nieznaleziono, $"Nie znaleziono pracowników w bazie danych");
                }

                foreach (var ele in workers)
                {
                    var worker = await _workerRepository.GetAsync(ele.WorkerID);

                    var days = DaysWithoutWeekends.Count(order.StartDate, (DateTime)order.EndDate);

                    var payment = new Payment
                    {
                        OrderID     = command.Order.OrderID,
                        WorkerID    = worker.WorkerID,
                        Amount      = worker.ManHour * 8 * days,
                        PaymentDate = DateTime.UtcNow,
                        PaymentID   = Guid.NewGuid()
                    };

                    await _paymentRepository.AddAsync(payment);
                }
            }

            order.Paid = true;
            await _orderRepository.UpdateAsync(order);
        }
        public async Task <long> Handle(CreatePaymentCommand request, CancellationToken cancellationToken)
        {
            var entity = new Payment
            {
                Name       = request.Name,
                IsComplete = false
            };


            entity.DomainEvents.Add(new PaymentCreatedEvent(entity));
            await _repository.AddAsync(entity, cancellationToken);

            return(entity.Id);
        }
        private async Task MeasureAndKeepResultAsync(IReadOnlyCollection <Payment> payments)
        {
            var stopwatch = new Stopwatch();

            stopwatch.Start();

            await _objectUnderMeasurement.AddAsync(payments);

            stopwatch.Stop();

            await _objectUnderMeasurement.ClearAsync();

            KeepResult(payments.Count, stopwatch.Elapsed);
        }
Esempio n. 6
0
        public async Task <bool> Handle(CreatePaymentCommand request, CancellationToken cancellationToken)
        {
            // TODO: Use Distributed Transaction Like CAP, Saga, ...

            var paymentCreatedEvent = _mapper.Map <PaymentCreatedEvent>(request);
            var data = _mapper.Map <Domain.PaymentEntity>(paymentCreatedEvent);

            data.Id = await _paymentRepository.AddAsync(data, CancellationToken.None);

            paymentCreatedEvent.PaymentId = data.Id;

            await _eventSourceRepository.InsertEventAsync(paymentCreatedEvent, cancellationToken);

            _eventBus.Publish(paymentCreatedEvent);

            return(true);
        }
Esempio n. 7
0
        /// <summary>
        /// save changes
        /// </summary>
        public async Task <PaymentModel> Create(PaymentModel model)
        {
            // try to add the payment model
            await _repository.AddAsync(model);

            await _repository.SaveChangesAsync();

            // try to add the payment model
            var result = _repository.GetByCreditCardAsync(model.CreditCardNumber);

            if (result != null)
            {
                return(model);
            }
            // Throw the custom exception if unable to save the payment
            throw new PaymentException("Unable to Save the Payment");
        }
Esempio n. 8
0
        public async Task <Payment> AddPaymentAsync(CreateNewPayment newPaymentData)
        {
            newPaymentData.Validate();

            var payer = await userRepository.GetByIdAsync(newPaymentData.PayerId);

            if (payer == null)
            {
                throw new NotFoundException("User with given id does not exist.");
            }

            var receiver = await userRepository.GetByIdAsync(newPaymentData.ReceiverId);

            if (receiver == null)
            {
                throw new NotFoundException("User with given id does not exist.");
            }

            var expectedPayments = await GetExpectedPaymentsBetweenUsers(
                userA : payer,
                userB : receiver,
                groupContextId : newPaymentData.GroupContextId
                );

            if (expectedPayments.Count < 1)
            {
                throw new BadRequestException("No payment expected.");
            }

            var expectedPayment = expectedPayments.Single();

            if (payer.Id != expectedPayment.PayerId || receiver.Id != expectedPayment.ReceiverId)
            {
                throw new BadRequestException($"User {receiver.Email} already owes you money.");
            }

            if (newPaymentData.Amount > expectedPayment.Amount)
            {
                throw new BadRequestException("Trying to pay back more than owned.");
            }

            var paymentToAdd = newPaymentData.ToPayment();

            return(await paymentRepository.AddAsync(paymentToAdd));
        }
Esempio n. 9
0
        public async Task <PaymentResponse> Handle(ProcessPaymentCommand command,
                                                   CancellationToken cancellationToken = default)
        {
            var bankResponse = await _bankService.ProcessPaymentAsync(command.Request);

            var paymentToSave = _converter.Map <Payment>(command.Request);

            paymentToSave.CardNumber        = _aesHelper.Encrypt(paymentToSave.CardNumber);
            paymentToSave.BankPaymentStatus = bankResponse.PaymentStatus;
            paymentToSave.BankPaymentId     = bankResponse.PaymentId;

            var payment = await _paymentRepository.AddAsync(paymentToSave);

            var paymentResponse = _converter.Map <PaymentResponse>(payment);

            paymentResponse.CardNumber = _creditCardMasker.MaskCreditCardNumber(command.Request.CardNumber);
            return(paymentResponse);
        }
        public async Task <string> AddAsync(Payments payment)
        {
            var resultFromPayment = _gateway.PaymentProcess(payment);

            payment.PaymentStatus = PaymetStatus.Completed;

            var paymentRef = await _context.AddAsync(payment);

            //Publish the event here
            //Create Integration Event
            var paymentProcessedEvent = new PaymentProcessedIntegrationEvent(paymentRef.PaymentsId,
                                                                             paymentRef.BookingOrderId,
                                                                             paymentRef.CustomerId, (int)payment.PaymentStatus);

            _eventBus.Publish(paymentProcessedEvent);

            return(paymentRef.PaymentsId);
        }
Esempio n. 11
0
        public async Task <OrderModel> AddAsync(List <OrderItemModel> items, Guid id)
        {
            var user = await _userService.GetAsync(id);

            double totalCost = items.Sum(x => x.Count * x.PrintingEdition.Price);

            if (totalCost <= default(int))
            {
                throw new ServerException(HttpStatusCode.BadRequest,
                                          ExceptionMessage.INVALID_DATA);
            }

            var payment = new Payment()
            {
                TransactionId = string.Empty
            };

            var order = new OrderModel
            {
                UserId       = user.Id,
                CreationDate = DateTime.Now,
                TotalCost    = totalCost,
                Status       = Enums.OrderStatusType.Unpaid,
                PaymentId    = payment.Id,
                Description  = string.Empty
            };

            foreach (var item in items)
            {
                item.OrderId = order.Id;
            }

            order.Items = items;

            var mapped = _mapper.Map <Order>(order);

            await _paymentRepository.AddAsync(payment);

            await _orderRepository.AddAsync(mapped);

            return(order);
        }
Esempio n. 12
0
        public override async Task <string> Execute(ConsumeContext <MakePayment> context)
        {
            var command = context.Message;

            var response = await _processor.ProcessAsync(
                command.Currency,
                command.Amount,
                command.CardNumber,
                command.ExpiryMonth,
                command.ExpiryYear,
                command.Cvv,
                command.CardHolderName);

            // We assume command sent through the bus are ALWAYS valid. In other words, the code below should never fail.
            var payment = Payment.Create(
                response.PaymentId,
                command.MerchantId,
                Card.Create(
                    CardNumber.Create(command.CardNumber).GetValue(),
                    ExpiryDate.Create(command.ExpiryMonth, command.ExpiryYear).GetValue(),
                    Cvv.Create(command.Cvv).GetValue(),
                    command.CardHolderName).GetValue(),
                Price.Create(command.Currency, command.Amount).GetValue(),
                command.Description);

            // This is simplistic :)
            if (response.Status == PaymentStatus.Approved)
            {
                payment.Approve();
            }
            else
            {
                payment.Decline("Payment was declined");
            }

            // Persist the payment
            await _repository.AddAsync(payment);

            // We return the Id of the created entity!
            return(response.PaymentId);
        }
        public async Task <PaymentModel> Create(PaymentModel model)
        {
            int  retry = 3;
            bool isFailed;

            do
            {
                try
                {
                    // try to add the payment model
                    await _repository.AddAsync(model);

                    await _repository.SaveChangesAsync();

                    // try to add the payment model
                    var result = _repository.GetByCreditCardAsync(model.CreditCardNumber);
                    if (result != null)
                    {
                        return(model);
                    }
                    // Throw the custom exception if unable to save the payment
                    throw new PaymentException("Unable to Save the Payment");
                }
                catch (PaymentException)
                {
                    retry   -= 1;
                    isFailed = true;
                }
                catch (Exception)
                {
                    retry   -= 1;
                    isFailed = true;
                }
            } while (retry != 0);

            if (isFailed)
            {
                throw new PaymentException("Unable to Save the Payment");
            }
            return(model);
        }
Esempio n. 14
0
        public async Task <PaymentResponse> SaveAsync(Payment payment, int userCommontId)
        {
            var existingUser = await _userCommonRepository.FindById(userCommontId);

            if (existingUser == null)
            {
                return(new PaymentResponse("User not found"));
            }
            payment.UserCommon = existingUser;
            try
            {
                await _paymentRepository.AddAsync(payment);

                await _unitOfWork.CompleteAsync();

                return(new PaymentResponse(payment));
            }
            catch (Exception ex)
            {
                return(new PaymentResponse($"An error ocurred while saving the payment: {ex.Message}"));
            }
        }
Esempio n. 15
0
        public async Task <Payment> AddPayment(PaymentDto payment)
        {
            try
            {
                var paymentEntity = _mapper.Map <PaymentDto, Payment>(payment);
                paymentEntity = _paymentRepository.AddAsync(paymentEntity).Result;
                PaymentState paymentStateData = new PaymentState()
                {
                    Payment = paymentEntity, PaymentId = paymentEntity.PaymentId, CreatedDate = DateTime.Now, State = PaymentStateEnum.Pending.ToString()
                };
                var paymentState = await _paymentStateRepository.AddAsync(paymentStateData);

                _UOW.Complete();

                _paymentGateway.PaymentProcess(payment, paymentState);
                return(paymentEntity);
            }
            catch (Exception)
            {
                throw new Exception("This payment can not be processed");
            }
        }
Esempio n. 16
0
        public async Task <string> AddAsync(PaymentDTO payment)
        {
            var resultFromPayment = _gateway.PaymentProcess(payment);

            var paymentEntity = new Payments
            {
                BookingOrderId = payment.BookingOrderId,
                CustomerId     = payment.CustomerId,
                Price          = payment.Price,
                PaymentStatus  = PaymetStatus.Completed //This part is based on the result returned from external gateway
            };

            var paymentRef = await _context.AddAsync(paymentEntity);

            //Publish the event here
            //Create Integration Event
            var paymentProcessedEvent = new PaymentProcessedIntegrationEvent(paymentRef.PaymentsId,
                                                                             paymentRef.BookingOrderId,
                                                                             paymentRef.CustomerId, (int)paymentEntity.PaymentStatus);

            _eventBus.Publish(paymentProcessedEvent);

            return(paymentRef.PaymentsId);
        }
Esempio n. 17
0
        public async Task Handle(OrderPlacedEvent notification, CancellationToken cancellationToken)
        {
            Payment newPayment = new Payment(notification.OrderId);

            await _paymentRepository.AddAsync(newPayment);
        }
Esempio n. 18
0
        //Basic

        public async Task <int> AddAsync(PaymentEntity paymentEntity)
        {
            return(await _paymentRepository.AddAsync(paymentEntity));
        }
        public async Task <Result> Handle(RegisterPayment request, CancellationToken cancellationToken)
        {
            var payment = Payment.Register(request.Id, request.SourceId, request.CategoryId, request.DateTime, request.Amount);

            return(await paymentRepository.AddAsync(payment, cancellationToken));
        }