public void Should_throw_if_user_does_not_exist() { var dto = new UserTransactionDto { UserId = 4 }; Func <System.Threading.Tasks.Task> act = async() => await _service.AddTransaction(dto); act.ShouldThrow <BusinessException>().Where(e => e.Status == ErrorStatus.DataNotFound); }
public async System.Threading.Tasks.Task Should_update_user_budget_when_buying() { var dto = new UserTransactionDto { UserId = userId, Quantity = 2, Price = 10, CompanyId = notOwnedCompanyId }; await _service.AddTransaction(dto); _user.Budget.Should().Be(80); }
public void Should_not_sell_if_user_doesnt_have_any_company_stocks() { var dto = new UserTransactionDto { UserId = userId, Quantity = -2, Price = 10, CompanyId = notOwnedCompanyId }; Func <System.Threading.Tasks.Task> act = async() => await _service.AddTransaction(dto); act.ShouldThrow <BusinessException>().Where(e => e.Status == ErrorStatus.BusinessRuleViolation); _user.Transactions.Count.Should().Be(1); }
private static void VerifyTransaction(UserTransactionDto dto, User user) { if (dto.Quantity < 0) { int currentlyOwnedStocksCount = user.Transactions.Where(t => t.CompanyId == dto.CompanyId) .Sum(t => t.Quantity); if (currentlyOwnedStocksCount < -dto.Quantity) { throw new BusinessException($"Cannot sell more stocks than currently owned ({currentlyOwnedStocksCount})"); } } else if (user.Budget < dto.Price * dto.Quantity) { throw new BusinessException($"Not enough free budget (currently {user.Budget})"); } }
/// <inheritdoc /> public async Task AddTransaction(UserTransactionDto dto) { var user = await _userRepository.GetUserWithTransactions(dto.UserId); if (user == null) { throw new BusinessException(nameof(dto.UserId), "User does not exist", ErrorStatus.DataNotFound); } VerifyTransaction(dto, user); user.Budget -= dto.Quantity * dto.Price; user.Transactions.Add(new UserTransaction { UserId = dto.UserId, CompanyId = dto.CompanyId, Date = dto.Date, Price = dto.Price, Quantity = dto.Quantity }); var saveTask = _userRepository.Save(); var clearCache = _transactionsRepository.ClearTransactionsCache(dto.UserId); await Task.WhenAll(saveTask, clearCache); }