protected virtual async Task <bool> Pay(BuyProductReq buyProductReq, string userName) { double accountBalance = _transactionDAO.GetAccountbalance(userName); double ammountToPay = buyProductReq.Price * buyProductReq.Quantity; TimeSpan sleepFor = SIMULTANEOUS_REQUESTS_WAIT_FOR; if (sleepFor.TotalMilliseconds > 0) { await Task.Delay(sleepFor); } if (accountBalance < ammountToPay) { return(false); } DepositRequest depositRequest = new DepositRequest { Amount = buyProductReq.Price * buyProductReq.Quantity, Reason = TRANSACTION_REASON, ReceiverId = TRANSACTION_RECIVER_ID, SenderId = userName }; bool payResult = _transactionDAO.Pay(depositRequest); return(payResult); }
/// <summary> /// Moves money from the specified input <see cref="Account"/> to the specified destination <see cref="Account"/>. /// </summary> public Result <bool> Transfer(TransferRequest request) { var withdrawRequest = new WithdrawRequest { AccountNumber = request.SourceAccountNumber, Currency = request.Currency }; var withdrawResult = this.Withdraw(withdrawRequest); if (withdrawResult.IsError) { return(withdrawResult); } var depositRequest = new DepositRequest { AccountNumber = request.DestinationAccountNumber, Currency = request.Currency }; var depositResult = this.Deposit(depositRequest); // TODO: Unintended side effect here if the Deposit action fails, the withdraw request has already completed. // TODO: Ideally, this would all be wrapped in some sort of transaction that can be rolled back from persistence. return(depositResult.IsError ? depositResult : Result.Ok(true)); }
public async Task Deposit_WithIncorrectRequest_ReturnFailedTransactionsResult() { // Arrange var depositRequest = new DepositRequest { AccountIban = "TH123456", Amount = 0, }; var transactionsResult = new TransactionsResult { Success = false }; transactionsService .DepositAsync(Arg.Any <DepositRequest>()) .Returns(Task.FromResult(transactionsResult)); // Act var actionResult = await transactionsController.Deposit(depositRequest); var objectResult = actionResult as OkObjectResult; // Assert Assert.NotNull(objectResult); Assert.Equal((int)System.Net.HttpStatusCode.OK, objectResult.StatusCode); Assert.False((objectResult.Value as TransactionsResult).Success); }
public void Deposit(DepositRequest depositRequest) { BankAccount bankAccount = _bankRepository.FindBy(depositRequest.AccountId); bankAccount.Deposit(depositRequest.Amount, ""); _bankRepository.Save(bankAccount); }
public async Task <AccountTradeModel> CloseTrade(CloseTradeRequest request) { using (var scope = _container.BeginLifetimeScope()) { var repository = scope.Resolve <IAccountTradeRepository>(); var entity = await repository.GetAsync(request.TradeId); if (entity != null && entity.AccountId == request.AccountId) { entity.CloseDate = request.CloseDate; entity.ClosePrice = request.ClosePrice; var tradeAmount = CalculateTradeAmount(entity); await repository.CommitAsync(); var transferRequest = new DepositRequest { TransferDate = request.CloseDate, AccountId = request.AccountId, Amount = tradeAmount }; await Transfer(transferRequest, TransferType.Trade); return(new AccountTradeModel(entity)); } return(null); } }
public override Task <Empty> Deposit(DepositRequest request, ServerCallContext context) { using var db = new AppDbContext(); if (db.Sessions.FirstOrDefault(s => s.ID == Guid.Parse(request.SessionId)) == null) { throw new RpcException(new Status(StatusCode.PermissionDenied, "Session is invalid")); } if (request.Amount < 1) { throw new RpcException(new Status(StatusCode.InvalidArgument, "Amount cannot be less than 0")); } var account = db.Accounts.FirstOrDefault(a => a.ID == Guid.Parse(request.AccountId)); if (account == null) { throw new RpcException(new Status(StatusCode.NotFound, "Account not found")); } account.Balance += request.Amount; db.Accounts.Attach(account); db.Entry(account).Property(a => a.Balance).IsModified = true; var t = TransactionModel.CreateDepositTransaction(request, account); db.Transactions.Add(t); db.SaveChanges(); return(Task.FromResult(new Empty())); }
public DepositResponseContainer Deposit(DepositRequest request) { var result = _walletRepository.Deposit(new Internal.Wallet.DTO.DepositRequest { Amount = request.Amount, Currency = request.Currency, MerchantId = _merchantAuthInfo.MerchantId, Token = request.Token, TransactionId = request.TransactionId, UserId = request.UserId }); if (200 != result.StatusCode) { return(new DepositResponseContainer { StatusCode = (StatusCodes)result.StatusCode }); } return(new DepositResponseContainer { StatusCode = (StatusCodes)result.StatusCode, Data = new DepositResponse { TransactionId = result.Data.TransactionId, Balance = result.Data.Balance } }); }
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))); }
public async Task Deposit_DepositInvalidAmounts_ReturnsBadRequest(int depositAmount) { //// 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/Deposit"; DepositRequest depositRequest = new DepositRequest { Amount = depositAmount }; StringContent content = depositRequest.AsStringContent(); //// Act HttpResponseMessage response = await client.PostAsync(endpoint, content); //// Assert Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); walletServiceMock.VerifyNoOtherCalls(); }
public static TransactionModel CreateDepositTransaction(DepositRequest request, AccountModel account) => new TransactionModel( Guid.NewGuid(), DateTime.UtcNow, $"${request.Amount}.00 deposited into the account", account.UserID, TransactionDbEnum.Deposit, request.Amount);
public async Task <IActionResult> PutAccount(Guid id, [FromBody] DepositRequest depositRequest) { try { //if (!RequestHelper.ValidateId(id, Request, _env)) // return BadRequest("HeaderId and Id are not equal"); var account = await _context.Accounts.FirstOrDefaultAsync(x => x.OwnerId == id); account.Balance += depositRequest.Amount; _context.Entry(account).State = EntityState.Modified; await _context.SaveChangesAsync(); _rabbitMqClient.SendMessage(new HistoryMessage { Event = "DepositedMoney", EventMessage = $"Deposited ${depositRequest.Amount} to own account", User = id, Timestamp = DateTime.UtcNow }); _logger.LogInformation("Successfully deposited {Amount} to {@Account}", depositRequest.Amount, account); } catch (Exception e) { _logger.LogError(e, "Failed to deposit money"); throw; } return(NoContent()); }
private bool DoDepositComplete(MonMsg_G2H request, MonTgt_G2H_EFT_DepositComplete monDepositRequest) { InstallationDetailsForMSMQ installationDetails = ExCommsDataContext.Current.GetInstallationDetailsByDatapak(request.InstallationNo); HandlerHelper.Current.SaveSDTRequest(monDepositRequest.CardNumber, request.InstallationNo); Log.Info("TransactionID used in Deposit Request " + installationDetails.TransactionID.ToString()); string asset = HandlerHelper.Current.GetAssetByStockPrefix(request.Asset); DateTime transDate = DateTime.Now; //Authentication - To do DepositRequest depositRequest = new DepositRequest { //AccountType = monDepositRequest.ac, CashableFunds = Convert.ToInt32((monDepositRequest.CashableAmount * 100)), NonCashableFunds = Convert.ToInt32((monDepositRequest.NonCashableAmount * 100)), //Authentication = BarPosition = installationDetails.Bar_Pos_Name, CardNo = monDepositRequest.CardNumber, InstallationNo = request.InstallationNo, SlotIndex = installationDetails.Bar_Pos_Name, SlotNumber = asset, Stand = installationDetails.Bar_Pos_Name, TransactionDate = transDate.ToString("yyyyMMdd").PadLeft(8, '0'), TransactionID = installationDetails.TransactionID.ToString().PadLeft(3, '0').Substring(0, 3), TransactionTime = transDate.ToString("HHmmss").PadLeft(6, '0'), SiteCode = request.SiteCode }; HandlerHelper.PlayerGatewayInstance.DepositComplete(depositRequest, this.DepositCompleteResp); return(true); }
internal DepositResponseContainer Deposit(DepositRequest model) { var client = new RestClient { BaseUrl = new Uri($"{AuthInfo.BaseUrl}/{Controller}") }; var request = new RestRequest { Resource = "Deposit", Method = Method.POST }; var rawHash = $"{model.Amount}|{model.Currency}|{model.MerchantId}|{model.TransactionId}|{model.Token}|{model.UserId}|{AuthInfo.PrivateKey}"; var hash = GetSha256(rawHash); model.Hash = hash; request.AddJsonBody(model); var response = client.Execute <DepositResponseContainer>(request); if (response.StatusCode != HttpStatusCode.OK) { throw new CantConnectToServerException(response); } return(response.Data); }
public async Task DepositAsync_WithAmountMoreThanZero_ReturnTransactionsResult() { // Arrange var depositRequest = new DepositRequest { AccountIban = "TH123456", Amount = 1000, }; var account = new Account { AccountId = Guid.NewGuid(), AccountIban = "TH123456", Balance = 1000, }; accountRepository.GetByAccountIbanAsync(Arg.Any <string>()).Returns(Task.FromResult(account)); accountRepository.UpdateAccountAsync(Arg.Any <Account>()).Returns(Task.FromResult(new Account())); depositRepository.AddDepositAsync(Arg.Any <Deposit>()).Returns(Task.FromResult(new Deposit())); // Act var transactionsResult = await transactionsService.DepositAsync(depositRequest); // Assert Assert.True(transactionsResult.Success); Assert.Equal(1999, transactionsResult.Balance); }
public void Deposit(DepositRequest request) { var account = _accountRepository.FindBy(request.AccountNo); account.Deposit(request.Amount, string.Empty); _accountRepository.Save(account); }
public async Task <IActionResult> Deposit([FromBody] DepositRequest message) { var request = new DepositCommand(message.AccountId, message.Amount); await depositInput.Handle(request); return(depositPresenter.ViewModel); }
public async Task Deposit_Deposit10_ReturnsOkAndPostDepositBalance() { //// Arrange decimal postDepositBalance = 15; Balance expectedBalance = new Balance() { Amount = postDepositBalance }; BalanceResponse expectedBalanceResponse = new BalanceResponse() { Amount = postDepositBalance }; decimal depositAmount = 10; DepositRequest depositRequest = new DepositRequest { Amount = depositAmount }; // Setup Mocks Mock <IWalletService> walletServiceMock = new Mock <IWalletService>(); Deposit deposit = new Deposit { Amount = depositAmount }; walletServiceMock .Setup(walletService => walletService.DepositFundsAsync(deposit)) .Returns(Task.FromResult(expectedBalance)); IWalletService walletService = walletServiceMock.Object; ILogger <WalletController> logger = Mock.Of <ILogger <WalletController> >(); IMapper mapper = Mock.Of <IMapper>(mapper => mapper.Map <Deposit>(depositRequest) == deposit && mapper.Map <BalanceResponse>(expectedBalance) == expectedBalanceResponse); // Initialize SUT WalletController walletController = new WalletController(logger, mapper, walletService); //// Act ActionResult <BalanceResponse> actionResult = await walletController.Deposit(depositRequest); 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.DepositFundsAsync(deposit), Times.Once); walletServiceMock.VerifyNoOtherCalls(); }
public void Deposit_WhenSet_ValidatesInput(decimal amount, int numberOfErrors) { var request = new DepositRequest { Deposit = amount }; Assert.That(ValidateModelHelper.ValidateModel(request).Count, Is.EqualTo(numberOfErrors)); }
protected async Task DepositToCustomer(int amount) { DepositRequest request = new DepositRequest() { Deposit = amount }; var response = await PutAsync("/api/customer/deposit", request); }
public void UpdateRequest(DepositRequest depositRequest) { var request = _context.DepositRequests.FirstOrDefault(x => x.Id == depositRequest.Id); if (request != null) { _context.SaveChanges(); } }
public DepositRequest MapAddDepositRequestToModel(DepositRequestViewModel model) { DepositRequest bankDeposit = Mapper.Map <DepositRequest>(model); bankDeposit.Id = Guid.NewGuid().ToString(); bankDeposit.CreationDate = DateTime.UtcNow; return(bankDeposit); }
/// <summary> /// Deposits an amount to the a customers account. /// </summary> /// <param name="request">The request containing the amount to deposit.</param> /// <param name="customerId">Id of the customer to deposit to.</param> /// <returns>A customer wrapped in a response object.</returns> public async Task DepositAsync(DepositRequest request, string customerId) { //Amount to deposit var depositAmount = request.Deposit; //Deposits await _unitOfWork.CustomerRepository.DepositAsync(customerId, depositAmount); await _unitOfWork.SaveChangesAsync(); }
public async Task <ViewResult> AddBalance() { var(jwtToken, id) = JwtHelper.GetJwtAndIdFromJwt(Request); var depositRequest = new DepositRequest { Amount = 1000 }; await _bankClient.Deposit(depositRequest, id, jwtToken); return(await Index()); }
public async Task <ActionResult <BalanceResponse> > Deposit(DepositRequest depositRequest) { Deposit deposit = _mapper.Map <Deposit>(depositRequest); Balance balance = await _walletService.DepositFundsAsync(deposit); BalanceResponse balanceResponse = _mapper.Map <BalanceResponse>(balance); return(Ok(balanceResponse)); }
protected void btnDeposit_Click(object sender, EventArgs e) { var request = new DepositRequest(); var accountNo = new Guid(ddlAccounts.SelectedValue); request.AccountNo = accountNo; request.Amount = decimal.Parse(txtAmount.Text); new ApplicationAccountService().Deposit(request); DisplaySelectedAccount(); }
protected void btnDeposit_Click(object sender, EventArgs e) { ApplicationBankAccountService service = new ApplicationBankAccountService(); DepositRequest request = new DepositRequest(); Guid AccId = new Guid(ddlBankAccounts.SelectedValue.ToString()); request.AccountId = AccId; request.Amount = Decimal.Parse(txtAmount.Text); service.Deposit(request); DisplaySelectedAccount(); }
public async Task <IActionResult> Deposit([FromBody] DepositRequest depositRequest) { if (depositRequest == null) { return(BadRequest(ModelState)); } var transactionsResult = await transactionsService.DepositAsync(depositRequest); return(Ok(transactionsResult)); }
/// <summary> /// Иницциирование двухстадийной оплаты заказа /// </summary> public DepositResponse Deposit(DepositParams depositParams) { var url = _settings.BaseUrl + "/deposit.do"; DepositRequest request = new DepositRequest(depositParams) { userName = _settings.Username, password = _settings.Password }; var result = _networkClient.PostObjectViaUrlParams <DepositResponse>(url, request); return(result); }
/// <summary> /// Send the deposit money request, and return the deposit money request info. /// </summary> /// <returns>If a request is already, return the deposit money info. Null if there was an error</returns> public DepositRequestResult MakeDepositRequest(DepositRequest model) { DepositRequestResult result = null; var response = SendRequest(HttpVerbs.Post, "api/DepositMoney", model, true); if (response != null) { result = JsonConvert.DeserializeObject <DepositRequestResult>(response.Content.ReadAsStringAsync().Result); } return(result); }
private async Task Transfer(DepositRequest request, TransferType transferType) { using (var scope = _container.BeginLifetimeScope()) { var repository = scope.Resolve <IAccountTransferRepository>(); var entity = repository.Add(new AccountTransferEntity()); entity.AccountId = request.AccountId; entity.TransferDate = request.TransferDate; entity.Amount = request.Amount; entity.TransferType = transferType; await repository.CommitAsync(); } }
private bool DoDepositRequest(MonMsg_G2H request, MonTgt_G2H_EFT_DepositRequest monDepositRequest) { Log.Info("Started Deposit Request"); Log.Info("Card Value : " + monDepositRequest.CardNumber); //Log.Info("Encrypted Pin XXXXXXXXXXXXXXXX"); Log.Info("Started DepositRequest " + monDepositRequest.CardNumber); InstallationDetailsForMSMQ installationDetails = ExCommsDataContext.Current.GetInstallationDetailsByDatapak(request.InstallationNo); HandlerHelper.Current.SaveSDTRequest(monDepositRequest.CardNumber, request.InstallationNo); //HandlerHelper.Current.SaveSDTAccountType(monDepositRequest.CardNumber, ); string asset = HandlerHelper.Current.GetAssetByStockPrefix(request.Asset); DateTime transDate = DateTime.Now; //Authentication - To do DepositRequest depositRequest = new DepositRequest { //AccountType = monDepositRequest.ac, CashableFunds = Convert.ToInt32((monDepositRequest.CashableAmount * 100)), NonCashableFunds = Convert.ToInt32((monDepositRequest.NonCashableAmount * 100)), //Authentication = BarPosition = installationDetails.Bar_Pos_Name, CardNo = monDepositRequest.CardNumber, //EncryptedPin = InstallationNo = request.InstallationNo, SlotIndex = installationDetails.Bar_Pos_Name, SlotNumber = asset, Stand = installationDetails.Bar_Pos_Name, TransactionDate = transDate.ToString("yyyyMMdd").PadLeft(8, '0'), TransactionID = installationDetails.TransactionID.ToString(), TransactionTime = transDate.ToString("HHmmss").PadLeft(6, '0'), SiteCode = request.SiteCode }; HandlerHelper.PlayerGatewayInstance.DepositRequest(depositRequest, this.DepositRequestResp); Log.Info("Time taken to send message to Gateway " + DateTime.Now.TimeOfDay.ToString()); return true; }
private bool DoDepositComplete(MonMsg_G2H request, MonTgt_G2H_EFT_DepositComplete monDepositRequest) { InstallationDetailsForMSMQ installationDetails = ExCommsDataContext.Current.GetInstallationDetailsByDatapak(request.InstallationNo); HandlerHelper.Current.SaveSDTRequest(monDepositRequest.CardNumber, request.InstallationNo); Log.Info("TransactionID used in Deposit Request " + installationDetails.TransactionID.ToString()); string asset = HandlerHelper.Current.GetAssetByStockPrefix(request.Asset); DateTime transDate = DateTime.Now; //Authentication - To do DepositRequest depositRequest = new DepositRequest { //AccountType = monDepositRequest.ac, CashableFunds = Convert.ToInt32((monDepositRequest.CashableAmount * 100)), NonCashableFunds = Convert.ToInt32((monDepositRequest.NonCashableAmount * 100)), //Authentication = BarPosition = installationDetails.Bar_Pos_Name, CardNo = monDepositRequest.CardNumber, InstallationNo = request.InstallationNo, SlotIndex = installationDetails.Bar_Pos_Name, SlotNumber = asset, Stand = installationDetails.Bar_Pos_Name, TransactionDate = transDate.ToString("yyyyMMdd").PadLeft(8, '0'), TransactionID = installationDetails.TransactionID.ToString().PadLeft(3, '0').Substring(0, 3), TransactionTime = transDate.ToString("HHmmss").PadLeft(6, '0'), SiteCode = request.SiteCode }; HandlerHelper.PlayerGatewayInstance.DepositComplete(depositRequest, this.DepositCompleteResp); return true; }