public IActionResult Withdraw(WithdrawViewModel model) { if (ModelState.IsValid) { var command = new WithdrawCommand { AccountId = model.AccountId, Amount = model.Amount, }; var query = new WithdrawHandler(new BankContext()).Handler(command); if (query.IsCompletedSuccessfully) { TempData["Success"] = $"{model.Amount.ToString("C")} withdrawn from account"; return(View()); } else { TempData["Error"] = $"Withdraw failed"; return(View()); } } return(View()); }
public async Task <IActionResult> Withdraw( [FromBody] WithdrawCommand command, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); return(Ok(await _mediator.Send(command, cancellationToken))); }
public void Setup() { var fixture = new Fixture(); _withdrawCommand = fixture.Build <WithdrawCommand>() .FromFactory(() => new WithdrawCommand(1, CurrencySettings.DefaultCurrencyKey)) .Create(); _withdrawCommandWithHugeMoney = fixture.Build <WithdrawCommand>() .FromFactory(() => new WithdrawCommand(1000, CurrencySettings.DefaultCurrencyKey)) .Create(); _currencies = fixture.Build <Currency>() .FromFactory(() => new Currency("PHP", 1, "en-PH")) .CreateMany(5); _wallets = fixture.Build <Wallet>() .CreateMany(1); _walletsWithSmallBalance = fixture.Build <Wallet>() .FromFactory(() => new Wallet(1, new WalletId(Guid.NewGuid()), new Money(10), 1)) .CreateMany(1); _target = new WithdrawCommandHandler(_walletRepositoryMock.Object, _currencyRepositoryMock.Object, _authenticationServiceMock.Object); }
public void WithdrawCommandCreateTest() { WithdrawCommand command = new WithdrawCommand(null, 0); Assert.IsInstanceOfType(command, typeof(WithdrawCommand)); Assert.IsInstanceOfType(command, typeof(CommandAbstract)); }
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()); }
public void Withdraw_Overdraft() { var options = new DbContextOptionsBuilder <BankContext>() .UseInMemoryDatabase(databaseName: "NegativeAmount") .Options; using (var context = new BankContext(options)) { var account = new Account { AccountId = 2, Frequency = "Daily", Balance = 500 }; context.Accounts.Add(account); context.SaveChanges(); } using (var context = new BankContext(options)) { var command = new WithdrawCommand { AccountId = 2, Amount = 1000 }; var handler = new WithdrawHandler(context); Assert.ThrowsAsync <InsufficientFundsException>(() => handler.Handler(command)); } }
public void Setup() { _accountRepository = new Mock <IAccountRepository>(); _notificationService = new Mock <INotificationService>(); _subject = new WithdrawCommand(_accountRepository.Object, _notificationService.Object); }
public void Deposit_NegativeAmount() { var options = new DbContextOptionsBuilder <BankContext>() .UseInMemoryDatabase(databaseName: "NegativeAmount") .Options; using (var context = new BankContext(options)) { var account = new Account { AccountId = 3, Frequency = "Daily" }; context.Accounts.Add(account); context.SaveChanges(); } using (var context = new BankContext(options)) { var command = new WithdrawCommand() { AccountId = 3, Amount = -50 }; var handler = new WithdrawHandler(context); Assert.ThrowsAsync <NegativeAmountException>(() => handler.Handler(command)); } }
public async Task <IActionResult> withdraw([FromBody] WithdrawCommand command) { var response = new DepositResponse(); try { if (command.Amount < 50000 || command.Amount % 50000 != 0) { response.Code = ErrorCode.GetError(ErrorCode.AmountInvalid).Key; response.Message = ErrorCode.GetError(ErrorCode.AmountInvalid).Value; return(Ok(response)); } var walletType = _context.WalletType.Where(s => s.WalletTypeName == WalletTypeEnum.CHECKING.ToString()).FirstOrDefault(); var transactionType = _context.TransactionType.Where(s => s.TransactionTypeName == TransactionTypeEnum.WITHDRAW.ToString()).FirstOrDefault(); command.Fee = transactionType.Fee; command.TransactionTypeId = transactionType.TransactionTypeId; command.WalletTypeId = walletType.WalletTypeId; response = await _mediator.Send(command); } catch (Exception ex) { response.Code = ErrorCode.GetError(ErrorCode.SystemError).Key; response.Message = ErrorCode.GetError(ErrorCode.SystemError).Value; Logger.Error($"Exception: {ex} , Method:withdraw"); } return(Ok(response)); }
public async Task Then_the_incentive_is_not_pausePayments_when_the_incentive_has_paid_earnings() { //Arrange var incentiveModel = _fixture.Build <ApprenticeshipIncentiveModel>() .With(p => p.PendingPaymentModels, new List <PendingPaymentModel>()) .With(p => p.PaymentModels, new List <PaymentModel>()) .With(p => p.ClawbackPaymentModels, new List <ClawbackPaymentModel>()) .Create(); var pendingPaymentModel = _fixture.Build <PendingPaymentModel>() .With(p => p.ApprenticeshipIncentiveId, incentiveModel.Id) .Create(); incentiveModel.PendingPaymentModels.Add(pendingPaymentModel); var paymentModel = _fixture.Build <PaymentModel>() .With(p => p.ApprenticeshipIncentiveId, incentiveModel.Id) .With(p => p.PendingPaymentId, pendingPaymentModel.Id) .With(p => p.PaidDate, DateTime.Today.AddDays(-1)) .Create(); incentiveModel.PaymentModels.Add(paymentModel); var incentive = new ApprenticeshipIncentiveFactory().GetExisting(incentiveModel.Id, incentiveModel); var command = new WithdrawCommand(incentive.Account.Id, incentive.Id); _mockIncentiveDomainRepository.Setup(x => x.FindByApprenticeshipId(command.IncentiveApplicationApprenticeshipId)).ReturnsAsync(incentive); // Act await _sut.Handle(command); // Assert incentive.PausePayments.Should().BeFalse(); }
public async Task <IActionResult> Withdraw( [FromBody] WithdrawRequest request, CancellationToken token) { var query = new WithdrawCommand( 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 WithdrawView( response.Balance))); }
//-- Calls the Invoker method Withdraw() that calls the ConcreteCommand Withdraw public void DoWithdraw() { Console.Write("How much is being withdrawn?\n$"); _withdraw = new WithdrawCommand(_account, GetValue(), _transactionCount); _invoker.WithdrawCommand = _withdraw; _invoker.Withdraw(); _transactionCount = _invoker.TransactionHistory.Count + 1; }
public async Task <IActionResult> Withdraw([FromBody] WithdrawCommand command) { var result = await _mediator.Send(command); return(result.Success ? Ok() : BadRequest(result.Error)); }
public async Task <IActionResult> Withdraw([FromBody] WithdrawRequest message) { var request = new WithdrawCommand(message.AccountId, message.Amount); await withdrawInput.Handle(request); return(withdrawPresenter.ViewModel); }
private async Task WithdrawAsync(WithdrawCommand withdrawCommand) { var account = await Context.ActorSelection("./Customer/").ResolveOne(TimeSpan.FromSeconds(10)); if (account == null) { } }
public void WithdrawCommandExecuteTest() { BankAccount bankAccount = new BankAccount(); WithdrawCommand command = new WithdrawCommand(bankAccount, 10); command.Execute(); Assert.AreEqual(bankAccount.Balance, -10); }
private void Withdraw(WithdrawCommand withdrawCommand) { if (!_managedAccounts.TryGetValue(withdrawCommand.TransactionToAccountId, out var account)) { account = Context.ActorOf(_system.DI().Props <CustomerActor>(), withdrawCommand.TransactionToAccountId.ToString()); } account.Tell(withdrawCommand); }
public void TransactionQueueAddTest() { BankAccount bankAccount = new BankAccount(); WithdrawCommand command = new WithdrawCommand(bankAccount, 10); TransactionsQueue queue = new TransactionsQueue(); queue.AddTransaction(command); Assert.AreEqual(queue.TransactionQueueCount, 1); }
public async Task Should_withdrawn_money_succesfully() { var command = new WithdrawCommand { AccountNo = 3, Amount = 599 }; var content = new StringContent(command.AsJson(), Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("api/account/withdraw", content); response.StatusCode.Should().Be(HttpStatusCode.OK); }
public async Task Should_return_error_for_invalid_amounts(decimal amount) { var command = new WithdrawCommand { AccountNo = 3, Amount = amount }; var content = new StringContent(command.AsJson(), Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync("api/account/withdraw", content); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); }
public Task <Result <Account> > Handle(WithdrawCommand request, CancellationToken cancellationToken) { var account = this._context.Accounts.Find(request.AccountNo); if (account is Account) { var result = account.Withdraw(request.Amount); return(Task.FromResult(Result.From(account, result))); } return(Task.FromResult(Result.Fail <Account>($"Conta #{request.AccountNo} não encontrada"))); }
public async Task <IActionResult> Withdraw([FromBody] WithdrawCommand command) { await Mediator.Send(command); var query = new InquiryByAccountNumberQuery() { AccountNumber = command.AccountNumber }; return(Ok(await Mediator.Send(query))); }
public void Run() { var account = new Account { Id = 42, Balance = 10000 }; var command = new WithdrawCommand(account, 5000); command.Validate(); command.Execute(); }
public async Task <IActionResult> Withdraw([FromRoute] int accountNumber, [FromBody] AccountOperationRequest request) { var withdrawCommand = new WithdrawCommand { AccountNumber = accountNumber, Amount = request.OperationAmount, Tags = request.Tags }; await _mediator.Send(withdrawCommand).ConfigureAwait(false); return(Ok()); }
public void Withdraw_GivenCorrectRequest_WithSameCurrency_NotEnoughBalance_ShouldThrowBusinessException() { var command = new WithdrawCommand() { AccountNumber = "1", Amount = 3000, Currency = "USD" }; var result = Assert.ThrowsAsync <WithdrawFailException>(() => handler.Handle(command, CancellationToken.None)); result.ShouldNotBeNull(); result.Message.Contains("The current balance not enough to withdraw."); }
public void Withdraw_GivenNegativeExchangedAmount_ShouldThrowBusinessErrorException() { var command = new WithdrawCommand() { AccountNumber = "1", Amount = -3, Currency = "USD" }; var result = Assert.ThrowsAsync <WithdrawFailException>(() => handler.Handle(command, CancellationToken.None)); result.ShouldNotBeNull(); result.Message.Contains("Invalid actual amount after exchanged."); }
public void Withdraw_GivenUnSupportCurrency_ShouldThrowBusinessErrorException() { var command = new WithdrawCommand() { AccountNumber = "1", Amount = 3, Currency = "VND" }; var result = Assert.ThrowsAsync <WithdrawFailException>(() => handler.Handle(command, CancellationToken.None)); result.ShouldNotBeNull(); result.Message.Contains("Invalid Currency VND."); }
private async Task Handle(WithdrawCommand command, IEventPublisher publisher) { await _executionInfoRepository.GetOrAddAsync( OperationName, command.OperationId, () => new OperationExecutionInfo <WithdrawalDepositData>( OperationName, command.OperationId, new WithdrawalDepositData { AccountId = command.AccountId, Amount = command.Amount, AuditLog = command.AuditLog, State = WithdrawalState.Created, Comment = command.Comment }, _systemClock.UtcNow.UtcDateTime)); var account = await _accountsRepository.GetAsync(command.AccountId); if (account == null) { publisher.PublishEvent(new WithdrawalStartFailedInternalEvent(command.OperationId, _systemClock.UtcNow.UtcDateTime, $"Account {command.AccountId} not found.")); return; } var accountCapital = await _accountManagementService.GetAccountCapitalAsync(account.Id, useCache : false); if (accountCapital.Disposable < command.Amount) { publisher.PublishEvent(new WithdrawalStartFailedInternalEvent(command.OperationId, _systemClock.UtcNow.UtcDateTime, $"Account {account.Id} balance {accountCapital.Balance}{accountCapital.AssetId} is not enough to withdraw {command.Amount}{accountCapital.AssetId}. " + $"Taking into account the current state of the trading account: {accountCapital.ToJson()}.")); return; } if (account.IsWithdrawalDisabled) { publisher.PublishEvent(new WithdrawalStartFailedInternalEvent(command.OperationId, _systemClock.UtcNow.UtcDateTime, "Withdrawal is disabled")); return; } _chaosKitty.Meow(command.OperationId); publisher.PublishEvent(new WithdrawalStartedInternalEvent(command.OperationId, _systemClock.UtcNow.UtcDateTime)); }
public async Task Then_the_incentive_is_deleted_when_the_incentive_has_no_paid_earnings() { //Arrange var incentive = _fixture.Create <Domain.ApprenticeshipIncentives.ApprenticeshipIncentive>(); var command = new WithdrawCommand(incentive.Account.Id, incentive.Id); _mockIncentiveDomainRepository.Setup(x => x.FindByApprenticeshipId(command.IncentiveApplicationApprenticeshipId)).ReturnsAsync(incentive); // Act await _sut.Handle(command); // Assert incentive.IsDeleted.Should().BeTrue(); }
public MainViewModel() { Owner = new Customer("isaac"); Transactions = new ObservableCollection <Transaction>(); UpdateAccount(Api.LoadAccount(Owner)); DepositCommand = new Command <int>( amount => { UpdateAccount(Api.Deposit(amount, Owner)); WithdrawCommand.Refresh(); }, TryParseInt); WithdrawCommand = new Command <int>( amount => UpdateAccount(Api.Withdraw(amount, Owner)), TryParseInt, () => account.IsInCredit); }
public async Task <IActionResult> Withdraw([FromBody] WithdrawCommand command) { WithdrawResult result = await _handler.Execute(command); if (result == null) { return(new NoContentResult()); } Model model = new Model( result.Transaction.Amount, result.Transaction.Description, result.Transaction.TransactionDate, result.UpdatedBalance ); return(new ObjectResult(model)); }