public JsonResult ToggleTimeTracking([FromBody] TimeTrackingViewModel vm) { if (ModelState.IsValid) { TimeTracking runningTimeTracking = _repository.GetRunningTimeTracking(User.Identity.Name); TimeTracking newTimeTracking; if (runningTimeTracking == null) { if (vm.TaskId != 0) { newTimeTracking = new TimeTracking { UserName = User.Identity.Name, Task = _repository.GetTaskById(vm.TaskId, User.Identity.Name), StartTime = DateTime.UtcNow }; } else if (vm.Description != null) { newTimeTracking = new TimeTracking { UserName = User.Identity.Name, Description = vm.Description, StartTime = DateTime.UtcNow }; } else { newTimeTracking = new TimeTracking { UserName = User.Identity.Name, StartTime = DateTime.UtcNow }; } TimeTracking saved = _repository.AddTimeTrackingEntry(newTimeTracking); if (_repository.SaveAll()) { return Json(Mapper.Map<TimeTrackingViewModel>(_repository.GetTimeTrackingById(saved.Id, User.Identity.Name))); } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { error = "Starting a new timetracking entry failed." }); } } else { TimeTracking original = _repository.GetTimeTrackingById(runningTimeTracking.Id, User.Identity.Name); original.EndTime = DateTime.UtcNow; // User wants to just stop time if (runningTimeTracking.Id == vm.Id) { if (_repository.SaveAll()) { return Json(Mapper.Map<TimeTrackingViewModel>(original)); } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { error = "Stopping an existing timetracking entry failed." }); } } else // User has started new time tracking, stop old one and start new { if (vm.TaskId != 0) { newTimeTracking = new TimeTracking { UserName = User.Identity.Name, Task = _repository.GetTaskById(vm.TaskId, User.Identity.Name), StartTime = DateTime.UtcNow }; } else if (vm.Description != null) { newTimeTracking = new TimeTracking { UserName = User.Identity.Name, Description = vm.Description, StartTime = DateTime.UtcNow }; } else { newTimeTracking = new TimeTracking { UserName = User.Identity.Name, StartTime = DateTime.UtcNow }; } TimeTracking saved = _repository.AddTimeTrackingEntry(newTimeTracking); if (_repository.SaveAll()) { return Json(Mapper.Map<TimeTrackingViewModel>(_repository.GetTimeTrackingById(saved.Id, User.Identity.Name))); } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { error = "Stopping old and starting a new timetracking entry failed." }); } } } } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { error = "Viewmodel was not valid." }); } }
/* Timetracking */ public TimeTracking AddTimeTrackingEntry(TimeTracking timeTracking) { return _context.TimeTracking.Add(timeTracking).Entity; }