public async Task <IActionResult> CreateWorkPeriodAsync([FromBody] WorkPeriodInDTO workPeriodInDTO) { if (workPeriodInDTO == null) { return(BadRequest()); } var departmentModel = await _unitOfWork.Departments.GetByIdAsync(workPeriodInDTO.DepartmentId); if (departmentModel == null) { return(BadRequest("You must create a department before creating a work period.")); } if (ModelState.IsValid) { var workPeriodModel = _mapper.Map <WorkPeriod>(workPeriodInDTO); workPeriodModel.Active = true; await _unitOfWork.WorkPeriods.AddAsync(workPeriodModel); await _unitOfWork.CompleteAsync(); var workPeriodOutDTO = _mapper.Map <WorkPeriodOutDTO>(workPeriodModel); if (workPeriodModel.UserWorkPeriods != null) { var userWorkPeriods = workPeriodModel.UserWorkPeriods.ToList(); var userWorkPeriodDTOs = new List <UserWorkPeriodDTO>(); for (int i = 0; i < userWorkPeriods.Count; i++) { userWorkPeriodDTOs.Add(_mapper.Map <UserWorkPeriodDTO>(userWorkPeriods[i])); } workPeriodOutDTO.UserWorkPeriods = userWorkPeriodDTOs; } workPeriodOutDTO = _mapper.Map <WorkPeriodOutDTO>(await _unitOfWork.WorkPeriods.GetByIdAsync(workPeriodOutDTO.Id)); return(CreatedAtRoute("GetWorkPeriod", new { id = workPeriodOutDTO.Id }, workPeriodOutDTO)); } else { return(BadRequest("Please fill all the required fields.")); } }
public async Task <IActionResult> UpdateAsync(long id, WorkPeriodInDTO newWorkPeriodDTO) { var oldWorkPeriodModel = await _unitOfWork.WorkPeriods.GetByIdAsync(id); if (oldWorkPeriodModel == null) { return(NotFound($"Work period {id} could not be found.")); } if (oldWorkPeriodModel.DepartmentId != newWorkPeriodDTO.DepartmentId) { return(BadRequest($"Please create a new work period for department {newWorkPeriodDTO.DepartmentId}. This instance belongs to {oldWorkPeriodModel.DepartmentId}.")); } newWorkPeriodDTO.Id = id; var newWorkPeriodModel = _mapper.Map <WorkPeriod>(newWorkPeriodDTO); await _unitOfWork.WorkPeriods.UpdateAsync(id, newWorkPeriodModel); await _unitOfWork.CompleteAsync(); return(Ok(newWorkPeriodDTO)); }