public ActionResult InsertSavingsGoal(SavingsGoalsViewModel model) { SavingsGoal newSavingsGoal = new SavingsGoal(); newSavingsGoal = model.savingsGoal; newSavingsGoal.ClientID = CLIENT_ID; newSavingsGoal.SavingsPointValue = 0; newSavingsGoal.Status = "Active"; if (newSavingsGoal.SavingGoalID == 0) { newSavingsGoal.StartDate = model.savingsGoal.StartDate; newSavingsGoal.CurrentGoalAmount = 0; newSavingsGoal.SavingsGoalAmount = model.savingsGoal.SavingsGoalAmount; newSavingsGoal.EndDate = model.savingsGoal.EndDate; newSavingsGoal.GoalDescription = model.savingsGoal.GoalDescription; newSavingsGoal.Recurring = model.savingsGoal.Recurring; dbContext.SavingsGoals.Add(newSavingsGoal); ModelState.Remove("savingsGoal.SavingGoalId"); //remove the error saying that this id is needed, when it will be automatically generated on insert } else { dbContext.Entry(newSavingsGoal).State = EntityState.Modified; } if (ModelState.IsValid) { dbContext.SaveChanges(); return(RedirectToAction("index")); } return(View(model)); }
static void testSGReadModifyRewrite(long SGID) { Console.WriteLine("\n\n-------------------- Test: Recreate, Modify, Rewrite Existing SavingsGoal --------------------"); // Reinstantiate a SavingsGoal from DB records SavingsGoalService sgService = new SavingsGoalService(); SavingsGoal existingGoal = sgService.getUsingID(SGID); // Print summary of goal that was just reinstantiated Console.WriteLine("Savings Goal Summary:\n---------------------"); Console.WriteLine(existingGoal + "\n"); // Modify the payment period, system recalculates end date, redisplay summary existingGoal.updatePeriod(contrPeriod.Weekly); Console.WriteLine("Savings Goal Summary:\n---------------------"); Console.WriteLine(existingGoal + "\n"); // Modify the payment amound to half, system recalculates number of payment periods needed and end date, redisplay summary existingGoal.updateContrAmt(existingGoal.contrAmt * 2); Console.WriteLine("Savings Goal Summary:\n---------------------"); Console.WriteLine(existingGoal + "\n"); // Rewrite the modified goal to DB sgService.update(existingGoal); }
public void checkGoalStatus() { List <SavingsGoal> passedGoalDate = dbContext.SavingsGoals.Where(x => x.EndDate <= DateTime.Now && x.Status.Trim().ToUpper() == "ACTIVE").ToList(); foreach (SavingsGoal goal in passedGoalDate) { if (goal.CurrentGoalAmount == goal.SavingsGoalAmount) { goal.Status = "Success"; } else { goal.Status = "Fail"; } if (goal.Recurring.Trim().ToUpper() == "YES") { SavingsGoal newSavingGoal = new SavingsGoal(); newSavingGoal.Status = "Active"; newSavingGoal.StartDate = goal.StartDate.AddMonths(1); newSavingGoal.EndDate = goal.EndDate.AddMonths(1); newSavingGoal.GoalDescription = goal.GoalDescription; newSavingGoal.Recurring = goal.Recurring; newSavingGoal.SavingsGoalAmount = goal.SavingsGoalAmount; newSavingGoal.CurrentGoalAmount = 0; newSavingGoal.ClientID = goal.ClientID; newSavingGoal.SavingsPointValue = 0; dbContext.SavingsGoals.Add(newSavingGoal); } } dbContext.SaveChanges(); }
public ActionResult AddFunds(int?id) { if (Session["UserID"] == null) { return(RedirectToAction("Login", "Home")); } else { CLIENT_ID = int.Parse(Session["UserID"].ToString()); } if (id == null) //Only allow updates to a valid goal { return(RedirectToAction("index")); } SavingsGoal goal = dbContext.SavingsGoals.Where(x => x.ClientID == CLIENT_ID && x.SavingGoalID == id).FirstOrDefault(); if (goal == null) //allow only valid updates { return(RedirectToAction("index")); } SavingsGoalsViewModel model = new SavingsGoalsViewModel(); model.clientTransaction = new HomeController().getTransactionInfo(); //get total amount available on each client's accounts model.savingsGoal = goal; return(View(model)); }
public IActionResult Add() { var model = new SavingsGoal() { HasDeadline = false, }; return(View(model)); }
static void testSGShowJSON(SavingsGoal sg) { Console.WriteLine("\n\n-------------------- Test: Display JSON of SavingsGoal Object --------------------"); // Print the JSON representation of the goal we created SavingsGoalService sgService = new SavingsGoalService(); Console.WriteLine(sgService.getJSON(sg)); }
public async Task <IActionResult> Edit(SavingsGoal goal) { if (ModelState.IsValid) { _repo.Edit <SavingsGoal>(goal); if (await _repo.SaveAll()) { return(RedirectToAction("Goals")); } } return(View(goal)); }
public async Task <float> CalculateProgress(SavingsGoal goal) { var savings = await _context.Savings .Where(x => x.SavingsGoalId == goal.Id) .ToListAsync(); float totalAdditions = savings.Where(x => x.Type == Models.Type.Addition) .Select(x => x.Amount) .Sum(); float totalSubtractions = savings.Where(x => x.Type == Models.Type.Subtraction) .Select(x => x.Amount) .Sum(); return((totalAdditions - totalSubtractions) / goal.Amount * 100); }
static void testSGShowSerialize(SavingsGoal sg) { Console.WriteLine("\n\n-------------------- Test: Display String Serialization of SavingsGoal Object --------------------"); // Serialize the runtime object to String[] SavingsGoalService sgService = new SavingsGoalService(); string[] serialized = sgService.serialize(sg); Console.WriteLine("\nSavingsGoal Serialized:\n-----------------------\n"); // Print the serialized SavingsGoal foreach (string attr in serialized) { Console.WriteLine(" " + attr); } }
public IActionResult CreateByID(string apiKey, [FromBody] JsonElement reqBody) { if (!api.validAPIKey(apiKey)) { return(new UnauthorizedObjectResult("Invalid API key")); } long SGID = sgs.getNextAvailID(); // Validate that the POST request contains all necessary attributes to create a NEW SavingsGoal and nothing more Dictionary <string, object> req = JsonConvert.DeserializeObject <Dictionary <string, object> >(Convert.ToString(reqBody)); HashSet <string> reqAttributes = new HashSet <string>(req.Keys); if (!reqAttributes.SetEquals(createCustomAttrs)) { return(BadRequest("Invalid attribute(s) in request body")); } // Create the SavingsGoal with the given SGID using the POST payload SavingsGoal s; try { s = new SavingsGoal( SGID: SGID, accID: Convert.ToInt64(req["AccountID"]), Convert.ToString(req["Name"]), goalAmt: Convert.ToDecimal(req["GoalAmt"]), period: sgs.castPeriod(Convert.ToString(req["Period"])), startDate: Convert.ToDateTime(req["StartDate"]), endDate: Convert.ToDateTime(req["EndDate"]) ); } catch { return(BadRequest()); } // Write the new SavingsGoal sgs.write(s); return(api.serveJson(sgs.getJSON(s))); }
public async Task <IActionResult> Add(SavingsGoal model) { if (ModelState.IsValid) { var goals = await _repo.GetList <SavingsGoal>(); if (!goals.Any()) { model.IsPinned = true; } _repo.Add <SavingsGoal>(model); if (await _repo.SaveAll()) { return(RedirectToAction("Goals")); } throw new Exception("Something went wrong, trying to add new Savings Goal"); } return(View(model)); }
static SavingsGoal testSGCreateByContrAmt() { Console.WriteLine("\n\n-------------------- Test: Creating A New Savings Goal By Contribution Amount, Write --------------------"); // Query DB for the next avail ID SavingsGoalService sgService = new SavingsGoalService(); long SGID = sgService.getNextAvailID(); Console.WriteLine("Next available SGID that can be assigned: " + SGID + "\n"); // Create a new Savings Goal for the amount of $300 dynamically calculate end date DateTime endDate = new DateTime(2021, 12, 20, 0, 0, 0).Date; SavingsGoal sampleGoal = new SavingsGoal(SGID, 2, "Tuition", (decimal)3425.00, contrPeriod.Weekly, (decimal)325.00); // Print summary of goal that was just created Console.WriteLine("Savings Goal Summary:\n---------------------"); Console.WriteLine(sampleGoal); // Write SavingsGoal object to DB sgService.write(sampleGoal); return(sampleGoal); }
// --------------------------------------------------- Begin Savings Goal Testing --------------------------------------------------- static SavingsGoal testSGCreateByDate() { Console.WriteLine("\n-------------------- Test: Creating A New Savings Goal By End Date, Write --------------------"); // Query DB for the next avail ID SavingsGoalService sgService = new SavingsGoalService(); long SGID = sgService.getNextAvailID(); Console.WriteLine("Next available SGID that can be assigned: " + SGID + "\n"); // Create a new Savings Goal for the amount of $150 ending on December 20th, dynamically calculate payments DateTime endDate = new DateTime(2021, 12, 20, 0, 0, 0).Date; SavingsGoal sampleGoal = new SavingsGoal(SGID, 2, "Christmas Gift", (decimal)150.00, contrPeriod.Monthly, endDate); // Print summary of goal that was just created Console.WriteLine("Savings Goal Summary:\n---------------------"); Console.WriteLine(sampleGoal); // Write SavingsGoal object to DB sgService.write(sampleGoal); return(sampleGoal); }
public ActionResult AddFunds(SavingsGoalsViewModel model) { if (model.addToGoal + model.savingsGoal.CurrentGoalAmount > model.savingsGoal.SavingsGoalAmount) { //Trying to add more than specified goal amount error ModelState.AddModelError("addToGoal", "The amount you want to add cannot exceed the savings goal limit."); } if (model.addToGoal <= 0) { //less than 0 transaction error ModelState.AddModelError("addToGoal", "The amount you want to enter cannot be less than 0."); } if (model.addToGoal > dbContext.Transactions.Where(x => x.TransactionAccountNo == model.transaction.TransactionAccountNo).Sum(x => x.TransactionAmount)) { //prevents user from overdrafting ModelState.AddModelError("addToGoal", "The amount you want to enter cannot exceed account balance."); } SavingsGoal goal = dbContext.SavingsGoals.Where(x => x.SavingGoalID == model.savingsGoal.SavingGoalID).FirstOrDefault(); if (goal == null) { //error getting goal to update ModelState.AddModelError("addToGoal", "Error trying to add to this goal."); } if (ModelState.IsValid) { Transaction trans = new Transaction(); trans.TransactionAccountNo = model.transaction.TransactionAccountNo; trans.TransactionAmount = model.addToGoal * -1; trans.TransactionDate = DateTime.Now; trans.Description = "Added to goal: " + model.savingsGoal.GoalDescription; trans.CategoryID = 17; goal.CurrentGoalAmount = goal.CurrentGoalAmount + model.addToGoal; if (goal.CurrentGoalAmount >= goal.SavingsGoalAmount) //User just achieved goal { goal.Status = "Success"; TimeSpan difference = goal.EndDate.Subtract(DateTime.Now); TempData["SuccessTitle"] = "Congratulations! \"" + goal.GoalDescription + "\" Completed!"; TempData["SuccessBody"] = "You just achieved your goal of saving " + goal.CurrentGoalAmount + " by " + goal.EndDate.ToLongDateString() + ". You finished this " + difference.Days + " Days before your target date!"; if (goal.Recurring.Trim().ToUpper() == "YES") { SavingsGoal newSavingGoal = new SavingsGoal(); newSavingGoal.Status = "Active"; newSavingGoal.StartDate = goal.StartDate.AddMonths(1); newSavingGoal.EndDate = goal.EndDate.AddMonths(1); newSavingGoal.GoalDescription = goal.GoalDescription; newSavingGoal.Recurring = goal.Recurring; newSavingGoal.SavingsGoalAmount = goal.SavingsGoalAmount; newSavingGoal.CurrentGoalAmount = 0; newSavingGoal.ClientID = goal.ClientID; newSavingGoal.SavingsPointValue = 0; dbContext.SavingsGoals.Add(newSavingGoal); } } dbContext.Transactions.Add(trans); dbContext.SaveChanges(); return(RedirectToAction("index")); } //repopluate the transactions for the dropdown list model.clientTransaction = new HomeController().getTransactionInfo(); return(View(model)); }
public IActionResult UpdateByID(long SGID, string apiKey, [FromBody] JsonElement reqBody) { if (!api.validAPIKey(apiKey)) { return(new UnauthorizedObjectResult("Invalid API key")); } if (SGID < 1) { return(BadRequest("Invalid SGID specified")); } // Validate the attributes of the PATCH request, each attribute specified // in the request must be an attribute of a SavingsGoal Dictionary <string, object> req = JsonConvert.DeserializeObject <Dictionary <string, object> >(Convert.ToString(reqBody)); HashSet <string> reqAttributes = new HashSet <string>(req.Keys); if (!api.validAttributes(updateableAttrs, reqAttributes)) { return(BadRequest("Invalid attribute(s) in request body")); } SavingsGoal s = sgs.getUsingID(SGID); // Http PATCH cannot update a SavingsGoal that does not exist if (s == null) { return(NotFound("Cannot update a SavingsGoal that does not exist!")); } // PATCH request body should pass no more than a single attribute unless: // Updating GoalAmt, in which a boolean ExtendDate should be passed // Updating ContrAmt AND Period simultaneously try { if (reqAttributes.Contains("GoalAmt")) { // Updating Goal Amount must also specify ExtendDate if (!reqAttributes.SetEquals(updateGoalAmt)) { return(BadRequest("Invalid attribute(s) in request body, expected exactly { GoalAmt, ExtendDate }")); } s.updateGoalAmt(Convert.ToDecimal(req["GoalAmt"]), Convert.ToBoolean(req["ExtendDate"])); } else if (reqAttributes.Contains("ContrAmt")) { // Update Contribution Amount and Period simultaneously if (reqAttributes.Count > 1) { if (!reqAttributes.SetEquals(updateContrAmt)) { return(BadRequest("Invalid attribute(s) in request body, expected exactly { ContrAmt, Period }")); } s.updateContrAmtAndPeriod(Convert.ToDecimal(req["ContrAmt"]), sgs.castPeriod(Convert.ToString(req["Period"]))); } // Update just Contribution Amount else { s.updateContrAmt(Convert.ToDecimal(req["ContrAmt"])); } } // All other attributes should specify only a single value else { if (reqAttributes.Count != 1) { return(BadRequest("Invalid attribute(s) in request body, expected only one of the following: { Name, Period, EndDate }")); } if (reqAttributes.Contains("Name")) { s.updateName(Convert.ToString(req["Name"])); } else if (reqAttributes.Contains("Period")) { s.updatePeriod(sgs.castPeriod(Convert.ToString(req["Period"]))); } else if (reqAttributes.Contains("EndDate")) { s.updateEndDate(Convert.ToDateTime(req["EndDate"])); } } } catch (Exception e) { Console.WriteLine(e.ToString()); return(BadRequest()); } // Write changes, if any sgs.update(s); return(api.serveJson(sgs.getJSON(s))); }
public IActionResult CreateByID(long SGID, string apiKey, [FromBody] JsonElement reqBody) { if (!api.validAPIKey(apiKey)) { return(new UnauthorizedObjectResult("Invalid API key")); } if (SGID < 1) { return(BadRequest("Invalid SGID specified")); } // Validate that the POST request contains all necessary attributes to create a NEW SavingsGoal and nothing more Dictionary <string, object> req = JsonConvert.DeserializeObject <Dictionary <string, object> >(Convert.ToString(reqBody)); HashSet <string> reqAttributes = new HashSet <string>(req.Keys); bool createByDate = reqAttributes.SetEquals(createDateAttrs); bool createByContr = reqAttributes.SetEquals(createContrAttrs); if (!createByDate && !createByContr) { return(BadRequest("Invalid attribute(s) in request body")); } // POST should be used only to create a new SavingsGoal, not allowed if SavingsGoal with given SGID already exists SavingsGoal s = sgs.getUsingID(SGID); if (s != null) { return(Conflict($"A SavingsGoal already exists with SGID {SGID}")); } // Create the SavingsGoal with the given SGID using the POST payload try { // Create a SavingsGoal by a specified end date if (createByDate) { s = new SavingsGoal( SGID: SGID, accID: Convert.ToInt64(req["AccountID"]), Convert.ToString(req["Name"]), goalAmt: Convert.ToDecimal(req["GoalAmt"]), period: sgs.castPeriod(Convert.ToString(req["Period"])), endDate: Convert.ToDateTime(req["EndDate"]) );; } // Create a SavingsGoal by a specified contribution amount else { s = new SavingsGoal( SGID: SGID, accID: Convert.ToInt64(req["AccountID"]), Convert.ToString(req["Name"]), goalAmt: Convert.ToDecimal(req["GoalAmt"]), period: sgs.castPeriod(Convert.ToString(req["Period"])), contrAmt: Convert.ToDecimal(req["ContrAmt"]) ); } } catch { return(BadRequest()); } // Write the new SavingsGoal sgs.write(s); return(api.serveJson(sgs.getJSON(s))); }