Пример #1
0
        private void commandToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateOutput("A account is created, transaction commands are queued up then committed, the results are displayed.");

            BankAccount       bankAccount = new BankAccount();
            TransactionsQueue queue       = new TransactionsQueue();

            CommandAbstract command;

            UpdateOutput("Beginning account balance: " + bankAccount.Balance.ToString());

            command = new DepositCommand(bankAccount, 50);
            queue.AddTransaction(command);
            UpdateOutput("Depositing 50");

            command = new DepositCommand(bankAccount, 20);
            queue.AddTransaction(command);
            UpdateOutput("Depositing 20");

            command = new WithdrawCommand(bankAccount, 10);
            queue.AddTransaction(command);
            UpdateOutput("Withdrawing 10");

            UpdateOutput("Before committing account balance: " + bankAccount.Balance.ToString());
            queue.CommitTransactions();

            UpdateOutput("Final account balance: " + bankAccount.Balance.ToString());
        }
Пример #2
0
        public void DepositCommandCreateTest()
        {
            DepositCommand command = new DepositCommand(null, 0);

            Assert.IsInstanceOfType(command, typeof(DepositCommand));
            Assert.IsInstanceOfType(command, typeof(CommandAbstract));
        }
Пример #3
0
        public async Task <IActionResult> Deposit(
            [FromBody] DepositRequest request,
            CancellationToken token)
        {
            var query = new DepositCommand(
                request.AccountNumber,
                request.Amount,
                CorrelationContext.Get());
            var response = await _mediator
                           .Send(
                query,
                token);

            if (!response
                .ValidationResult
                .IsValid)
            {
                var errors = string.Empty;
                response
                .ValidationResult
                .Errors
                .ToList()
                .ForEach(e => { errors += $"{e}//r//n"; });
                return(BadRequest(errors));
            }

            return(Ok(new DepositView(
                          response.Balance)));
        }
Пример #4
0
        public IActionResult Deposit(DepositViewModel model)
        {
            if (ModelState.IsValid)
            {
                var command = new DepositCommand()
                {
                    AccountId = model.AccountId,
                    Amount    = model.Amount
                };

                var query = new DepositHandler().Handler(command);
                if (query.IsCompletedSuccessfully)
                {
                    TempData["Success"] = $"{model.Amount.ToString("C")} deposited to account";
                    return(View());
                }
                else
                {
                    TempData["Error"] = $"Deposit failed";
                    return(View());
                }
            }
            else
            {
                return(NotFound());
            }
        }
Пример #5
0
        public async void Deposit_Valid_Amount(string pin, string name, string accountId, double amount)
        {
            var account  = Substitute.For <Account>();
            var customer = Substitute.For <Customer>();

            customer.FindAccount(Arg.Any <Guid>())
            .Returns(account);

            customerReadOnlyRepository
            .GetByAccount(Guid.Parse(accountId))
            .Returns(customer);

            var depositUseCase = new DepositService(
                customerReadOnlyRepository,
                customerWriteOnlyRepository,
                converter
                );

            var request = new DepositCommand(
                Guid.Parse(accountId),
                amount
                );

            DepositResult result = await depositUseCase.Handle(request);

            Assert.Equal(request.Amount, result.Transaction.Amount);
        }
Пример #6
0
 public async Task <IActionResult> Deposit(
     [FromBody] DepositCommand command,
     CancellationToken cancellationToken = default)
 {
     cancellationToken.ThrowIfCancellationRequested();
     return(Ok(await _mediator.Send(command, cancellationToken)));
 }
