Esempio n. 1
0
        public async Task <IActionResult> Add(CalendarVacationViewModel vacationViewModel)
        {
            if (vacationViewModel.Id.GetValueOrDefault() != 0)
            {
                return(BadRequest("Id must be empty."));
            }

            if (vacationViewModel.Type == VacationType.None)
            {
                return(BadRequest("Vacation type can not be empty."));
            }

            if (vacationViewModel.DateFrom > vacationViewModel.DateTo)
            {
                return(BadRequest("Date from can not be greater than date to."));
            }

            Employee employee = await _employeeRepository.GetAsync(vacationViewModel.EmployeeId);

            if (employee == null)
            {
                return(NotFound("Employee does not exist."));
            }

            int  userId = employee.UserId;
            int  authenticatedUserId = Int32.Parse(User.Claims.Single(x => x.Type == ApplicationClaimTypes.UserId).Value);
            bool isAdmin             = User.IsInRole(Roles.Admin);

            if (!isAdmin && userId != authenticatedUserId)
            {
                return(Unauthorized());
            }

            if (employee.Vacations.Any(x => x.DateFrom <= vacationViewModel.DateTo && vacationViewModel.DateFrom <= x.DateTo && x.Id != vacationViewModel.Id))
            {
                return(BadRequest("Date range intersects with other vacation."));
            }

            Vacation vacation = new Vacation()
            {
                EmployeeId = employee.Id.Value,
                DateFrom   = vacationViewModel.DateFrom,
                DateTo     = vacationViewModel.DateTo,
                Type       = vacationViewModel.Type
            };

            vacation.Id = await _vacationRepository.AddAsync(vacation);

            return(CreatedAtRoute("GetVacation", new { id = vacation.Id }, vacation));
        }