Exemple #1
0
 public VolunteerViewModel(List <Location> locations, List <Organization> organizations)
 {
     Volunteer          = new Volunteer();
     VolunteerProfile   = new VolunteerProfile();
     this.locations     = locations;
     this.organizations = organizations;
 }
Exemple #2
0
        private async Task <bool> UpdateUserProfile(AppUser user)
        {
            // get positions for display
            Positions = await _context.Positions.ToListAsync();

            // tag it for change
            _context.Update(user);

            // keep all properties that won't be edited
            DetailsModel.Id        = user.VolunteerProfile.Id;
            DetailsModel.FirstName = user.VolunteerProfile.FirstName;
            DetailsModel.LastName  = user.VolunteerProfile.LastName;

            // for all properties that can be edited, replace old values with new values via model
            VolunteerProfile newVolunteerProfile = _mapper.Map <VolunteerProfile>(DetailsModel);

            newVolunteerProfile.User   = user;
            newVolunteerProfile.UserID = user.Id;
            user.VolunteerProfile      = newVolunteerProfile;
            // email is attached to the AppUser entity so it has to be updated individually
            user.Email = DetailsModel.Email;

            // update preferred and assigned positions
            UpdateVolunteerPositions(user.VolunteerProfile);
            await _context.SaveChangesAsync();

            return(true);
        }
        public List <Shift> GetWorkablShiftsForVolunteer(VolunteerProfile volunteer)
        {
            // find all nonrecurring shifts that agree with the given availabilites
            if (_context.Shifts.Any())
            {
                _context.Entry(volunteer).Collection(v => v.Availabilities).Load();
                _context.Entry(volunteer).Reference(v => v.Positions).Load();

                List <Shift> availableShifts = new List <Shift>();

                foreach (var shift in _context.Shifts.Where(s => string.IsNullOrEmpty(s.RecurrenceRule)))
                {
                    if (shift.Volunteer == null &&
                        shift.StartTime > DateTime.Now &&
                        volunteer.Availabilities
                        .Any(a =>
                             shift.StartTime.TimeOfDay >= a.StartTime &&
                             shift.EndTime.TimeOfDay <= a.EndTime &&
                             Enum.GetName(typeof(DayOfWeek), shift.StartTime.DayOfWeek).ToLower() == a.AvailableDay) &&
                        volunteer.Positions.Any(p => p.Id == shift.PositionId))
                    {
                        availableShifts.Add(shift);
                    }
                }

                // find all recurring shifts that agree with the given availabilities
                foreach (var recurringShift in _context.Shifts.Where(s => !string.IsNullOrWhiteSpace(s.RecurrenceRule)))
                {
                    var childShiftDates = RecurrenceHelper.GetRecurrenceDateTimeCollection(recurringShift.RecurrenceRule, recurringShift.StartTime);
                    foreach (var date in childShiftDates)
                    {
                        bool dateIsAvailable = recurringShift.Volunteer == null && date > DateTime.Now.Date.AddDays(1) &&
                                               volunteer.Availabilities
                                               .Any(a => recurringShift.StartTime.TimeOfDay >= a.StartTime && recurringShift.EndTime.TimeOfDay <= a.EndTime) &&
                                               volunteer.Positions.Any(p => p.Id == recurringShift.PositionId);

                        if (dateIsAvailable)
                        {
                            var availableShift = new Shift()
                            {
                                StartTime = date + recurringShift.StartTime.TimeOfDay,
                                EndTime   = date + recurringShift.EndTime.TimeOfDay,
                                Position  = recurringShift.Position
                            };

                            availableShifts.Add(availableShift);
                        }
                    }
                }

                // order shifts by ascending date
                return(availableShifts.OrderBy(s => s.StartTime).ToList());
            }
            return(null);
        }