Пример #7
0
        static void Main(string[] args)
        {
            //Receiver receiver = new Receiver();
            //Command command = new ConcreteCommand(receiver);
            //Invoker invoker = new Invoker();
            //invoker.SetCommand(command);
            //invoker.ExecuteCommand();


            Account account = new Account();

            var commandDepoist = new DepositCommand(account, 5000);

            var invoker = new Bank.Invoker();

            invoker.SetCommand(commandDepoist);
            invoker.ExecuteCommand();

            Console.WriteLine("The current amount of account is:{0}", account.TotalAmount);

            var commandWithdrawal = new WithdrawalCommand(account, 2000);

            invoker.SetCommand(commandWithdrawal);
            invoker.ExecuteCommand();

            Console.WriteLine("The current amount of account is:{0}", account.TotalAmount);

            Console.Read();
        }
Пример #8
0
        public async Task <IActionResult> Deposit([FromBody] DepositRequest message)
        {
            var request = new DepositCommand(message.AccountId, message.Amount);

            await depositInput.Handle(request);

            return(depositPresenter.ViewModel);
        }
Пример #9
0
        public void DepositCommandExecuteTest()
        {
            BankAccount    bankAccount = new BankAccount();
            DepositCommand command     = new DepositCommand(bankAccount, 10);

            command.Execute();
            Assert.AreEqual(bankAccount.Balance, 10);
        }
Пример #10
0
 //-- Calls the Invoker method Deposit() that calls the ConcreteCommand Deposit
 public void DoDeposit()
 {
     Console.Write("How much is being deposited?\n$");
     _deposit = new DepositCommand(_account, GetValue(), _transactionCount);
     _invoker.DepositCommand = _deposit;
     _invoker.Deposit();
     _transactionCount = _invoker.TransactionHistory.Count + 1;
 }
Пример #11
0
        public async Task <IActionResult> Deposit([FromBody] DepositCommand command)
        {
            var result = await _mediator.Send(command);

            return(result.Success
                ? Ok()
                : BadRequest(result.Error));
        }
Пример #12
0
        private void Deposit(DepositCommand depositCommand)
        {
            if (!_managedAccounts.TryGetValue(depositCommand.TransactionToAccountId, out var account))
            {
                account = Context.ActorOf(_system.DI().Props <CustomerActor>(), depositCommand.TransactionToAccountId.ToString());
            }

            account.Tell(depositCommand);
        }
