public async Task <IEnumerable <BankAccountStockEntity> > GetBankAccountStocks(int bankAccountId) { try { var result = await _bankAccountStockRepository.Select(a => a.BankAccountId == bankAccountId); return(result); } catch (Exception e) { _logger.LogError(e, "Unable to get bank account stocks for account ID: {@BankAccountId}", bankAccountId); throw; } }
public async Task ProcessOrder(BankAccountEntity bankAccount, BrokerOrderDto order) { try { var stockList = (await _stockRepository.Select(a => a.Symbol == order.Symbol)).ToList(); if (stockList.Count() > 1) { throw new ArgumentException($"Symbol {order.Symbol.ToUpper()} is not unique"); } var stock = stockList.Single(); var stockValue = stock.CurrentPrice * order.Amount; bankAccount.BalanceInBrl -= stockValue; if (bankAccount.BalanceInBrl < 0) { throw new ArgumentException("Insufficient balance in account"); } await _bankAccountRepository.Update(bankAccount); var accountStock = (await _bankAccountStockRepository.Select(a => a.BankAccountId == bankAccount.Id && a.Symbol == order.Symbol)).SingleOrDefault(); if (accountStock != null) { accountStock.Amount += order.Amount; if (accountStock.Amount < 0) { throw new ArgumentException("Insufficient stocks to sell"); } await _bankAccountStockRepository.Update(accountStock); } else { if (order.Amount < 0) { throw new ArgumentException("Insufficient stocks to sell"); } var newAccountStock = new BankAccountStockEntity() { BankAccountId = bankAccount.Id, Symbol = stock.Symbol, Amount = order.Amount }; await _bankAccountStockRepository.Insert(newAccountStock); } _bankAccountStockRepository.Save(); _bankAccountRepository.Save(); } catch (Exception e) { _logger.LogError(e, "Service could not complete order"); throw; } }