Exemple #4
0
        //public ActionResult VolunteerClockedInOut(int locationId, string userName)
        public ActionResult VolunteerClockedInOut()
        {
            VIMSDBContext context   = ((Repository <Volunteer>)volunteerInfoRepository).Context;
            Volunteer     volunteer = (Volunteer)TempData["VolunteerInfo"];
            Location      location  = ((Location)TempData["Location"]);

            context.Entry(volunteer).State = EntityState.Modified; // reload after request

            VolunteerTimeClock clockInfo = volunteerInfoRepository.GetClockedInInfo(volunteer);
            VolunteerPhoto     photo     = volunteerInfoRepository.GetLastPhotoInfo(volunteer);
            VolunteerProfile   profile   = volunteerInfoRepository.GetDefaultProfileInfo(volunteer.Id);

            if (clockInfo != null)
            {
                // was clocked in so clock out
                clockInfo.ClockOut      = DateTime.Now;
                clockInfo.ClockOutPhoto =
                    photo != null ? photo.Path : null;
                context.SaveChanges(); //BKP todo, merge with repo code
            }
            else
            {
                // clock in
                VolunteerTimeClock clockIn = new VolunteerTimeClock();
                clockIn.VolunteerProfile = profile;
                clockIn.LocationId       = location.Id;
                clockIn.ClockIn          = DateTime.Now;
                clockIn.LocationId       = ViewBag.LocationId;
                clockIn.ClockInPhoto     =
                    photo != null ? photo.Path : null;
                clockIn.CreatedBy = null;
                clockIn.CreatedDt = DateTime.Now;
                volunteer.VolunteerTimeClocks.Add(clockIn);
                context.SaveChanges(); //BKP todo, merge with repo code
            }

            // build model for view
            VolunteerClockedInOutViewModel model = new VolunteerClockedInOutViewModel();

            model.isClockedIn            = (clockInfo == null); // now!, clocked in
            model.Volunteer              = volunteer;
            model.LocationId             = (int)location.Id;
            model.LocationName           = location.Name;
            model.TimeLogged             = VolunteerClockedInOutViewModel.GetHoursLogged(volunteerInfoRepository.GetVolunteersCompletedInOutInfos(volunteer));
            model.RecentClockInformation = volunteerInfoRepository.GetVolunteersRecentClockInOutInfos(volunteer, Util.TJSConstants.RECENT_LIST_LEN);
            model.CaseNumber             = profile != null ? profile.CaseNumber : "NA";
            model.TimeNeeded             = profile != null ? new TimeSpan((short)profile.Volunteer_Hours_Needed, 0, 0) : new TimeSpan(0, 0, 0);

            return(View(model));
        }
