private Expense RegisterSimpleExpense(RegisterExpense simpleExpense, Payee payee) { var entity = (SimpleExpense)simpleExpense; entity.Payee = payee; #region Validations if (simpleExpense.Payers?.Any() != true) { ModelState.AddModelError("Payers", "When registering a Simple Expense, you must specify at least one Payer."); return(null); } #region Validate Payers // TODO: validate duplications before calling the database var payers = _roommates.GetByIds(simpleExpense.Payers.Select(x => x.Id).Distinct()); if (payers.Count() != simpleExpense.Payers.Count()) { ModelState.AddModelError("Payers", "At least one Payer is invalid, does not represent a registered Roommate, or is duplicated."); return(null); } else if (payers.Count() == 1 && payers.First().Id == payee.Id) { ModelState.AddModelError("Payers", "At this moment, self expenses are not supported. Please consider other alternatives."); return(null); } var sum = simpleExpense.Payers.Sum(x => x.Amount * (decimal)x.Multiplier); if (sum > 0) { ModelState.AddModelError("Payers", "An Expense cannot be proportional and even at the same time. Amount and Multiplier cannot be filled at the same time. Please, select only one."); return(null); } entity.Payers = simpleExpense.Payers.Select(x => new Payer { Id = x.Id, Amount = simpleExpense.Distribution.GetAmount(simpleExpense, x), Name = payers.Single(p => p.Id == x.Id).Name }); var total = entity.Payers.Sum(x => x.Amount); if (total != simpleExpense.Total) { ModelState.AddModelError("Payers", "The total amount for this expense and the total amount by payers' distribution differ."); return(null); } #endregion #endregion var result = _expenses.Add(entity); if (result != null) { UpdateBalances(entity.Payers, entity.Payee, entity.Total); } return(result); }