public void GetBalances_SplitsExpensesBetweenAll() { var userA = CreateSettlementUser(); var userB = CreateSettlementUser(); var userC = CreateSettlementUser(); var users = new[] { userA, userB, userC }; _settlementUsersRepository.GetSettlementUsers(_settlementId) .Returns(users); var expenses = new[] { new Expense { WhoPaid = userA, Amount = 9 } }; _expensesRepository.GetExpenses(_settlementId) .Returns(expenses); var provider = CreateBalancesProvider(); var balances = provider.GetBalances(_settlementId); Assert.Collection(balances, item => Assert.Equal(6M, item.Balance), item => Assert.Equal(-3M, item.Balance), item => Assert.Equal(-3M, item.Balance) ); }
public IReadOnlyList <UserBalance> GetBalances(string settlementId) { var expenses = _expensesRepository.GetExpenses(settlementId).ToList(); var expensesSumByWhoPaid = expenses .GroupBy(e => e.WhoPaid.Id) .ToDictionary(g => g.Key, g => g.Sum(e => e.Amount)); var settlementUsers = _settlementUsersRepository.GetSettlementUsers(settlementId) .ToList(); var usersCount = settlementUsers.Count(); var expensesSumByParticipant = settlementUsers .ToDictionary(u => u.Id, u => Round(expenses .Where(e => e.Participants.IsNullOrEmpty() || e.Participants.Any(p => p.Id == u.Id)) .Sum(e => e.Amount / (e.Participants.IsNullOrEmpty() ? usersCount : e.Participants.Count)))); var transactions = _transactionsRepository.GetTransactions(settlementId) .ToList(); var outgoingTransactionsSumByUser = transactions .GroupBy(t => t.From.Id) .ToDictionary(g => g.Key, g => g.Sum(t => t.Amount)); var incomingTransactionsSumByUser = transactions .GroupBy(t => t.To.Id) .ToDictionary(g => g.Key, g => g.Sum(t => t.Amount)); return(settlementUsers .Select(u => new UserBalance { User = u, Balance = expensesSumByWhoPaid.GetValueOrDefault(u.Id, 0) - expensesSumByParticipant.GetValueOrDefault(u.Id, 0) + outgoingTransactionsSumByUser.GetValueOrDefault(u.Id, 0) - incomingTransactionsSumByUser.GetValueOrDefault(u.Id, 0) }) .ToList()); }
public ActionResult GetAll(string settlementId) { return(Ok(_settlementUsersRepository.GetSettlementUsers(settlementId))); }