public async Task <WithdrawalResult> WithDraw(CreateWithdrawal withdrawalInfo) { _logger.LogInformation($"{nameof(AccountService)}.{nameof(WithDraw)} - {withdrawalInfo}"); Account account = await _unitOfWork.Accounts.FindByIdAsync(withdrawalInfo.AccountId); if (account == null) { return(new WithdrawalResult(withdrawalInfo.AccountId, AccountStatus.Error, "Account id not be found", Currency.None, Amount.FromInput(withdrawalInfo.Amount.Value), Amount.None, Amount.None)); } if (canWithDraw() == false) { return(new WithdrawalResult(withdrawalInfo.AccountId, AccountStatus.Error, "You've exceeded withdrawal limit or amount is greater than balance", Currency.None, Amount.FromInput(withdrawalInfo.Amount.Value), Amount.FromInput(account.Balance), Amount.FromInput(account.Balance))); } decimal oldBalance = account.Balance; decimal newBalance = account.Balance - withdrawalInfo.Amount.Value; account.Balance = newBalance; await _unitOfWork.Accounts.UpdateAsync(account); Transaction transaction = new Transaction { AccountId = withdrawalInfo.AccountId, Type = TransactionType.Withdrawal.ToString(), Amount = withdrawalInfo.Amount.Value, Balance = account.Balance, Timestamp = DateTime.Now }; await _unitOfWork.Transactions.AddAsync(transaction); await _unitOfWork.Complete(); return(new WithdrawalResult(withdrawalInfo.AccountId, AccountStatus.Success, AccountStatus.Success.ToString(), Currency.FromInput(Currencies.GBP), Amount.FromInput(withdrawalInfo.Amount.Value), Amount.FromInput(oldBalance), Amount.FromInput(account.Balance))); bool canWithDraw() { return(withdrawalInfo.Amount.Value <= account.Balance && account.Balance > 0); } }
public async Task <IActionResult> Withdraw(CreateWithdrawalRequest request, CancellationToken token) { _logger.LogInformation($"{nameof(AccountController)}.{nameof(Withdraw)} - {request}"); if (!ModelState.IsValid) { return(BadRequest($"Problem with CreateWithdrawalRequest")); } CreateWithdrawal withdraw = new CreateWithdrawal(request.AccountId, Amount.FromInput(request.Amount)); WithdrawalResult withdrawalResult = await _accountService.WithDraw(withdraw); if (withdrawalResult.Status == AccountStatus.Error) { return(BadRequest($"{withdrawalResult.Message}")); } AccountWithdrawalResponse response = new AccountWithdrawalResponse(withdrawalResult.AccountId, withdrawalResult.Amount.Value, withdrawalResult.OldBalance.Value, withdrawalResult.NewBalance.Value); return(Ok(response)); }