Exemple #5
0
        private void UpdateVolunteerPositions(VolunteerProfile volunteer)
        {
            // clear out all current preferences for this volunteer
            List <PositionVolunteer> oldPositions = _context.PositionVolunteers
                                                    .Where(p => p.Volunteer == volunteer).ToList();

            _context.PositionVolunteers.RemoveRange(oldPositions);

            // load new position selection into volunteerprofile
            volunteer.Positions = new List <PositionVolunteer>();

            // iterate through all positions (via model property that contains every selectable position)
            foreach (Position position in Positions)
            {
                // prepare an entity to be added to the volunteer's list of positions
                PositionVolunteer posVol = new PositionVolunteer()
                {
                    Volunteer = volunteer,
                    Position  = position,
                };

                // for each position, check to see if it was selected as a preferred position or an assigned position
                var preferred = Request.Form["preferred-" + position.Name];
                var assigned  = Request.Form["assigned-" + position.Name];

                bool selectedAsPreferredPosition = preferred.Count > 0 && assigned.Count == 0;
                bool selectedAsAssignedPosition  = preferred.Count == 0 && assigned.Count > 0;
                bool selectedAsBoth = preferred.Count > 0 && assigned.Count > 0;

                if (selectedAsPreferredPosition)
                {
                    posVol.Association = PositionVolunteer.AssociationType.Preferred;
                    volunteer.Positions.Add(posVol);
                }
                else if (selectedAsAssignedPosition)
                {
                    posVol.Association = PositionVolunteer.AssociationType.Assigned;
                    volunteer.Positions.Add(posVol);
                }
                else if (selectedAsBoth)
                {
                    posVol.Association = PositionVolunteer.AssociationType.PreferredAndAssigned;
                    volunteer.Positions.Add(posVol);
                }
            }
        }
        private void FillPreferredPositions(VolunteerProfile volunteer)
        {
            // clear out all current preferences for this volunteer
            List <PositionVolunteer> oldPositions = _context.PositionVolunteers
                                                    .Where(p => p.Volunteer == volunteer).ToList();

            _context.PositionVolunteers.RemoveRange(oldPositions);
            volunteer.Positions = new List <PositionVolunteer>();
            foreach (Position position in Positions)
            {
                var preferred = Request.Form["preferred-" + position.Name];
                var assigned  = Request.Form["assigned-" + position.Name];

                PositionVolunteer posVol = new PositionVolunteer()
                {
                    Volunteer = volunteer,
                    Position  = position,
                };

                // this means it was preferred, StringValues are weird
                if (preferred.Count > 0 && assigned.Count == 0)
                {
                    posVol.Association = PositionVolunteer.AssociationType.Preferred;
                    volunteer.Positions.Add(posVol);
                }
                // this means it was assigned
                else if (preferred.Count == 0 && assigned.Count > 0)
                {
                    posVol.Association = PositionVolunteer.AssociationType.Assigned;
                    volunteer.Positions.Add(posVol);
                }
                // this means it was both
                else if (preferred.Count > 0 && assigned.Count > 0)
                {
                    posVol.Association = PositionVolunteer.AssociationType.PreferredAndAssigned;
                    volunteer.Positions.Add(posVol);
                }
            }
        }
        private List <PositionVolunteer> AssignPreferredPositions(VolunteerProfile volunteer)
        {
            List <PositionVolunteer> volunteerPositions = new List <PositionVolunteer>();

            foreach (Position position in Positions)
            {
                var positionWasSelected = Request.Form[position.Name];

                // this means it was selected, StringValues are weird
                if (positionWasSelected.Count > 0)
                {
                    PositionVolunteer posVol = new PositionVolunteer()
                    {
                        Volunteer   = volunteer,
                        Position    = position,
                        Association = PositionVolunteer.AssociationType.Preferred
                    };
                    volunteerPositions.Add(posVol);
                }
            }

            return(volunteerPositions);
        }
Exemple #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="locationId"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        //[HttpGet]
        public ActionResult VolunteerClockIn(int locationId, string userName)
        {
            Volunteer volunteer = volunteerInfoRepository.GetVolunteer(userName);
            Location  location  = lookUpRepository.GetLocationById((int)locationId);

            if (volunteer != null && volunteer.Id > 0)
            {
                VolunteerProfile profile =
                    volunteerInfoRepository.GetLastProfileInfo(volunteer.Id);
                VolunteerTimeClock clockInfo = volunteerInfoRepository.GetClockedInInfo(volunteer);

                //todo move to a view model?
                ViewBag.isClockedIn = (clockInfo != null); // clocked in
                ViewBag.Case        = profile != null ? profile.CaseNumber : "NA";

                TempData["VolunteerInfo"] = volunteer;
                TempData["Location"]      = location;

                VolunteerClockInViewModel vm = new VolunteerClockInViewModel();
                vm.Volunteer    = volunteer;
                vm.LocationId   = (int)location.Id;
                vm.LocationName = location.Name;
                VolunteerPhoto photo = volunteerInfoRepository.GetLastPhotoInfo(volunteer);
                if (photo != null)
                {
                    vm.DefaultPhotoPath = volunteerInfoRepository.GetLastPhotoInfo(volunteer).Path;
                }

                //dispose now, new context will be created in next request
                volunteerInfoRepository.Dispose();

                return(View(vm));
            }

            return(RedirectToAction("VolunteerLookUp", "VolunteerClockTime", new { locationId = location.Id }));
        }