Пример #13
0
        public async Task Should_be_possible_to_deposit_amount_on_account()
        {
            var command = new DepositCommand {
                AccountNo = 4, Amount = 100
            };
            var content  = new StringContent(command.AsJson(), Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync("api/account/deposit", content);

            response.StatusCode.Should().Be(HttpStatusCode.OK);
        }
Пример #14
0
        string BuildDepositCommand()
        {
            var order = new DepositCommand()
            {
                AccountId     = "test1",
                DepositAmount = 1000
            };

            return(JsonConvert.SerializeObject(order));
        }
Пример #15
0
        public Task <Result <Account> > Handle(DepositCommand request, CancellationToken cancellationToken)
        {
            var account = this._context.Accounts.Find(request.AccountNo);

            if (account is Account)
            {
                var result = account.Deposit(request.Amount);
                return(Task.FromResult(Result.From(account, result)));
            }
            return(Task.FromResult(Result.Fail <Account>($"Conta #{request.AccountNo} não encontrada")));
        }
Пример #16
0
        public async Task <IActionResult> Deposit([FromBody] DepositCommand command)
        {
            await Mediator.Send(command);

            var query = new InquiryByAccountNumberQuery()
            {
                AccountNumber = command.AccountNumber
            };

            return(Ok(await Mediator.Send(query)));
        }
Пример #17
0
        public async Task <IActionResult> Deposit(Guid accountId, [FromBody] DepositModel model, CancellationToken token)
        {
            var command = new DepositCommand {
                AccountId = accountId,
                Amount    = model.Amount,
            };

            var response = await mediator.Send(command, token);

            return(Ok(response));
        }
Пример #18
0
        public async Task <IActionResult> Deposit([FromRoute] int accountNumber, [FromBody] AccountOperationRequest request)
        {
            var depositCommand = new DepositCommand
            {
                AccountNumber = accountNumber,
                Amount        = request.OperationAmount,
                Tags          = request.Tags
            };
            await _mediator.Send(depositCommand).ConfigureAwait(false);

            return(Ok());
        }
        public WhenDepositingMoney()
        {
            _accountAuthorisationMock = new Mock <IAccountAuthorisation>();

            var container = Bootstrapper.BootstrapContainerAndAdapters(c =>
            {
                c.RegisterInstance(_accountAuthorisationMock.Object);
            });

            _command          = container.GetInstance <DepositCommand>();
            _bankAccountStore = container.GetInstance <IBankAccountStore>();
        }
        public void Deposit_GivenUnSupportCurrency_ShouldThrowBusinessErrorException()
        {
            var command = new DepositCommand()
            {
                AccountNumber = "1", Amount = 3, Currency = "VND"
            };

            var result = Assert.ThrowsAsync <DepositFailException>(() => handler.Handle(command, CancellationToken.None));

            result.ShouldNotBeNull();
            result.Message.Contains("Invalid Currency VND.");
        }
        public void Deposit_GivenNegativeExchangedAmount_ShouldThrowBusinessErrorException()
        {
            var command = new DepositCommand()
            {
                AccountNumber = "1", Amount = -3, Currency = "EUR"
            };

            var result = Assert.ThrowsAsync <DepositFailException>(() => handler.Handle(command, CancellationToken.None));

            result.ShouldNotBeNull();
            result.Message.Contains($"Invalid actual amount {command.Amount * 40}");
        }
Пример #22
0
        /// <summary>
        /// The Command Handler.
        /// This Allows interleaving of processing because multiple deposits can happen concurrently
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        public async Task Deposit(DepositCommand command)
        {
            if (this.IsClosed())
            {
                throw new UnableToDepositToClosedAccountException();
            }

            await this.ConcurrentWriteAsync(new DepositedEvent(command.Amount)
            {
                RelationEvent = Guid.NewGuid().ToString("D")
            }, MQ.MQPublishType.Asynchronous);
        }
Пример #23
0
        private async Task DepositAsync(DepositCommand depositCommand)
        {
            IActorRef account;

            if (!_cachedAccounts.ContainsKey(depositCommand.TransactionToAccountId))
            {
                account = await Context.ActorSelection($"../*/*/{depositCommand.TransactionToAccountId}").ResolveOne(TimeSpan.FromSeconds(10));
            }
            else
            {
                account = _cachedAccounts[depositCommand.TransactionToAccountId];
            }

            account?.Tell(depositCommand);
        }
        public async Task <IActionResult> Deposit([FromBody] DepositCommand command)
        {
            DepositResult depositResult = await _depositCommandHandler.Execute(command);

            if (depositResult == null)
            {
                return(new NoContentResult());
            }
            Model model = new Model(
                depositResult.Transaction.Amount,
                depositResult.Transaction.Description,
                depositResult.Transaction.TransactionDate,
                depositResult.UpdatedBalance);

            return(new ObjectResult(model));
        }
Пример #25
0
        private void InitializeFields()
        {
            _transactionCount = 1;

            _account = new SavingsAccount
            {
                Balance = 500.00m,
                //InterestPercentage = 0.0215m
            };

            //_interest = new CalculateInterest(_account, _transactionCount);
            _balance  = new GetBalanceCommand(_account, _transactionCount);
            _deposit  = new DepositCommand(_account, 0m, _transactionCount);
            _withdraw = new WithdrawCommand(_account, 0m, _transactionCount);
            _revert   = new RevertTransaction(_account, 0m, _transactionCount, 0);

            _invoker = new AccountInvoker(_balance, _deposit, _withdraw, _revert);
        }
Пример #26
0
        // TODO: In the future use correlation id
        public async Task Execute(TransactionCommand command)
        {
            var currentEvents  = (await bankTransactionEventStore.ReadAll(command.AccountId)).ToArray();
            var currentVersion = currentEvents.Length;
            var balance        = BalanceReport.GetBalance(currentEvents);

            TransactionEvent evt = command switch
            {
                DepositCommand deposit =>
                new Deposit(deposit.Amount, deposit.AccountId, DateTimeOffset.Now, deposit.CorrelationId),
                WithdrawalCommand withdrawal when balance >= withdrawal.Amount =>
                new Withdrawal(withdrawal.Amount, withdrawal.AccountId, DateTimeOffset.Now, withdrawal.CorrelationId),
                _ =>
                throw new ArgumentException()
            };

            await bankTransactionEventStore.Append(currentVersion, evt);
        }
    }
        public async Task Deposit_GivenCorrectRequest_WithSameCurrency_ShouldDepositSuccessfulWithCorrectAmount()
        {
            DepositCommand command = new DepositCommand()
            {
                AccountNumber = "1", Amount = 30, Currency = "THB"
            };
            await handler.Handle(command, CancellationToken.None);

            var depositAccount = context.BankAccounts.First(a => a.AccountNumber == command.AccountNumber);

            var currentBalance      = _accountRepository.GetCurrentBalanceByAccountId(depositAccount);
            var withdrawTransaction = context.Transactions.FirstOrDefault(a => a.AccountId == depositAccount.Id &&
                                                                          a.TransactionDatetime == dateTime.Now &&
                                                                          a.Action == ActionCode.Deposit);


            currentBalance.ShouldBe(130);
            withdrawTransaction.ShouldNotBeNull();
            withdrawTransaction.Amount.ShouldBe(30);
            depositAccount.LastActivityDate.ShouldBe(dateTime.Now);
        }
