private static void GenerateVacationDaysListFromBooking(VacationBooking vacationBooking, List <DateTime> holidayList, List <DateTime> userVacDates, List <DateTime> previousDates,
                                                         out List <DateTime> doubleBookingDatesList, out List <VacationDay> vacdayList)
 {
     doubleBookingDatesList = new List <DateTime>();
     vacdayList             = new List <VacationDay>();
     for (DateTime d = vacationBooking.FromDate; d <= vacationBooking.ToDate; d = d.AddDays(1))
     {
         var vacday = new VacationDay()
         {
             Id                = 0,
             VacationDate      = d,
             VacationBookingId = vacationBooking.Id,
         };
         if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
         {
             continue;
         }
         if (holidayList.Contains(d))
         {
             continue;
         }
         if (previousDates.Contains(d))
         {
             vacdayList.Add(vacday);
             continue;
         }
         if (userVacDates.Contains(d))
         {
             doubleBookingDatesList.Add(d);
             continue;
         }
         vacdayList.Add(vacday);
     }
 }
        ///<summary>
        ///Returns list of all valid approval states for the specified user.
        ///</summary>
        private async Task <IEnumerable <object> > GetApprovalStatesForUser(VacationBooking vacationBooking, User user)
        {
            var apporalStateList = (ApprovalState[])Enum.GetValues(typeof(ApprovalState));

            return(await HasRolesAsync(user, "Admin") || IsManagerForBookingUser(vacationBooking, user)
                ? apporalStateList.Select(x => new { Value = x.ToString() })
                : apporalStateList.Select(x => new { Value = x.ToString() }).Where(a => a.Value == vacationBooking.Approval));
        }