Exemple #9
0
        public List <Availability> GetAvailabilitiesFromFormData(IFormCollection formData, VolunteerProfile volunteer)
        {
            try
            {
                List <Availability> availabilities = new List <Availability>();
                string[]            daysInWeek     = { "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" };
                for (int i = 0; i < daysInWeek.Length; i++)
                {
                    string currentDay = daysInWeek[i];
                    int    fieldCountForCurrentDay = formData.Keys.Count(k => k.Contains($"{currentDay}-1"));

                    for (int j = 1; j <= fieldCountForCurrentDay; j++)
                    {
                        string startTimeString = formData[$"{currentDay}-1-{j}"];
                        string endTimeString   = formData[$"{currentDay}-2-{j}"];


                        if (string.IsNullOrWhiteSpace(startTimeString) ^ string.IsNullOrWhiteSpace(endTimeString))
                        {
                            return(null);
                        }

                        if (string.IsNullOrWhiteSpace(startTimeString) || string.IsNullOrWhiteSpace(endTimeString))
                        {
                            continue;
                        }

                        string[] startTimeParts = startTimeString.Split(':');
                        string[] endTimeParts   = endTimeString.Split(':');

                        int startHours   = int.TryParse(startTimeParts[0], out int resultSH) ? resultSH : -1;
                        int startMinutes = int.TryParse(startTimeParts[1], out int resultSM) ? resultSM : -1;
                        int endHours     = int.TryParse(endTimeParts[0], out int resultEH) ? resultEH : -1;
                        int endMinutes   = int.TryParse(endTimeParts[1], out int resultEM) ? resultEM : -1;

                        if (startHours == -1 || startMinutes == -1 || endHours == -1 || endMinutes == -1)
                        {
                            //ModelState.AddModelError("TimeError", "One or more of the entered times are not valid.");
                            return(null);
                        }

                        TimeSpan startTime = new TimeSpan(int.Parse(startTimeParts[0]), int.Parse(startTimeParts[1]), 0);
                        TimeSpan endTime   = new TimeSpan(int.Parse(endTimeParts[0]), int.Parse(endTimeParts[1]), 0);

                        Availability a = new Availability()
                        {
                            AvailableDay = daysInWeek[i],
                            StartTime    = startTime,
                            EndTime      = endTime,
                            Volunteer    = volunteer
                        };

                        availabilities.Add(a);
                    }
                }

                return(availabilities);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(null);
            }
        }
Exemple #10
0
        public async Task <bool> UpdateVolunteerAvailability(IFormCollection formData, VolunteerProfile vol, FoodBankContext _context)
        {
            await _context.Entry(vol).Collection(p => p.Availabilities).LoadAsync();

            List <Availability> oldAvailabilities = await _context.Availabilities.Where(a => a.Volunteer.Id == vol.Id).ToListAsync();

            _context.Availabilities.RemoveRange(oldAvailabilities);

            await _context.SaveChangesAsync();

            List <Availability> newAvailabilites = GetAvailabilitiesFromFormData(formData, vol);

            if (newAvailabilites != null)
            {
                await _context.Availabilities.AddRangeAsync(newAvailabilites);

                await _context.SaveChangesAsync();

                return(true);
            }
            else
            {
                await _context.Availabilities.AddRangeAsync(oldAvailabilities);

                await _context.SaveChangesAsync();

                return(false);
            }
        }
