Esempio n. 1
0
        public IActionResult Add(AddViewModel model)
        {
            var expenses = new List <Expense>();

            foreach (var user in model.Paid)
            {
                var tempValue = Convert.ToDouble(user.Value, CultureInfo.CurrentCulture);
                var value     = Convert.ToDecimal(tempValue);
                if (value != Decimal.Zero)
                {
                    expenses.Add(new Expense()
                    {
                        ExpenseTitle = model.Name,
                        User         = _userRepository.GetUserByName(user.Key),
                        Paid         = value
                    });
                }
            }
            _expenseRepository.AddExpenses(expenses);

            var expensegroup = new ExpenseName()
            {
                Name     = model.Name,
                Expenses = expenses
            };

            _expenseNameRepository.AddGroup(expensegroup);

            decimal sum      = 0;
            decimal tookPart = 0;

            foreach (var user in model.Paid)
            {
                var tempValue = Convert.ToDouble(user.Value, CultureInfo.CurrentCulture);
                var value     = Convert.ToDecimal(tempValue);
                if (value != Decimal.Zero)
                {
                    sum += value;
                    tookPart++;
                }
            }

            var usersToModify = new List <User>();
            var needToPay     = sum / tookPart;

            foreach (var user in model.Paid)
            {
                var tempValue = Convert.ToDouble(user.Value, CultureInfo.CurrentCulture);
                var value     = Convert.ToDecimal(tempValue);
                if (value != Decimal.Zero)
                {
                    usersToModify.Add(new User()
                    {
                        Name = user.Key,
                        Paid = needToPay - value
                    });
                }
            }

            _userRepository.UpdateUsers(usersToModify);

            _expenseRepository.GetAllExpenses();

            var viewModel = new IndexViewModel()
            {
                AllUsers = _userRepository.GetAllUsers(),
                Expenses = _expenseNameRepository.GetAllExpenses()
            };

            return(View("~/Views/Home/Index.cshtml", viewModel));
        }