public ActionResult SaveExpense(ExpenseVM view) { ModelState.Remove("Id"); if (ModelState.IsValid) { if (view.Id == 0) { _expenseRepository.AddToDatabase(view.MapToModel()); TempData["expenseCreatedOrUpdatedMessage"] = "Expense successfully created!"; } else { _expenseRepository.UpdateInDatabase(view.MapToModel(), view.Id); TempData["expenseCreatedOrUpdatedMessage"] = "Expense successfully updated!"; } _expenseRepository.Save(); // calculate ExchangeRate for ExpenseSum if neccessary var travelReport = _travelReportRepository.FindById(view.TravelReportId).MapToView(); var country = _countryAllowanceRepository .GetAllFromDatabaseEnumerable() .Where(c => c.Id == travelReport.CountryAllowanceId) .SingleOrDefault() .MapToView(); travelReport.ExpenseSum = 0; CalculateExpenseSum(travelReport); } return(RedirectToAction("Edit/" + view.TravelReportId)); }
private void CalculatePrivateCarMileageExpenses(TravelReportVM view) { decimal mileageSum = 0; if (view.StartMileage != null && view.EndMileage != null) { mileageSum = view.EndMileage.Value - view.StartMileage.Value; } // add/update private car expense in Expenses if (view.VehicleType.Value == 0) { var mileageExpense = new ExpenseVM { TravelReportId = view.Id, Date = view.Return, ExpenseCategoryId = 10, BillNumber = "-", BillAmount = mileageSum * 2, OfficialCurrency = "HRK" }; var expenses = _expenseRepository.GetAllFromDatabaseEnumerable().Where(e => e.TravelReportId == view.Id).ToList(); bool exists = false; foreach (var expense in expenses) { if (expense.ExpenseCategoryId == 10) { exists = true; mileageExpense.Id = expense.Id; } } if (exists) { _expenseRepository.UpdateInDatabase(mileageExpense.MapToModel(), mileageExpense.Id); } else { _expenseRepository.AddToDatabase(mileageExpense.MapToModel()); } _expenseRepository.Save(); } else // in case that VehicleType gets changed from "PrivateCar" to any other VehicleType, delete previously existing PrivateCarExpense { var privateCarExpense = _expenseRepository .GetAllFromDatabaseEnumerable() .Where(e => e.ExpenseCategoryId == 10 && e.TravelReportId == view.Id) .SingleOrDefault() .MapToView(); if (privateCarExpense != null) { var expenseInDb = _expenseRepository.FindById(privateCarExpense.Id); _expenseRepository.DeleteFromDatabase(expenseInDb); _expenseRepository.Save(); } } }