Пример #28
0
        public void Setup()
        {
            var fixture = new Fixture();

            _depositCommand = fixture.Build <DepositCommand>()
                              .FromFactory(() => new DepositCommand(1, CurrencySettings.DefaultCurrencyKey))
                              .Create();

            _depositCommandWithZeroMoney = fixture.Build <DepositCommand>()
                                           .FromFactory(() => new DepositCommand(0, CurrencySettings.DefaultCurrencyKey))
                                           .Create();

            _currencies = fixture.Build <Currency>()
                          //.FromFactory(() => new Currency("PHP", 1,"en-PH"))
                          .CreateMany(5);

            _wallets = fixture.Build <Wallet>()
                       .CreateMany(1);

            _target = new DepositCommandHandler(_walletRepositoryMock.Object, _currencyRepositoryMock.Object, _authenticationServiceMock.Object);
        }
Пример #29
0
        private async Task Handle(DepositCommand c, IEventPublisher publisher)
        {
            await _executionInfoRepository.GetOrAddAsync(
                OperationName,
                c.OperationId,
                () => new OperationExecutionInfo <WithdrawalDepositData>(
                    OperationName,
                    c.OperationId,
                    new WithdrawalDepositData
            {
                AccountId = c.AccountId,
                Amount = c.Amount,
                AuditLog = c.AuditLog,
                State = WithdrawalState.Created,
                Comment = c.Comment
            },
                    _systemClock.UtcNow.UtcDateTime));

            _chaosKitty.Meow(c.OperationId);

            publisher.PublishEvent(new DepositStartedInternalEvent(c.OperationId, _systemClock.UtcNow.UtcDateTime));
        }
Пример #30
0
        public async Task <IActionResult> Deposit([FromBody] DepositRequest request)
        {
            var command = new DepositCommand(
                request.AccountId,
                request.Amount);

            DepositResult depositResult = await depositService.Process(command);

            if (depositResult == null)
            {
                return(new NoContentResult());
            }

            Model model = new Model(
                depositResult.Transaction.Amount,
                depositResult.Transaction.Description,
                depositResult.Transaction.TransactionDate,
                depositResult.UpdatedBalance
                );

            return(new ObjectResult(model));
        }