public void Withdrawal(WithdrawalRequest withdrawalRequest) { BankAccount bankAccount = _bankRepository.FindBy(withdrawalRequest.AccountId); bankAccount.Withdraw(withdrawalRequest.Amount, ""); _bankRepository.Save(bankAccount); }
public async Task <MessageEnvelope> Withdrawal(KeyPair destination, string amount, ConstellationInfo.Asset asset, bool waitForFinalize = true) { var paymentMessage = new WithdrawalRequest(); var tx = await TransactionHelper.GetWithdrawalTx(keyPair, constellation, destination, amount, asset); paymentMessage.TransactionXdr = tx.ToArray(); var response = (CentaurusResponse)await connection.SendMessage(paymentMessage.CreateEnvelope()); var result = await(waitForFinalize ? response.ResponseTask : response.AcknowledgmentTask); var txResultMessage = result.Message as ITransactionResultMessage; if (txResultMessage is null) { throw new Exception($"Unexpected result type '{result.Message.MessageType}'"); } tx.Sign(keyPair); foreach (var signature in txResultMessage.TxSignatures) { tx.Signatures.Add(signature.ToDecoratedSignature()); } var submitResult = await tx.Submit(constellation); if (!submitResult.IsSuccess()) { logger.Error($"Submit withdrawal failed. Result xdr: {submitResult.ResultXdr}"); } return(result); }
public async Task <ValidationResult> ValidateWithdrawalRequest(WithdrawalRequest request) { var result = await HttpClient.SecurePostAsJsonAsync(Token, "api/Payment/ValidateWithdrawalRequest", request); return(await EnsureApiResult <ValidationResult>(result)); }
public async Task <IHttpActionResult> PutWithdrawalRequest(long id, WithdrawalRequest withdrawalRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != withdrawalRequest.Id) { return(BadRequest()); } db.Entry(withdrawalRequest).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!WithdrawalRequestExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public ActionResult WithdrawalRequest([FromBody] WithdrawalRequest withdrawalRequest) { if (!ModelState.IsValid) { return(BadRequest(new ApiResponse { Status = false, ModelState = ModelState })); } Task.WaitAny(); try { if (withdrawalRequest == null) { return(BadRequest(new ApiResponse { Status = false })); } else { return(Ok(new ApiResponse { Status = true })); } } catch (Exception exp) { _logger.LogError(exp.Message); return(BadRequest(new ApiResponse { Status = false })); } }
private static Withdrawal CheckBankNotes(WithdrawalRequest withdrawalRequest) { var withdrawal = new Withdrawal(); var withdrawalAmount = withdrawalRequest.Amount; while (withdrawalAmount >= BankNotes[2]) { withdrawalAmount -= BankNotes[2]; withdrawal.FiftyReaisAmount++; } while (withdrawalAmount >= BankNotes[1]) { withdrawalAmount -= BankNotes[1]; withdrawal.TwentyReaisAmount++; } while (withdrawalAmount >= BankNotes[0]) { withdrawalAmount -= BankNotes[0]; withdrawal.TenReaisAmount++; } if (withdrawalAmount != 0) { withdrawal.Message = "Valor inválido. Sacando o valor mais próximo..."; } return(withdrawal); }
public async Task Withdrawal_WithdrawalInvalidAmounts_ReturnsBadRequest(int withdrawalAmount) { //// Arrange // Setup Mocks Mock <IWalletService> walletServiceMock = new Mock <IWalletService>(); IWalletService walletService = walletServiceMock.Object; // Initialize HTTP client and request data WebApplicationFactory <Startup> factory = new CustomWebApplicationFactory <Startup>(services => services.SwapTransient(provider => walletService) ); HttpClient client = factory.CreateClient(); string endpoint = "Wallet/Withdraw"; WithdrawalRequest withdrawalRequest = new WithdrawalRequest { Amount = withdrawalAmount }; StringContent content = withdrawalRequest.AsStringContent(); //// Act HttpResponseMessage response = await client.PostAsync(endpoint, content); //// Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); walletServiceMock.VerifyNoOtherCalls(); }
public void Whitdrawal(WithdrawalRequest request) { var account = _accountRepository.FindBy(request.AccountNo); account.Withdraw(request.Amount, string.Empty); _accountRepository.Save(account); }
public async Task Withdrawal_Withdraw20_ReturnsOkAndBalance5() { //// Arrange decimal postWithdrawalBalanceAmount = 5; Balance postWithdrawalBalance = new Balance() { Amount = postWithdrawalBalanceAmount }; BalanceResponse expectedBalanceResponse = new BalanceResponse() { Amount = postWithdrawalBalanceAmount }; decimal withdrawalAmount = 20; WithdrawalRequest withdrawalRequest = new WithdrawalRequest { Amount = withdrawalAmount }; // Setup Mocks Mock <IWalletService> walletServiceMock = new Mock <IWalletService>(); Withdrawal withdrawal = new Withdrawal { Amount = withdrawalAmount }; walletServiceMock .Setup(walletService => walletService.WithdrawFundsAsync(withdrawal)) .Returns(Task.FromResult(postWithdrawalBalance)); IWalletService walletService = walletServiceMock.Object; ILogger <WalletController> logger = Mock.Of <ILogger <WalletController> >(); IMapper mapper = Mock.Of <IMapper>(mapper => mapper.Map <Withdrawal>(withdrawalRequest) == withdrawal && mapper.Map <BalanceResponse>(postWithdrawalBalance) == expectedBalanceResponse); // Initialize SUT WalletController walletController = new WalletController(logger, mapper, walletService); //// Act ActionResult <BalanceResponse> actionResult = await walletController.Withdraw(withdrawalRequest); ActionResult actualActionResult = actionResult.Result; //// Assert OkObjectResult okObjectResult = Assert.IsType <OkObjectResult>(actionResult.Result); BalanceResponse actualBalanceResponse = Assert.IsType <BalanceResponse>(okObjectResult.Value); Assert.Equal(expectedBalanceResponse, actualBalanceResponse); walletServiceMock.Verify(walletService => walletService.WithdrawFundsAsync(withdrawal), Times.Once); walletServiceMock.VerifyNoOtherCalls(); }
public void WithdrawAsyncTest(HttpStatusCode httpStatusCode, ContractStatus withdrawalType) { // Arrange Mock.Get(_contractsDataLogger) .Setup(p => p.LogInformation(It.IsAny <string>(), It.IsAny <object[]>())); if (httpStatusCode != HttpStatusCode.OK) { Mock.Get(_contractsDataLogger) .Setup(p => p.LogError(It.IsAny <ApiGeneralException>(), It.IsAny <string>(), It.IsAny <object[]>())); } var expectedContractRequest = new WithdrawalRequest { ContractNumber = "Test", ContractVersion = 1, FileName = "sample-blob-file.xml", Id = 1, WithdrawalType = withdrawalType }; ContractsDataService contractsDataService = CreateContractsDataService(); SetUpHttpMessageHandler(expectedContractRequest, httpStatusCode, $"/api/contract/withdraw", HttpMethod.Patch); //Act Func <Task> action = async() => await contractsDataService.WithdrawAsync(expectedContractRequest); // Assert switch (httpStatusCode) { case HttpStatusCode.OK: action.Should().NotThrow(); break; case HttpStatusCode.BadRequest: action.Should().Throw <ContractBadRequestClientException>(); break; case HttpStatusCode.NotFound: action.Should().Throw <ContractNotFoundClientException>(); break; case HttpStatusCode.PreconditionFailed: action.Should().Throw <ContractStatusClientException>(); break; case HttpStatusCode.Conflict: action.Should().Throw <ContractUpdateConcurrencyClientException>(); break; default: throw new NotImplementedException(); } _mockHttpMessageHandler.VerifyNoOutstandingExpectation(); VerifyAllMocks(); }
public async Task <ActionResult <BalanceResponse> > Withdraw(WithdrawalRequest withdrawalRequest) { Withdrawal withdrawal = _mapper.Map <Withdrawal>(withdrawalRequest); Balance balance = await _walletService.WithdrawFundsAsync(withdrawal); BalanceResponse balanceResponse = _mapper.Map <BalanceResponse>(balance); return(Ok(balanceResponse)); }
public async Task <IHttpActionResult> GetWithdrawalRequest(long id) { WithdrawalRequest withdrawalRequest = await db.WithdrawalRequests.FindAsync(id); if (withdrawalRequest == null) { return(NotFound()); } return(Ok(withdrawalRequest)); }
protected void btnWithdrawal_Click(object sender, EventArgs e) { var request = new WithdrawalRequest(); var accountNo = new Guid(ddlAccounts.SelectedValue); request.AccountNo = accountNo; request.Amount = decimal.Parse(txtAmount.Text); new ApplicationAccountService().Whitdrawal(request); DisplaySelectedAccount(); }
protected void btnWithdrawal_Click(object sender, EventArgs e) { ApplicationBankAccountService service = new ApplicationBankAccountService(); WithdrawalRequest request = new WithdrawalRequest(); Guid AccId = new Guid(ddlBankAccounts.SelectedValue.ToString()); request.AccountId = AccId; request.Amount = Decimal.Parse(txtAmount.Text); service.Withdrawal(request); DisplaySelectedAccount(); }
public async Task <IHttpActionResult> PostWithdrawalRequest(WithdrawalRequest withdrawalRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } db.WithdrawalRequests.Add(withdrawalRequest); await db.SaveChangesAsync(); return(CreatedAtRoute("DefaultApi", new { id = withdrawalRequest.Id }, withdrawalRequest)); }
/// <summary> /// Send the withdrawal money request, and return the withdrawal money request info. /// </summary> /// <returns>If a request is already, return the withdrawal money info. Null if there was an error</returns> public WithdrawalRequestInfo MakeWithdrawalRequest(WithdrawalRequest model) { WithdrawalRequestInfo result = null; var response = SendRequest(HttpVerbs.Post, "api/WithdrawalMoney", model, true); if (response != null) { result = JsonConvert.DeserializeObject <WithdrawalRequestInfo>(response.Content.ReadAsStringAsync().Result); } return(result); }
/// <inheritdoc/> public async Task <bool> WithdrawAsync(ContractEvent contractEvent) { var withdrawRequest = new WithdrawalRequest() { ContractNumber = contractEvent.ContractNumber, ContractVersion = contractEvent.ContractVersion, FileName = contractEvent.ContractEventXml, WithdrawalType = (ClientEnums.ContractStatus)contractEvent.Status }; await _contractsDataService.WithdrawAsync(withdrawRequest); return(true); }
public async Task <IHttpActionResult> DeleteWithdrawalRequest(long id) { WithdrawalRequest withdrawalRequest = await db.WithdrawalRequests.FindAsync(id); if (withdrawalRequest == null) { return(NotFound()); } db.WithdrawalRequests.Remove(withdrawalRequest); await db.SaveChangesAsync(); return(Ok(withdrawalRequest)); }
public async Task Withdrawal_WithdrawalInsufficientBalanceException_ReturnsBadRequest() { //// Arrange int withdrawalAmount = 1000; // Setup Mocks Mock <IWalletService> walletServiceMock = new Mock <IWalletService>(); Withdrawal withdrawal = new Withdrawal { Amount = withdrawalAmount }; walletServiceMock .Setup(walletService => walletService.WithdrawFundsAsync(It.Is <Withdrawal>( actualWithdrawal => _comparer.Compare(withdrawal, actualWithdrawal).AreEqual))) .Throws <InsufficientBalanceException>(); IWalletService walletService = walletServiceMock.Object; // Initialize HTTP client and request data WebApplicationFactory <Startup> factory = new CustomWebApplicationFactory <Startup>(services => services.SwapTransient(provider => walletService) ); HttpClient client = factory.CreateClient(); string endpoint = "Wallet/Withdraw"; WithdrawalRequest withdrawalRequest = new WithdrawalRequest { Amount = withdrawalAmount }; StringContent content = withdrawalRequest.AsStringContent(); //// Act HttpResponseMessage response = await client.PostAsync(endpoint, content); //// Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); walletServiceMock.Verify(walletService => walletService.WithdrawFundsAsync(It.Is <Withdrawal>( actualWithdrawal => _comparer.Compare(withdrawal, actualWithdrawal).AreEqual) ), Times.Once); walletServiceMock.VerifyNoOtherCalls(); }
public async Task <ActionResult <WithdrawalResponse> > VerifyWithdrawal(WithdrawalRequest request) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (string.IsNullOrEmpty(request.PersonIdentifier)) { return(BadRequest("PersonIdentifier is empty")); } if (request.Amount <= decimal.Zero) { return(BadRequest("Amount for withdrawal must be greater than zero")); } var employee = await _employeeService.GetEmployeeByPersonIdentifier(request.PersonIdentifier); if (employee == null) { return(BadRequest("Employee not found")); } var adjustedAmount = decimal.Zero; var observations = _accountService.VerifyWithdrawal(request.Amount, employee); if (!observations.Any()) { adjustedAmount = _accountService.GetAdjustedWithdrawalAmount(request.Amount, employee); } return(Ok(new WithdrawalResponse { Allowed = !observations.Any(), Observations = observations.ToList(), AdjustedAmount = adjustedAmount })); } catch (Exception ex) { var friendlyMessage = $"An error occurred while checking a withdrawal (Person Identifier: {request.PersonIdentifier}, Amount: {request.Amount})"; _logger.LogError(ex, friendlyMessage); return(BadRequest($"{friendlyMessage}. Please, contact the support")); } }
public OfflineWithdrawalResponse OfflineWithdraw(WithdrawalRequest request) { ValidateAccountFrozenStatus(); var offlineWithdrawalRequest = new OfflineWithdrawRequest { PlayerId = PlayerId, Amount = request.Amount, PlayerBankAccountId = _paymentQueries.GetPlayer(PlayerId).CurrentBankAccount.Id, RequestedBy = Username, NotificationType = request.NotificationType, }; _withdrawalService.Request(offlineWithdrawalRequest); return(new OfflineWithdrawalResponse()); }
public async Task WithdrawalQuantumTest(double amount, bool hasWithdrawal, bool useFakeSigner, Type excpectedException) { var outputStream = new XdrDataOutputStream(); var txBuilder = new TransactionBuilder(new AccountResponse(TestEnvironment.Client1KeyPair.AccountId, 1)); txBuilder.SetFee(10_000); txBuilder.AddOperation(new PaymentOperation.Builder(TestEnvironment.Client1KeyPair, new AssetTypeNative(), (amount / AssetsHelper.StroopsPerAsset).ToString("0.##########", CultureInfo.InvariantCulture)).SetSourceAccount(TestEnvironment.AlphaKeyPair).Build()); txBuilder.AddTimeBounds(new stellar_dotnet_sdk.TimeBounds(maxTime: DateTimeOffset.UtcNow.AddSeconds(60))); var tx = txBuilder.Build(); stellar_dotnet_sdk.xdr.Transaction.Encode(outputStream, tx.ToXdrV1()); var account = Global.AccountStorage.GetAccount(TestEnvironment.Client1KeyPair); var withdrawal = new WithdrawalRequest { Account = account.Account.Id, RequestId = 1, TransactionXdr = outputStream.ToArray(), AccountWrapper = account }; var envelope = withdrawal.CreateEnvelope(); envelope.Sign(useFakeSigner ? TestEnvironment.Client2KeyPair : TestEnvironment.Client1KeyPair); if (!Global.IsAlpha) { var quantum = new RequestQuantum { Apex = Global.QuantumStorage.CurrentApex + 1, RequestEnvelope = envelope, Timestamp = DateTime.UtcNow.Ticks }; envelope = quantum.CreateEnvelope(); envelope.Sign(TestEnvironment.AlphaKeyPair); } var result = await AssertQuantumHandling(envelope, excpectedException); if (excpectedException == null) { Assert.IsTrue(account.HasPendingWithdrawal); Assert.IsTrue(account.Account.GetBalance(0).Liabilities == amount); } }
public void Setup() { var employee = new Employee { PersonIdentifier = "123456789", BirthDate = DateTime.Now.AddYears(-10), Account = new Account { Balance = 800.00m, Withdrawals = new List <Withdrawal>() } }; completedRequest = new WithdrawalRequest { Amount = 50.0m, PersonIdentifier = "123456789" }; wrongRequest = new WithdrawalRequest { PersonIdentifier = string.Empty }; _employeeService = new Mock <IEmployeeService>(); _accountService = new Mock <IAccountService>(); _logger = new Mock <ILogger <WithdrawalController> >(); _employeeService .Setup(s => s.GetEmployeeByPersonIdentifier(completedRequest.PersonIdentifier)) .Returns(Task.FromResult(employee)); _accountService .Setup(s => s.VerifyWithdrawal(completedRequest.Amount, employee)) .Returns(new List <string>()); _accountService .Setup(s => s.GetAdjustedWithdrawalAmount(completedRequest.Amount, employee)) .Returns(100.0m); _withdrawalController = new WithdrawalController(_employeeService.Object, _accountService.Object, _logger.Object); }
/// <inheritdoc/> public async Task WithdrawAsync(WithdrawalRequest withdrawalRequest) { _logger.LogInformation($"Withdraw endpoint called for [{withdrawalRequest.ContractNumber}] version [{withdrawalRequest.ContractVersion}] with type [{withdrawalRequest.WithdrawalType}]."); try { await Patch($"/api/contract/withdraw", withdrawalRequest); } catch (ApiGeneralException ex) { switch (ex.ResponseStatusCode) { case HttpStatusCode.PreconditionFailed: throw new ContractStatusClientException($"Contract not in correct status for manual approval.", ex); case HttpStatusCode.Conflict: throw new ContractUpdateConcurrencyClientException(withdrawalRequest.ContractNumber, withdrawalRequest.ContractVersion, ex); default: throw; } } }
public ValidationResult ValidateWithdrawalRequest(WithdrawalRequest request) { var player = _paymentQueries.GetPlayer(PlayerId); if (player == null) { throw new RegoException(ErrorMessagesEnum.ServiceUnavailable.ToString()); } var offlineWithdrawalRequest = new OfflineWithdrawRequest { PlayerId = PlayerId, Amount = request.Amount, PlayerBankAccountId = player.CurrentBankAccount.Id, RequestedBy = Username, NotificationType = request.NotificationType, }; var errors = new Dictionary <string, string>(); try { var result = _paymentQueries.ValidateOfflineWithdrawalRequest(offlineWithdrawalRequest); if (result.Errors.Any()) { result.Errors.ForEach(x => errors.Add(x.PropertyName, x.ErrorMessage)); } } catch (RegoValidationException regoValidationException) { errors.Add("Amount", regoValidationException.Message); } return(new ValidationResult { Errors = errors }); }
public async Task <(Guid requestId, string withdrawalCode)> CreateWithdrawalRequest(CreateWithdrawalRequestModel model) { logger.LogInformation($"{model} Starting..."); decimal amountCommission = 1m; var finalAmount = model.Amount - amountCommission; if (model.Amount <= 0 || finalAmount <= 0) { throw new ArgumentException("ErrorAmountMustBeGreaterZero"); } var wallet = await context.Wallets.FirstAsync(x => x.Currency == model.Currency && x.UserId == model.UserId); if (wallet.Amount < model.Amount) { throw new ArgumentException("ErrorNotEnoughMoney"); } if (wallet.Currency != Currency.SPX) { throw new ArgumentException($"Withdrawal requests from {wallet.Currency} not allowed"); } wallet.Amount -= model.Amount; var code = new PasswordGenerator(20).IncludeLowercase().IncludeUppercase().IncludeNumeric().Next(); var walletTransaction = new WalletTransaction { Id = Guid.NewGuid(), Amount = model.Amount, DateCreated = DateTime.UtcNow, Currency = Currency.SPX, Type = WalletTransactionType.WalletWithdraw, WithdrawAddress = model.Wallet, Status = WalletTransactionStatus.New, Wallet = wallet, }; context.Add(walletTransaction); var request = new WithdrawalRequest { Id = Guid.NewGuid(), Amount = model.Amount, AmountWithCommission = finalAmount, Currency = model.Currency, UserId = model.UserId, Status = WithdrawalRequestStatus.New, Wallet = model.Wallet, Code = code, DateCreate = DateTime.UtcNow, IsApprovedByManager = false, IsApprovedByUser = false, WalletTransactionId = walletTransaction.Id }; context.Add(request); await context.SaveChangesAsync(); return(request.Id, code); }
/// <summary> /// Withdraw funds from the constellation to the supported blockchain network. /// </summary> /// <param name="network">Blockchain provider identifier</param> /// <param name="destination">Destination address</param> /// <param name="assetId">Id of the asset to withdraw</param> /// <param name="amount">Amount to withdraw</param> /// <returns></returns> public async Task <QuantumResult> Withdraw(string network, string destination, int assetId, long amount) { var withdrawalRequest = new WithdrawalRequest(); //TODO: set amount, asset, destination return(await Send(withdrawalRequest)); }
public async Task <OfflineWithdrawalResponse> OfflineWithdrawal(WithdrawalRequest request) { return(await _memberApiProxy.OfflineWithdrawAsync(request)); }
public async Task <ValidationResult> ValidateWithdrawalRequest(WithdrawalRequest request) { return(await _memberApiProxy.ValidateWithdrawalRequest(request)); }
public Task Withdraw(string skillId, WithdrawalRequest request) { return(Inner.Withdraw(skillId, request)); }