public async Task <OperationResult <UserWalletsDTO> > ChangeWalletBalanceAsync (UserWalletBalanceOperationDTO userWallet) { if (!userWallet.UserId.HasValue) { throw new ArgumentNullException(nameof(userWallet.UserId), "User ID must not be null."); } var user = _userService.Get(userWallet.UserId.Value); if (user == null) { user = await _userService.CreateUserAsync(); } if (!await _currencySrv.IsExists(userWallet.Wallet.Currency)) { return(OperationResultBuilder <UserWalletsDTO> .BuildError(null, "Currency does not exist or is not supported.")); } var wallet = _walletRepo.Data .FirstOrDefault(w => w.UserFK.Equals(user.Id) && string.Equals(w.CurrencyISOCode, userWallet.Wallet.Currency, StringComparison.InvariantCultureIgnoreCase)); if (wallet == null) { wallet = new Wallet() { UserFK = user.Id, Amount = 0, CurrencyISOCode = userWallet.Wallet.Currency }; wallet = await _walletRepo.AddAsync(wallet); } wallet.Amount += userWallet.Wallet.Amount; if (wallet.Amount < 0) { return(OperationResultBuilder <UserWalletsDTO> .BuildError(null, "Operation rejected, insufficient funds.")); } wallet = await _walletRepo.UpdateAsync(wallet); return(await GetUserWalletsAsync(user.Id)); }
public async Task <IActionResult> ChangeWalletsBalance([FromBody] UserWalletBalanceOperationDTO userWallet) { if (userWallet == null || !userWallet.UserId.HasValue) { return(BadRequest("Invalid model.")); } var result = await _walletSrv.ChangeWalletBalanceAsync(userWallet); if (result.IsSuccess) { return(Ok(result)); } return(BadRequest(result)); }