예제 #1
0
        public async Task <IActionResult> Create([FromRoute] Guid employeeId, [FromBody] CreateShiftRequest request)
        {
            #region Error-handling
            // NOTE:    An issue with amount of days per month where a month might have 30 days, but 31 is a valid input
            //          Would be better to have a type like DateTime that handles this
            if (request.Day < 1 || request.Day > 31 || request.Month < 1 || request.Month > 12 || request.Year < 1 ||
                new DateTime(request.Year, request.Month, request.Day) < DateTime.Now)
            {
                return(StatusCode(StatusCodes.Status406NotAcceptable, "The given date for the shift is not valid!" +
                                  "\nMake sure the date is not in the past, and that Day is between 1-31, and Month is between 1-12!"));
            }
            // Handle out of bounds start time
            if (request.StartTime < 0 || request.StartTime > 23)
            {
                return(StatusCode(StatusCodes.Status406NotAcceptable, "The time given for the start of the shift is not valid! Must be between 0 and 23!"));
            }
            // Handle out of bounds end time
            if (request.EndTime <= request.StartTime || request.EndTime > 24)
            {
                return(StatusCode(StatusCodes.Status406NotAcceptable, "The time given for the end of the shift is not valid! Must be higher than the start time (" + request.StartTime + "), but no higher than 24!"));
            }
            // Check that shift does not overlap with an existing shift for the given employee
            List <Shift> employeeShifts = await _shiftService.GetShiftsForSpecificEmployeeByIdAsync(employeeId);

            for (int i = 0; i < employeeShifts.Count; i++)
            {
                if (DoesShiftsOverlap(employeeShifts[i], request))
                {
                    return(StatusCode(StatusCodes.Status406NotAcceptable, "The new time for this shift overlaps with a different shift (Id:" + employeeShifts[i].Id + ") for this employee (Id:" + employeeId + ")"));
                }
            }
            #endregion

            Shift shift = new Shift {
                ShiftOwnerId = employeeId, Day = request.Day, Month = request.Month,
                Year         = request.Year, StartTime = request.StartTime, EndTime = request.EndTime
            };

            await _shiftService.CreateShiftAsync(shift);

            string baseUrl     = HttpContext.Request.Scheme + "//" + HttpContext.Request.Host.ToUriComponent();
            string locationUri = baseUrl + "/" + ApiRoutes.Shifts.Get.Replace("{shiftId}", shift.Id.ToString());

            ShiftResponse response = new ShiftResponse {
                Id = shift.Id
            };
            return(Created(locationUri, response));
        }