public async Task <IActionResult> Put(int id, [FromBody] DailyExpense value) { if (value == null) { return(BadRequest()); } var spentItem = await _context.Wallet.FindAsync(id); if (spentItem == null) { _logger.LogInformation($"Daily Expense for {id} does not exists!!"); return(NotFound()); } //Assign Values // Use AutoMapper if more properties spentItem.Amount = value.Amount; spentItem.Description = value.Description; spentItem.SpentOn = value.SpentOn; _context.Update(spentItem); await SaveAsync(); return(NoContent()); }
public ActionResult EditExpenses(DailyExpense expenses) { var status = "error"; try { if (!Authenticated) { status = "SESSION EXPIRED"; } else { DailyExpense objexp = db.DailyExpenses.Where(x => x.UID == expenses.UID).FirstOrDefault(); objexp.UpdatedOn = DateTime.Now; objexp.UpdatedBy = ActiveUserId; objexp.Date = expenses.Date; objexp.Amount = expenses.Amount; objexp.Comments = expenses.Comments; //db.Entry(size).State = System.Data.Entity.EntityState.Modified; if (db.SaveChanges() > 0) { status = JsonConvert.SerializeObject(objexp); } } } catch (Exception ex) { ApplicationExceptionLogging(ex.Message, ex.StackTrace, "DailyExpensesController", "EditExpenses"); } return(Content(status)); }
public IActionResult Put(int id, [FromBody] DailyExpense value) { if (value == null) { return(BadRequest()); } var spentItem = _context.DailyExpenses.Find(id); if (spentItem == null) { //UnComment this for non Serilog Sink to Database //_logger.Information($"Daily Expense for {id} does not exists!!"); _logger.LogInformation($"Daily Expense for {id} does not exists!!"); return(NotFound()); } //Assign Values // Use AutoMapper if more properties spentItem.Amount = value.Amount; spentItem.Description = value.Description; spentItem.SpentOn = value.SpentOn; _context.Update(spentItem); Save(); return(NoContent()); }
private void CheckMovieBudget(DailyExpense expense) { if (expense.SpentOn == ExpenseType.Movies && expense.Amount > 300) { ModelState.AddModelError("MovieLimit", $"Max movie expense limit is 300 and your amount is {expense.Amount}"); } }
public ActionResult AddExpense(DailyExpense dailyexpense) { var status = "error"; try { if (!Authenticated) { status = "SESSION EXPIRED"; } else { dailyexpense.CreatedOn = DateTime.Now; dailyexpense.CreatedBy = ActiveUserId; dailyexpense.UID = Guid.NewGuid(); dailyexpense.Status = 1; db.DailyExpenses.Add(dailyexpense); if (db.SaveChanges() > 0) { status = JsonConvert.SerializeObject(dailyexpense); } } } catch (Exception ex) { ApplicationExceptionLogging(ex.Message, ex.StackTrace, "CategoryController", "AddCategory"); } return(Content(status)); }
public ActionResult DeleteConfirmed(int id) { DailyExpense dailyExpense = db.dailyExpense.Find(id); db.dailyExpense.Remove(dailyExpense); db.SaveChanges(); return(RedirectToAction("Index")); }
private void CheckMovieBudget(DailyExpense expense) { if (expense.SpentOn == ExpenseType.Movies && expense.Amount > 300) { //UnComment this for non Serilog Sink to Database //_logger.Error("Errorneous input for Movie"); _logger.LogError("Errorneous input for Movie"); ModelState.AddModelError("MovieLimit", $"Max movie expense limit is 300 and your amount is {expense.Amount}"); } }
public ActionResult Edit(DailyExpense objDailyExpenseInfo) { if (ModelState.IsValid) { DailyExpenseBLL objDailyExpenseBLL = new DailyExpenseBLL(); objDailyExpenseBLL.UpdateDailyExpenseInfo(objDailyExpenseInfo); } return(RedirectToAction("Index", "DailyExpense")); }
public ActionResult Save() { ExpenseDetailBLL objExpenseDetailBLL = new ExpenseDetailBLL(); var model = new DailyExpense { ExpenseDetailInfo = objExpenseDetailBLL.GetAllExpenseTypeInfo() }; return(View(model)); }
public ActionResult Edit([Bind(Include = "Id,Day,ItemCategoryId,Amount")] DailyExpense dailyExpense) { if (ModelState.IsValid) { db.Entry(dailyExpense).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.ItemCategoryId = new SelectList(db.itemCategory, "Id", "ItemName", dailyExpense.ItemCategoryId); return(View(dailyExpense)); }
public ActionResult Save(DailyExpense objDailyExpense) { objDailyExpense.ExpenseDetailId = Convert.ToInt16(Request.Form["ExpenseDetailId"]); if (ModelState.IsValid) { DailyExpenseBLL objDailyExpenseBLL = new DailyExpenseBLL(); objDailyExpenseBLL.SaveDailyExpenseInfo(objDailyExpense); } return(RedirectToAction("Index", "DailyExpense")); }
// GET: DailyExpenses/Details/5 public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } DailyExpense dailyExpense = db.dailyExpense.Find(id); if (dailyExpense == null) { return(HttpNotFound()); } return(View(dailyExpense)); }
// GET: DailyExpenses/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } DailyExpense dailyExpense = db.dailyExpense.Find(id); if (dailyExpense == null) { return(HttpNotFound()); } ViewBag.ItemCategoryId = new SelectList(db.itemCategory, "Id", "ItemName", dailyExpense.ItemCategoryId); return(View(dailyExpense)); }
public IActionResult Post([FromBody] DailyExpense value) { if (value == null) { throw new WebApiException("Request Object was NULL", HttpStatusCode.BadRequest); } CheckMovieBudget(value); if (!ModelState.IsValid) { throw new WebApiException($"Max movie expense limit is 300 and your amount is {value.Amount}", HttpStatusCode.BadRequest); } var newSpentItem = _context.DailyExpenses.Add(value); Save(); return(Ok(newSpentItem.Entity.Id)); }
public async Task <IActionResult> Post([FromBody] DailyExpense value) { if (value == null) { _logger.LogError("Request Object was NULL"); return(BadRequest()); } CheckMovieBudget(value); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var newSpentItem = _context.Wallet.AddAsync(value); await SaveAsync(); return(Ok(newSpentItem.Result.Entity.Id)); }
public ActionResult Delete(Guid Id) { var status = "error"; try { if (!Authenticated) { status = "SESSION EXPIRED"; } else { DailyExpense obj = new DailyExpense(); DailyExpense objexp = db.DailyExpenses.Where(x => x.UID == Id).FirstOrDefault(); objexp.Status = 2; if (db.SaveChanges() > 0) { var ListRelation = (from s in db.DailyExpenses where s.Status == 1 select new { UID = s.UID, Date = s.Date, Amount = s.Amount, Comments = s.Comments, }).ToList(); status = JsonConvert.SerializeObject(ListRelation); } } } catch (Exception ex) { ApplicationExceptionLogging(ex.Message, ex.StackTrace, "DailyExpenseController", "Edit"); } return(Content(status)); }
public IActionResult Post([FromBody] DailyExpense value) { if (value == null) { _logger.LogError("Request Object was NULL"); //UnComment this for non Serilog Sink to Database //_logger.Error("Request Object was NULL"); return(BadRequest()); } CheckMovieBudget(value); if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var newSpentItem = _context.DailyExpenses.Add(value); Save(); return(Ok(newSpentItem.Entity.Id)); }
public DailyExpense GetDailyExpenseInfo(int id) { objDataAccess = DataAccess.NewDataAccess(); objDbCommand = objDataAccess.GetCommand(true, IsolationLevel.ReadCommitted); DbDataReader objDbDataReader = null; List <DailyExpense> objDailyExpenseList = new List <DailyExpense>(); DailyExpense objDailyExpense = new DailyExpense(); try { objDbCommand.AddInParameter("DailyExpenseId", id); objDbDataReader = objDataAccess.ExecuteReader(objDbCommand, "[dbo].[uspGetDailyExpenseInfo]", CommandType.StoredProcedure); if (objDbDataReader.HasRows) { while (objDbDataReader.Read()) { objDailyExpense = new DailyExpense(); this.BuildModelForDailyExpense(objDbDataReader, objDailyExpense); objDailyExpenseList.Add(objDailyExpense); } } } catch (Exception ex) { throw new Exception("Error : " + ex.Message); } finally { if (objDbDataReader != null) { objDbDataReader.Close(); } objDataAccess.Dispose(objDbCommand); } return(objDailyExpense); }
public string UpdateDailyExpenseInfo(DailyExpense objDailyExpenseInfo) { int noRowCount = 0; objDataAccess = DataAccess.NewDataAccess(); objDbCommand = objDataAccess.GetCommand(true, IsolationLevel.Serializable); objDbCommand.AddInParameter("DailyExpenseId", objDailyExpenseInfo.DailyExpenseId); objDbCommand.AddInParameter("ExpenseDetailId", objDailyExpenseInfo.ExpenseDetailId); objDbCommand.AddInParameter("TotalAmount", objDailyExpenseInfo.TotalAmount); objDbCommand.AddInParameter("PaidAmount", objDailyExpenseInfo.PaidAmount); objDbCommand.AddInParameter("DueAmount", objDailyExpenseInfo.DueAmount); objDbCommand.AddInParameter("Date", objDailyExpenseInfo.Date); objDbCommand.AddInParameter("IsActive", objDailyExpenseInfo.IsActive); objDbCommand.AddInParameter("UpdatedBy", SessionUtility.STSessionContainer.UserID); try { noRowCount = objDataAccess.ExecuteNonQuery(objDbCommand, "[dbo].uspUpdateDailyExpense", CommandType.StoredProcedure); if (noRowCount > 0) { objDbCommand.Transaction.Commit(); return("Save Successfully"); } else { objDbCommand.Transaction.Rollback(); return("Save Failed"); } } catch (Exception ex) { objDbCommand.Transaction.Rollback(); throw new Exception("Database Error Occured", ex); } finally { objDataAccess.Dispose(objDbCommand); } }
public List <DailyExpense> GetAllDailyExpenseInfo() { objDataAccess = DataAccess.NewDataAccess(); objDbCommand = objDataAccess.GetCommand(true, IsolationLevel.ReadCommitted); DbDataReader objDbDataReader = null; List <DailyExpense> objDailyExpenseList = new List <DailyExpense>(); DailyExpense objDailyExpense; try { //objDbCommand.AddInParameter("CreatedBy", SessionUtility.TBSessionContainer.UserID); objDbDataReader = objDataAccess.ExecuteReader(objDbCommand, "[dbo].uspGetDailyExpenseList", CommandType.StoredProcedure); if (objDbDataReader.HasRows) { while (objDbDataReader.Read()) { objDailyExpense = new DailyExpense(); this.BuildModelForDailyExpense(objDbDataReader, objDailyExpense); objDailyExpenseList.Add(objDailyExpense); } } } catch (Exception ex) { throw new Exception("Error : " + ex.Message); } finally { if (objDbDataReader != null) { objDbDataReader.Close(); } objDataAccess.Dispose(objDbCommand); } return(objDailyExpenseList); }
public IActionResult Put(int id, [FromBody] DailyExpense value) { if (value == null) { throw new WebApiException("Request Object was NULL", HttpStatusCode.BadRequest); } var spentItem = _context.DailyExpenses.Find(id); if (spentItem == null) { throw new WebApiException($"Daily Expense for {id} does not exists!!", HttpStatusCode.NotFound); } //Assign Values // Use AutoMapper if more properties spentItem.Amount = value.Amount; spentItem.Description = value.Description; spentItem.SpentOn = value.SpentOn; _context.Update(spentItem); Save(); return(NoContent()); }
public async Task <dynamic> AddComponentAsync(AddDailyExpense[] addComponents, int instituteId) { var oldEntries = await iMSDbContext.DailyExpenses.Where(x => x.MessManageId == addComponents[0].MessManageId && x.ExpenseTypeId == addComponents[0].ExpenseTypeId && x.InstituteId == instituteId).ToListAsync(); iMSDbContext.RemoveRange(oldEntries); await iMSDbContext.SaveChangesAsync(); var results = new List <dynamic>(); foreach (AddDailyExpense addComponent in addComponents) { if (!string.IsNullOrEmpty(addComponent.BillNo) && !string.IsNullOrEmpty(addComponent.Particulars) && addComponent.Amount != 0) { var dailyExpense = new DailyExpense() { InstituteId = instituteId, MessManageId = addComponent.MessManageId, ExpenseTypeId = addComponent.ExpenseTypeId, Amount = addComponent.Amount, Description = addComponent.Description, BillNo = addComponent.BillNo, ProofUrl = addComponent.ProofUrl, Particulars = addComponent.Particulars, Date = addComponent.Date }; iMSDbContext.DailyExpenses.Add(dailyExpense); await iMSDbContext.SaveChangesAsync(); results.Add(dailyExpense); } else { results.Add(addComponent); } } return(new { HasError = false, Result = results, Message = "Daily Expenses added successfully" }); }
public ActionResult DailyExpenseView(DailyExpenseViewModel model, DateTime Day) { var k = Day.Month; var month = DateTimeFormatInfo.CurrentInfo.GetMonthName(k); model.budgetdetail = db.monthlyBudget.Where(b => b.BudgetMonth == month).ToList(); // model.dailyexpensedetail = db.dailyExpense.Where(b => b.Day.Month == Day.Month).ToList(); //model.budgetdetail = db.monthlyBudget; // model.budgetdetail = db.monthlyBudget.Where(s => s.BudgetMonth == BudgetMonth).ToList() ; //model.dailyexpensedetail.Reverse(); ItemCategory newItem = new ItemCategory(); newItem = db.itemCategory.FirstOrDefault(x => x.Id == model.ItemCategoryId); var matchcCategory = newItem.CategoryId; MonthlyBudget newBudget = new MonthlyBudget(); newBudget = db.monthlyBudget.FirstOrDefault(y => y.CategoryId == matchcCategory && y.BudgetMonth == month); var s = DateTime.ParseExact(newBudget.BudgetMonth, "MMMM", System.Globalization.CultureInfo.InvariantCulture).Month; if (model.Day.Month == s) { newBudget.ActualAmount += model.Amount; newBudget.Difference = newBudget.BudgetAmount - newBudget.ActualAmount; } //MonthlyBudget budget1 = db.monthlyBudget.FirstOrDefault(s => s.BudgetMonth.Month == BudgetMonth.Month); //model.dailyexpensedetail = db.dailyExpense; ////model.dailyexpensedetail.Reverse(); //model.budgetdetail = db.monthlyBudget; //ItemCategory newItem = new ItemCategory(); //newItem = db.itemCategory.FirstOrDefault(x => x.Id == model.ItemCategoryId); //var matchcCategory = newItem.CategoryId; //MonthlyBudget newBudget = new MonthlyBudget(); //newBudget = db.monthlyBudget.FirstOrDefault(y => y.CategoryId == matchcCategory); //if (model.Day.Month == newBudget.BudgetMonth.Month) //{ // newBudget.ActualAmount += model.Amount; // newBudget.Difference = newBudget.BudgetAmount - newBudget.ActualAmount; //} Category newCategory = new Category(); var categoryNameList = db.category.Select(a => a).ToList(); foreach (var item in categoryNameList) { var categoryName = db.category.FirstOrDefault(z => z.Id == matchcCategory); model.CategoryName = categoryName.CategoryName; } model.BudgetAmount = newBudget.BudgetAmount; model.ActualAmount = newBudget.ActualAmount; // model.Difference = newBudget.Difference; model.BudgetMonth = newBudget.BudgetMonth; var budgetList = db.monthlyBudget.Select(b => b).ToList(); foreach (var item in budgetList) { item.Difference = item.BudgetAmount - item.ActualAmount; model.Difference = item.Difference; } var budgettal1 = db.monthlyBudget.Where(a => a.BudgetMonth == month).Select(l => l.BudgetAmount).ToList(); // var budgetall = db.monthlyBudget.Select(a => a.BudgetAmount).ToList(); for (var i = 0; i < budgettal1.Count; i++) { model.TotalBudget += budgettal1[i]; } var newExpense = new DailyExpense { Day = model.Day, ItemCategoryId = model.ItemCategoryId, Amount = model.Amount }; db.dailyExpense.Add(newExpense); db.SaveChanges(); var budgetall1 = db.monthlyBudget.Where(a => a.BudgetMonth == month).Select(a => a.ActualAmount).ToList(); for (var i = 0; i < budgetall1.Count; i++) { model.TotalActual += budgetall1[i]; } model.TotalDifference = model.TotalBudget - model.TotalActual; model.dailyexpensedetail = db.dailyExpense.Where(b => b.Day.Month == Day.Month).ToList(); ModelState.Clear(); ViewBag.ItemCategoryId = new SelectList(db.itemCategory, "Id", "ItemName", model.ItemCategoryId); return(View(model)); }
public IHttpActionResult AddAdditionAmount(AdditionalExpenseRequest additionalExpenseRequest) { if (ModelState.IsValid) { int currentWeek = HelperFunctions.HelperFunctions.CurrentWeekNumber; int currentMonth = DateTime.UtcNow.Month; int currentYear = DateTime.UtcNow.Year; int userDataid = additionalExpenseRequest.UserDataID; int toCategoryID = db.Categories.Where(e => e.CategoryName.Equals(additionalExpenseRequest.ToCategory)).FirstOrDefault().CategoryID; if (additionalExpenseRequest.IsFromCategory) { int fromCategoryID = db.Categories.Where(e => e.CategoryName.Equals(additionalExpenseRequest.FromCategory)).FirstOrDefault().CategoryID; #region subtract_amount_from selected category // Create a new entry for DailyExpense DailyExpense dailyExpense = new DailyExpense(); dailyExpense.UserDataID = userDataid; dailyExpense.CategoryID = fromCategoryID; dailyExpense.Amount = additionalExpenseRequest.AmountToAdd; dailyExpense.CurrentWeek = currentWeek; dailyExpense.CurrentMonth = currentMonth; dailyExpense.CurrentYear = currentYear; dailyExpense.DateCreated = DateTime.UtcNow; dailyExpense.DateModified = DateTime.UtcNow; // Update WeeklySaving - Subtract the daily expense amount from the total amount for that category WeeklySaving weeklySavingfromCategory = db.WeeklySavings.Where(e => e.UserDataID == userDataid && e.CategoryID == fromCategoryID && e.CurrentMonth == currentMonth && e.CurrentYear == currentYear && e.CurrentWeek == currentWeek).FirstOrDefault(); if (weeklySavingfromCategory != null) { weeklySavingfromCategory.Amount -= additionalExpenseRequest.AmountToAdd; if (this.WeeklyExpenseForUserExists(userDataid, toCategoryID)) { WeeklyExpenseDetail weeklyExpenseDetail = db.WeeklyExpenseDetails.Where(e => e.UserDataID == userDataid && e.CategoryID == fromCategoryID).FirstOrDefault(); if (weeklyExpenseDetail != null) { // Update WeeklyExpenseDetails with new reset values weeklyExpenseDetail.Amount -= additionalExpenseRequest.AmountToAdd; weeklyExpenseDetail.DateModified = DateTime.UtcNow; db.Entry(weeklyExpenseDetail).State = EntityState.Modified; } else { return(BadRequest()); } } } else { return(BadRequest()); } #endregion } #region add amount to requested category if (this.WeeklyExpenseForUserExists(userDataid, toCategoryID)) { WeeklyExpenseDetail weeklyExpenseDetail = db.WeeklyExpenseDetails.Where(e => e.UserDataID == userDataid && e.CategoryID == toCategoryID).FirstOrDefault(); if (weeklyExpenseDetail != null) { // Update WeeklyExpenseDetails with new reset values weeklyExpenseDetail.Amount += additionalExpenseRequest.AmountToAdd; weeklyExpenseDetail.DateModified = DateTime.UtcNow; db.Entry(weeklyExpenseDetail).State = EntityState.Modified; // Check WeeklySavngs exits WeeklySaving weeklySavingsToUpdate = db.WeeklySavings.Where(e => e.UserDataID == userDataid && e.CategoryID == toCategoryID).FirstOrDefault(); if (weeklySavingsToUpdate != null) { weeklySavingsToUpdate.Amount += additionalExpenseRequest.AmountToAdd; weeklyExpenseDetail.DateModified = DateTime.UtcNow; db.Entry(weeklySavingsToUpdate).State = EntityState.Modified; try { db.SaveChanges(); return(Ok(true)); } catch (DbUpdateConcurrencyException) { throw; } } else { return(BadRequest()); } } else { return(BadRequest()); } } else { return(BadRequest()); } #endregion } else { return(BadRequest()); } }
private void BuildModelForDailyExpense(DbDataReader objDataReader, DailyExpense objDailyExpense) { DataTable objDataTable = objDataReader.GetSchemaTable(); foreach (DataRow dr in objDataTable.Rows) { String column = dr.ItemArray[0].ToString(); switch (column) { case "DailyExpenseId": if (!Convert.IsDBNull(objDataReader["DailyExpenseId"])) { objDailyExpense.DailyExpenseId = Convert.ToInt32(objDataReader["DailyExpenseId"]); } break; case "ExpenseDetailId": if (!Convert.IsDBNull(objDataReader["ExpenseDetailId"])) { objDailyExpense.ExpenseDetailId = Convert.ToInt16(objDataReader["ExpenseDetailId"].ToString()); } break; case "ExpenseType": if (!Convert.IsDBNull(objDataReader["ExpenseType"])) { objDailyExpense.ExpenseType = objDataReader["ExpenseType"].ToString(); } break; case "TotalAmount": if (!Convert.IsDBNull(objDataReader["TotalAmount"])) { objDailyExpense.TotalAmount = Convert.ToDouble(objDataReader["TotalAmount"].ToString()); } break; case "PaidAmount": if (!Convert.IsDBNull(objDataReader["PaidAmount"])) { objDailyExpense.PaidAmount = Convert.ToDouble(objDataReader["PaidAmount"].ToString()); } break; case "DueAmount": if (!Convert.IsDBNull(objDataReader["DueAmount"])) { objDailyExpense.DueAmount = Convert.ToDouble(objDataReader["DueAmount"].ToString()); } break; case "Date": if (!Convert.IsDBNull(objDataReader["Date"])) { objDailyExpense.Date = Convert.ToDateTime(objDataReader["Date"].ToString()); } break; case "IsActive": if (!Convert.IsDBNull(objDataReader["IsActive"])) { objDailyExpense.IsActive = Convert.ToBoolean(objDataReader["IsActive"].ToString()); } break; case "UserStatus": if (!Convert.IsDBNull(objDataReader["UserStatus"])) { objDailyExpense.UserStatus = objDataReader["UserStatus"].ToString(); } break; case "CreatedBy": if (!Convert.IsDBNull(objDataReader["CreatedBy"])) { objDailyExpense.CreatedBy = Convert.ToInt16(objDataReader["CreatedBy"]); } break; case "CreatedDate": if (!Convert.IsDBNull(objDataReader["CreatedDate"])) { objDailyExpense.CreatedDate = Convert.ToDateTime(objDataReader["CreatedDate"].ToString()); } break; case "UpdatedBy": if (!Convert.IsDBNull(objDataReader["UpdatedBy"])) { objDailyExpense.UpdatedBy = Convert.ToInt16(objDataReader["UpdatedBy"].ToString()); } break; case "UpdatedDate": if (!Convert.IsDBNull(objDataReader["UpdatedDate"])) { objDailyExpense.UpdatedDate = Convert.ToDateTime(objDataReader["UpdatedDate"].ToString()); } break; case "SortedBy": if (!Convert.IsDBNull(objDataReader["SortedBy"])) { objDailyExpense.SortedBy = Convert.ToByte(objDataReader["SortedBy"].ToString()); } break; case "Remarks": if (!Convert.IsDBNull(objDataReader["Remarks"])) { objDailyExpense.Remarks = objDataReader["Remarks"].ToString(); } break; default: break; } } }
public bool AddDailyExpense(DailyExpense de) { return(db.AddDailyExpense(de)); }
public IHttpActionResult AddUserDailyExpense(AddExpense addExpenseModel) { DailyExpense dailyExpense = new DailyExpense(); // Fetch category id from category name int categoryID = db.Categories.Where(e => e.CategoryName.Equals(addExpenseModel.Category)).FirstOrDefault().CategoryID; int week = HelperFunctions.HelperFunctions.CurrentWeekNumber; int month = DateTime.UtcNow.Month; int year = DateTime.UtcNow.Year; // Create a new entry for DailyExpense dailyExpense.UserDataID = addExpenseModel.UserDataID; dailyExpense.CategoryID = categoryID; dailyExpense.Amount = addExpenseModel.Amount; dailyExpense.CurrentWeek = week; dailyExpense.CurrentMonth = month; dailyExpense.CurrentYear = year; dailyExpense.DateCreated = DateTime.UtcNow; dailyExpense.DateModified = DateTime.UtcNow; // Update WeeklySaving - Subtract the daily expense amount from the total amount for that category WeeklySaving weeklySaving = db.WeeklySavings.Where(e => e.UserDataID == addExpenseModel.UserDataID && e.CategoryID == categoryID && e.CurrentMonth == month && e.CurrentYear == year && e.CurrentWeek == week).FirstOrDefault(); if (weeklySaving != null && weeklySaving.Amount != 0.00m && weeklySaving.Amount >= addExpenseModel.Amount) { weeklySaving.Amount -= addExpenseModel.Amount; } else { return(BadRequest()); } if (ModelState.IsValid) { DailyExpenseReturnModel dailyExpenseReturnModel = new DailyExpenseReturnModel(); // Saves data in DB db.Entry(weeklySaving).State = EntityState.Modified; _ = db.DailyExpenses.Add(dailyExpense); db.SaveChanges(); dailyExpenseReturnModel.isDatabaseUpdated = true; // Verifies if weekly limit is reached WeeklyExpenseDetail weeklyExpenseDetail = db.WeeklyExpenseDetails.Where(e => e.UserDataID == addExpenseModel.UserDataID && e.CategoryID == categoryID).FirstOrDefault(); if (this.VerifyThresholdNotReached(weeklyExpenseDetail.Amount, weeklySaving.Amount)) { dailyExpenseReturnModel.hasThresholdReached = false; } else { dailyExpenseReturnModel.hasThresholdReached = true; } return(Ok(dailyExpenseReturnModel)); } else { return(BadRequest()); } }