Пример #3
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            VacationBooking vac = (VacationBooking)validationContext.ObjectInstance;

            if (vac.ToDate < DateTime.Today.AddMonths(-pastMonths) || vac.ToDate > DateTime.Today.AddMonths(futureMonths))
            {
                return(new ValidationResult($"You can only book vacation {pastMonths} months in the past and {futureMonths} months in the future."));
            }
            if (vac.FromDate > vac.ToDate)
            {
                return(new ValidationResult($"Your ToDate must be large than your FromDate."));
            }

            return(ValidationResult.Success);
        }
        //Todo: Add both start and end-date as in parameters
        public async Task <IActionResult> Create(string startdate)
        {
            var vacBooking = new VacationBooking();

            if (!string.IsNullOrWhiteSpace(startdate))
            {
                vacBooking.FromDate = DateTime.Parse(startdate);
                vacBooking.ToDate   = DateTime.Parse(startdate);
            }
            else
            {
                vacBooking.FromDate = DateTime.Today;
                vacBooking.ToDate   = DateTime.Today;
            }
            ViewData["AbsenceTypes"] = new SelectList(await GetAbsenceTypes(), nameof(AbsenceType.Id), nameof(AbsenceType.Name));
            return(View(vacBooking));
        }
        public async Task <IActionResult> Create([Bind("Id,FromDate,ToDate,Comment,AbsenceTypeId")] VacationBooking vacationBooking)
        {
            var absenceType = await GetAbsenceTypeById(vacationBooking.AbsenceTypeId);

            if (absenceType == null)
            {
                AddInvalidAbsenceTypeError();
            }

            if (ModelState.IsValid)
            {
                vacationBooking.Approval = ApprovalState.Pending.ToString();

                bool isErrors = false;

                var user = await GetCurrentUser();

                var holidayList     = _context.WorkFreeDays.AsNoTracking().Select(x => x.Date).ToList();
                var userVacbookings = await GetVacationBookingsByUser(user);

                var userVacDates = GetVacationDatesFromBookings(userVacbookings);

                GenerateVacationDaysListFromBooking(vacationBooking, holidayList, userVacDates,
                                                    out List <DateTime> doubleBookingDatesList, out List <VacationDay> vacdayList);

                isErrors = ValidateVacationDaysList(vacdayList, isErrors);
                isErrors = ValidateDoubleBookingDatesList(doubleBookingDatesList, isErrors);

                vacationBooking.VacationDays = vacdayList;
                vacationBooking.UserId       = user.Id;
                vacationBooking.User         = user;
                vacationBooking.AbsenceType  = absenceType;

                if (!isErrors)
                {
                    _context.Add(vacationBooking);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            ViewData["AbsenceTypes"] = new SelectList(await GetAbsenceTypes(), nameof(AbsenceType.Id), nameof(AbsenceType.Name));
            return(View(vacationBooking));
        }
Пример #6
0
        public List <VacationDay> GetVacationDayFromBookings(VacationBooking vacationBooking)
        {
            var vacdayList = new List <VacationDay>();

            for (DateTime d = vacationBooking.FromDate; d <= vacationBooking.ToDate; d = d.AddDays(1))
            {
                var vacday = new VacationDay()
                {
                    Id                = 0,
                    VacationDate      = d,
                    VacationBookingId = vacationBooking.Id,
                };
                if (d.DayOfWeek == DayOfWeek.Saturday || d.DayOfWeek == DayOfWeek.Sunday)
                {
                    continue;
                }
                vacdayList.Add(vacday);
            }
            return(vacdayList);
        }
Пример #7
0
        private void SeedDatabase()
        {
            var team1 = new Team {
                Name = "Pandas", Shortening = "Pand"
            };
            var team2 = new Team {
                Name = "Tigers", Shortening = "Tigr"
            };
            var team3 = new Team {
                Name = "Rabbits", Shortening = "Rabt"
            };

            var teams = new List <Team>()
            {
                team1, team2, team3
            };

            _context.Teams.AddRange(teams);

            var dep1 = new Department {
                Name = "Developer", Shortening = "Dev"
            };
            var dep2 = new Department {
                Name = "Economy", Shortening = "Eco"
            };
            var dep3 = new Department {
                Name = "Support", Shortening = "Sup"
            };

            var deps = new List <Department>()
            {
                dep1, dep2, dep3
            };

            _context.Departments.AddRange(deps);

            bool roleExists = _roleManager.RoleExistsAsync("Manager").Result;

            if (!roleExists)
            {
                var managerRole = new Role()
                {
                    Name       = "Manager",
                    Shortening = "Mangr"
                };
                _roleManager.CreateAsync(managerRole).Wait();
            }

            const string userPassword = "******";

            var managerUser = new User {
                UserName = "******", Email = "*****@*****.**", FirstName = "Mike", LastName = "Manager", DisplayName = "Mike Manager", TeamId = team3.Id, DepartmentId = dep2.Id,
            };

            _userManager.CreateAsync(managerUser, userPassword).Wait();

            var user1 = new User {
                UserName = "******", Email = "*****@*****.**", FirstName = "Pelle", LastName = "Svantesson", DisplayName = "Pelle Svantesson", TeamId = team1.Id, DepartmentId = dep3.Id, ManagerUserId = managerUser.Id
            };
            var user2 = new User {
                UserName = "******", Email = "*****@*****.**", FirstName = "Thom", LastName = "Ivarsson", DisplayName = "Thom Ivarsson", TeamId = team2.Id, DepartmentId = dep2.Id, ManagerUserId = managerUser.Id
            };
            var user3 = new User {
                UserName = "******", Email = "*****@*****.**", FirstName = "Britta", LastName = "Johnsson", DisplayName = "Britta Johnsson", TeamId = team3.Id, DepartmentId = dep1.Id
            };
            var user4 = new User {
                UserName = "******", Email = "*****@*****.**", FirstName = "Einar", LastName = "Andersson", DisplayName = "Einar Andersson", TeamId = team1.Id, DepartmentId = dep2.Id, ManagerUserId = managerUser.Id
            };
            var user5 = new User {
                UserName = "******", Email = "*****@*****.**", FirstName = "Sarah", LastName = "Qvistsson", DisplayName = "Sarah Qvistsson", TeamId = team2.Id, DepartmentId = dep3.Id, ManagerUserId = managerUser.Id
            };

            var users = new List <User>()
            {
                user1, user2, user3, user4, user5
            };

            foreach (var user in users)
            {
                _userManager.CreateAsync(user, userPassword).Wait();
            }

            var abs1 = new AbsenceType {
                Name = "Vacation"
            };
            var abs2 = new AbsenceType {
                Name = "Leave"
            };
            var abs3 = new AbsenceType {
                Name = "Away"
            };

            var abses = new List <AbsenceType>()
            {
                abs1, abs2, abs3
            };

            var vac1 = new VacationBooking {
                Comment = "Trip to Paris", Approval = ApprovalState.Pending.ToString(), FromDate = DateTime.Now.Date.AddDays(-3), ToDate = DateTime.Now.Date.AddDays(3), User = user1, AbsenceType = abs1
            };
            var vac2 = new VacationBooking {
                Comment = "Away from home", Approval = ApprovalState.Pending.ToString(), FromDate = DateTime.Now.Date.AddDays(10), ToDate = DateTime.Now.Date.AddDays(12), User = user1, AbsenceType = abs3
            };
            var vac3 = new VacationBooking {
                Comment = "Party day", Approval = ApprovalState.Approved.ToString(), FromDate = DateTime.Now.Date.AddDays(15), ToDate = DateTime.Now.Date.AddDays(17), User = user1, AbsenceType = abs1
            };
            var vac4 = new VacationBooking {
                Comment = "Going to Hawaii", Approval = ApprovalState.Pending.ToString(), FromDate = DateTime.Now.Date.AddDays(8), ToDate = DateTime.Now.Date.AddDays(16), User = user2, AbsenceType = abs1
            };
            var vac5 = new VacationBooking {
                Comment = "Tripping", Approval = ApprovalState.Denied.ToString(), FromDate = DateTime.Now.Date.AddDays(2), ToDate = DateTime.Now.Date.AddDays(4), User = user2, AbsenceType = abs2
            };
            var vac6 = new VacationBooking {
                Comment = "Cruise trip", Approval = ApprovalState.Pending.ToString(), FromDate = DateTime.Now.Date.AddDays(11), ToDate = DateTime.Now.Date.AddDays(14), User = user3, AbsenceType = abs1
            };
            var vac7 = new VacationBooking {
                Comment = "Barcelona", Approval = ApprovalState.Approved.ToString(), FromDate = DateTime.Now.Date.AddDays(-1), ToDate = DateTime.Now.Date.AddDays(4), User = user3, AbsenceType = abs1
            };
            var vac8 = new VacationBooking {
                Comment = "Road trip", Approval = ApprovalState.Denied.ToString(), FromDate = DateTime.Now.Date.AddDays(5), ToDate = DateTime.Now.Date.AddDays(20), User = user4, AbsenceType = abs2
            };
            var vac9 = new VacationBooking {
                Comment = "Kentucky", Approval = ApprovalState.Pending.ToString(), FromDate = DateTime.Now.Date.AddDays(20), ToDate = DateTime.Now.Date.AddDays(25), User = user5, AbsenceType = abs3
            };
            var vac10 = new VacationBooking {
                Comment = "Far away", Approval = ApprovalState.Approved.ToString(), FromDate = DateTime.Now.Date.AddDays(-8), ToDate = DateTime.Now.Date.AddDays(-2), User = user5, AbsenceType = abs1
            };

            var vacs = new List <VacationBooking>()
            {
                vac1, vac2, vac3, vac4, vac5, vac6, vac7, vac8, vac9, vac10
            };

            foreach (var vac in vacs)
            {
                vac.VacationDays = GetVacationDayFromBookings(vac);
            }

            _context.AbsenceTypes.AddRange(abses);
            _context.VacationBookings.AddRange(vacs);

            _context.SaveChanges();
        }
 private static bool ApprovalIsNotPending(VacationBooking vacbookingReadOnly)
 {
     return(vacbookingReadOnly.Approval != ApprovalState.Pending.ToString());
 }
 private static void ValidateVacationBookingChanges(VacationBooking vacationBooking, VacationBooking vacbookingReadOnly)
 {
     vacationBooking.Approval = vacbookingReadOnly.Approval;
     vacationBooking.UserId   = vacbookingReadOnly.UserId;
 }
        public async Task <IActionResult> Edit(int id, [Bind("Id,UserId,FromDate,ToDate,Approval,Comment,AbsenceTypeId")] VacationBooking vacationBooking)
        {
            if (id != vacationBooking.Id)
            {
                return(NotFound());
            }

            var vacbookingReadOnly = await _context.VacationBookings.AsNoTracking()
                                     .Include(v => v.User).Include(v => v.VacationDays).Include(v => v.AbsenceType)
                                     .SingleOrDefaultAsync(v => v.Id == id);

            if (vacbookingReadOnly.UserId != vacationBooking.UserId)
            {
                return(NotFound());
            }

            var user = await GetCurrentUser();

            bool isNotEditable = false;

            if (!await HasRolesAsync(user, "Admin") && !IsManagerForBookingUser(vacbookingReadOnly, user))
            {
                if (ApprovalIsNotPending(vacbookingReadOnly))
                {
                    isNotEditable = true;
                    ViewBag.NotEditableMessage = "You can't edit a vacation booking with Approved or Denied status. " +
                                                 "\nPlease delete existing booking and create a new one.";
                    ModelState.AddModelError("UserId", "You can't edit a vacation booking with Approved or Denied status.");
                }

                ValidateVacationBookingChanges(vacationBooking, vacbookingReadOnly);
            }

            var absenceType = await GetAbsenceTypeById(vacationBooking.AbsenceTypeId);

            if (absenceType == null)
            {
                AddInvalidAbsenceTypeError();
            }

            if (ModelState.IsValid)
            {
                bool isErrors = false;

                var userVacbookings = await GetVacationBookingsNoTrackingByUserId(vacationBooking.UserId);

                var userVacDates = GetVacationDatesFromBookings(userVacbookings);
                var holidayList  = await _context.WorkFreeDays.Select(x => x.Date).ToListAsync();

                var previousDates = vacbookingReadOnly.VacationDays.Select(x => x.VacationDate).ToList();

                GenerateVacationDaysListFromBooking(vacationBooking, holidayList, userVacDates, previousDates,
                                                    out List <DateTime> doubleBookingDatesList, out List <VacationDay> vacdayList);

                isErrors = ValidateVacationDaysList(vacdayList, isErrors);
                isErrors = ValidateDoubleBookingDatesList(doubleBookingDatesList, isErrors);

                vacationBooking.VacationDays = vacdayList;
                vacationBooking.User         = vacbookingReadOnly.User;
                vacationBooking.AbsenceType  = absenceType;

                if (!isErrors)
                {
                    var oldVacationDays = _context.VacationDays.Where(v => v.VacationBookingId == id);
                    try
                    {
                        _context.RemoveRange(oldVacationDays);
                        _context.Update(vacationBooking);
                        await _context.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        if (!VacationBookingExists(vacationBooking.Id))
                        {
                            return(NotFound());
                        }
                        else
                        {
                            throw;
                        }
                    }

                    return(RedirectToAction(nameof(Index)));
                }
            }

            if (vacationBooking.User == null)
            {
                vacationBooking.User = vacbookingReadOnly.User;
            }
            ViewBag.NotEditable        = isNotEditable;
            ViewData["AbsenceTypes"]   = new SelectList(await GetAbsenceTypes(), nameof(AbsenceType.Id), nameof(AbsenceType.Name), vacationBooking.AbsenceTypeId);
            ViewData["ApprovalStates"] = new SelectList(await GetApprovalStatesForUser(vacationBooking, user), "Value", "Value", vacationBooking.Approval);
            ViewData["UserId"]         = new SelectList(await _context.Users.Where(x => x.Id == vacationBooking.UserId).ToListAsync(), "Id", "DisplayName", vacationBooking.UserId);
            return(View(vacationBooking));
        }
 private bool IsManagerForBookingUser(VacationBooking vacationBooking, User user)
 {
     return(vacationBooking.User.ManagerUserId == user.Id);
 }
 private static bool IsOwner(VacationBooking vacationBooking, User user)
 {
     return(vacationBooking.UserId == user.Id);
 }