Exemple #11
0
        private bool CreateVolunteer(string userName, string userRole)
        {
            var volunteer = new AppUser()
            {
                UserName           = userName,
                NormalizedUserName = userName.ToUpper(),
                EmailConfirmed     = true,
                Email = "*****@*****.**"
            };

            VolunteerProfile vi = new VolunteerProfile()
            {
                FirstName              = "testfirst",
                LastName               = "testlast",
                Address                = "testAddress",
                City                   = "testcity",
                PostalCode             = "T1R1L9",
                MainPhone              = "5555555555",
                AlternatePhone1        = "5555555555",
                AlternatePhone2        = "5555555555",
                ApprovalStatus         = ApprovalStatus.Pending,
                Birthdate              = DateTime.Now,
                EmergencyFullName      = "testemergency",
                EmergencyPhone1        = "5555555555",
                EmergencyPhone2        = "5555555555",
                EmergencyRelationship  = "testrelationship",
                FoodSafe               = false,
                FirstAidCpr            = false,
                OtherCertificates      = "TestOther",
                EducationTraining      = "testeducation",
                SkillsInterestsHobbies = "testskills",
                VolunteerExperience    = "testexperience",
                OtherBoards            = "otherboards",
            };

            Reference reference = new Reference()
            {
                Name         = "Steve",
                Volunteer    = vi,
                Phone        = "4034056785",
                Relationship = "Instructor",
                Occupation   = "Professor"
            };

            WorkExperience workExp = new WorkExperience()
            {
                EmployerName    = "testemployer",
                EmployerAddress = "testaddress",
                StartDate       = DateTime.Now,
                EndDate         = DateTime.Now.AddDays(20),
                EmployerPhone   = "5555555555",
                ContactPerson   = "testcontact",
                PositionWorked  = "testposition"
            };

            List <Reference> references = new List <Reference>();

            references.Add(reference);
            List <WorkExperience> workExperiences = new List <WorkExperience>();

            workExperiences.Add(workExp);

            vi.References              = references;
            vi.WorkExperiences         = workExperiences;
            volunteer.VolunteerProfile = vi;

            IdentityResult result = _userManager.CreateAsync(volunteer, "P@$$W0rd").Result;

            if (result.Succeeded)
            {
                SetUserToRole(volunteer, userRole);
            }
            else
            {
                return(false);
            }

            return(true);
        }
Exemple #12
0
 public ActionResult VolunteerEditProfile(Volunteer volunteer, VolunteerProfile profile, int locationId)
 {
     return(View());
 }
Exemple #13
0
        public HttpResponseMessage GetMyStatistics(string id)
        {
            if (ValidationService.AuthorizeToken(GetToken(), "get:/api/volunteer/statistics?id=") == false)
            {
                return(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.Unauthorized, Content = new StringContent("无访问权限", System.Text.Encoding.GetEncoding("UTF-8"), "application/text")
                });
            }
            User volunteer = myService.FindUser(new Guid(id));
            //获得VolunteerProfile
            VolunteerProfile myProfile = (VolunteerProfile)volunteer.UserProfiles[volunteer.Name + "VolunteerProfile"];

            //计算参加活动总数和完成率
            int    completedNumber = myService.FindAllVolunteerCompletedActivities(volunteer, "", false, 0, 0).Count();
            int    totalNumber     = myService.FindActivitesVolunteerSignedIn(volunteer, "", "", false, 0, 0).Count();
            double myCompleteRate;

            if (totalNumber != 0)
            {
                myCompleteRate = (double)completedNumber / totalNumber;
            }
            else
            {
                myCompleteRate = 0;
            }

            var result = new
            {
                //姓名
                name = volunteer.Name,
                id   = volunteer.Id,
                //等级
                level = myProfile.VolunteerLevel,
                //等级名称
                levelName = myProfile.VolunteerLevelName,
                //等级对应图片
                levelPicture = myProfile.VolunteerLevelPicture,
                //总点数
                point = myProfile.Point.TotalPoint,
                //升级所需点数
                pointsToNextLevel = myProfile.PointsToNextLevel,
                //力量
                strength = myProfile.HexagramProperty.Strength,
                //智力
                intelligence = myProfile.HexagramProperty.Intelligence,
                //耐力
                endurance = myProfile.HexagramProperty.Endurance,
                //爱心
                compassion = myProfile.HexagramProperty.Compassion,
                //奉献
                sacrifice = myProfile.HexagramProperty.Sacrifice,
                //参加活动总数
                signedInActivityNumber = totalNumber,
                //完成率
                completeRate = myCompleteRate
            };
            StringWriter   tw             = new StringWriter();
            JsonSerializer jsonSerializer = new JsonSerializer();

            jsonSerializer.Serialize(tw, result, result.GetType());
            return(new HttpResponseMessage {
                Content = new StringContent(tw.ToString(), System.Text.Encoding.GetEncoding("UTF-8"), "application/json")
            });
        }