public void SendTasks(DietPlan dietPlan, Action<ResponseMessage, DietPlan> callback)
        {
            if (_connectionStore.IsConnectionEstablished)
            {
                TransferModelToTaskItem(dietPlan);

                var scheduleItems = new ScheduleItemCollection();

                foreach (var taskItem in TodayTasks)
                {
                    var scheduleItem = new ScheduleItem()
                    {
                        UserId = dietPlan.User.Id,
                        ConnectionId = _connectionStore.ConnectionId,
                        StartTime = taskItem.StartTime,
                        Message = TransferTaskItemToXml(taskItem)
                    };
                    scheduleItems.Add(scheduleItem);
                }

                AsychronousLoadHelper.AsychronousCall(() =>
                {
                    var scheduleService = new ScheduleService();
                    var response = scheduleService.AddSchedule(scheduleItems);
                    callback(response, dietPlan);
                });
            }
        }
 public void GetCompletedTasks(int userId, Action<ResponseMessage> callback)
 {
     AsychronousLoadHelper.AsychronousCall(() =>
     {
         var scheduleService = new ScheduleService();
         var response = scheduleService.GetCompletedTasks(userId);
         callback(response);
     });
 }
 public CreateDoctorSchedule()
 {
     InitializeComponent();
     scheduleService = new ScheduleService();
     ComboBoxItem cbm = null;
     dayOfWeekCombo.Items.Clear();
     for(int i=0; i<7; i++)
     {
         cbm = new ComboBoxItem();
         cbm.Content = (DayOfWeek)(i);
         cbm.Tag = i;
         dayOfWeekCombo.Items.Add(cbm);
     }
 }
 public CreateComponentCommandHandler(ILogger <CreateComponentCommandHandler> logger, IRepository <Order, string> repository, ScheduleService scheduleService)
 {
     _logger          = logger;
     _repository      = repository;
     _scheduleService = scheduleService;
 }
        /// <summary>
        /// Gets a list of available schedules for the group the selected sign-up person belongs to.
        /// </summary>
        /// <param name="groupGuid"></param>
        /// <returns></returns>
        private PersonScheduleSignupBag GetScheduleSignupData(Guid groupGuid)
        {
            List <PersonScheduleSignupDataBag> personScheduleSignups = new List <PersonScheduleSignupDataBag>();
            int numOfWeeks = FutureWeeksToShow;
            var startDate  = RockDateTime.Now.AddDays(1).Date;
            var endDate    = RockDateTime.Now.AddDays(numOfWeeks * 7);

            using (var rockContext = new RockContext())
            {
                var scheduleService                = new ScheduleService(rockContext);
                var attendanceService              = new AttendanceService(rockContext);
                var groupLocationService           = new GroupLocationService(rockContext);
                var groupService                   = new GroupService(rockContext);
                var personScheduleExclusionService = new PersonScheduleExclusionService(rockContext);

                var group = groupService.Get(groupGuid);
                var personGroupLocationList = GetApplicableGroupLocations(group, groupLocationService);

                var groupsThatHaveSchedulingRequirements          = personGroupLocationList.Where(a => a.Group.SchedulingMustMeetRequirements).Select(a => a.Group).Distinct().ToList();
                var personDoesntMeetSchedulingRequirementGroupIds = new HashSet <int>();

                // If the person does not meet the scheduling requirements for the current group.
                var personDoesntMeetSchedulingRequirements = groupService.GroupMembersNotMeetingRequirements(group, false, false)
                                                             .Where(a => a.Key.PersonId == CurrentPersonId)
                                                             .Any();

                if (personDoesntMeetSchedulingRequirements)
                {
                    personDoesntMeetSchedulingRequirementGroupIds.Add(group.Id);
                }

                // For every location in the location list.
                foreach (var personGroupLocation in personGroupLocationList)
                {
                    // Loop through each particular scheduling opportunity
                    foreach (var schedule in personGroupLocation.Schedules)
                    {
                        // Find if this has max volunteers here.
                        int maximumCapacitySetting = 0;
                        int desiredCapacitySetting = 0;
                        int minimumCapacitySetting = 0;
                        int desiredOrMinimumNeeded = 0;

                        if (personGroupLocation.GroupLocationScheduleConfigs.Any())
                        {
                            var groupConfigs = personGroupLocationList.Where(x => x.GroupId == personGroupLocation.GroupId).Select(x => x.GroupLocationScheduleConfigs);
                            foreach (var groupConfig in groupConfigs)
                            {
                                foreach (var config in groupConfig)
                                {
                                    if (config.ScheduleId == schedule.Id)
                                    {
                                        maximumCapacitySetting += config.MaximumCapacity ?? 0;
                                        desiredCapacitySetting += config.DesiredCapacity ?? 0;
                                        minimumCapacitySetting += config.MinimumCapacity ?? 0;
                                    }
                                }
                            }

                            desiredOrMinimumNeeded = Math.Max(desiredCapacitySetting, minimumCapacitySetting);
                        }

                        var startDateTimeList = schedule.GetScheduledStartTimes(startDate, endDate);

                        // For every start date time in the schedule, loop through to check if it is applicable to the current person. If so, we can add it to the master list.
                        foreach (var startDateTime in startDateTimeList)
                        {
                            var  occurrenceDate   = startDateTime.Date;
                            bool alreadyScheduled = attendanceService.IsScheduled(occurrenceDate, schedule.Id, CurrentPersonId);
                            if (alreadyScheduled)
                            {
                                continue;
                            }

                            // Don't show dates they have blacked out.
                            if (personScheduleExclusionService.IsExclusionDate(RequestContext.CurrentPerson.PrimaryAlias.PersonId, personGroupLocation.GroupId, occurrenceDate))
                            {
                                continue;
                            }

                            // Don't show groups that have scheduling requirements that the person hasn't met.
                            if (personDoesntMeetSchedulingRequirementGroupIds.Contains(personGroupLocation.GroupId))
                            {
                                continue;
                            }

                            // Get count of scheduled Occurrences with RSVP "Yes" for the group/schedule.
                            int currentScheduled = attendanceService
                                                   .Queryable()
                                                   .Where(a => a.Occurrence.OccurrenceDate == startDateTime.Date &&
                                                          a.Occurrence.ScheduleId == schedule.Id &&
                                                          a.RSVP == RSVP.Yes &&
                                                          a.Occurrence.GroupId == personGroupLocation.GroupId)
                                                   .Count();

                            bool maxScheduled = maximumCapacitySetting != 0 && currentScheduled >= maximumCapacitySetting;
                            int  peopleNeeded = desiredOrMinimumNeeded != 0 ? desiredOrMinimumNeeded - currentScheduled : 0;

                            // Add to master list personScheduleSignups.
                            personScheduleSignups.Add(new PersonScheduleSignupDataBag
                            {
                                GroupGuid         = personGroupLocation.Group.Guid,
                                GroupOrder        = personGroupLocation.Group.Order,
                                GroupName         = personGroupLocation.Group.Name,
                                LocationGuid      = personGroupLocation.Location.Guid,
                                LocationName      = personGroupLocation.Location.Name,
                                LocationOrder     = personGroupLocation.Order,
                                ScheduleGuid      = schedule.Guid,
                                ScheduleName      = schedule.Name,
                                ScheduledDateTime = startDateTime.ToRockDateTimeOffset(),
                                MaxScheduled      = maxScheduled,
                                PeopleNeeded      = peopleNeeded < 0 ? 0 : peopleNeeded
                            });
                        }
                    }
                }

                return(new PersonScheduleSignupBag
                {
                    GroupName = group.Name,
                    PersonScheduleSignups = personScheduleSignups
                });
            }
        }
 public DashboardDataHandle(IServiceProvider serviceProvider, IHttpReportsStorage storage, MonitorService monitorService, ScheduleService scheduleService, LocalizeService localizeService) : base(serviceProvider)
 {
     _storage         = storage;
     _monitorService  = monitorService;
     _scheduleService = scheduleService;
     _localizeService = localizeService;
 }
Exemple #7
0
        /// <summary>
        /// Maps the RLC data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        private void MapRLC(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext     = new RockContext();
            var importedLocations = lookupContext.Locations.AsNoTracking().Where(l => l.ForeignKey != null).ToList();
            var newGroups         = new List <Group>();

            var archivedScheduleName = "Archived Attendance";
            var archivedScheduleId   = new ScheduleService(lookupContext).Queryable()
                                       .Where(s => s.Name.Equals(archivedScheduleName, StringComparison.CurrentCultureIgnoreCase))
                                       .Select(s => ( int? )s.Id).FirstOrDefault();

            if (!archivedScheduleId.HasValue)
            {
                var archivedSchedule = AddNamedSchedule(lookupContext, archivedScheduleName, null, null, null,
                                                        ImportDateTime, archivedScheduleName.RemoveSpecialCharacters(), true, ImportPersonAliasId);
                archivedScheduleId = archivedSchedule.Id;
            }

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var completedItems = 0;
            var percentage     = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying group location import ({0:N0} found, {1:N0} already exist).", totalRows, importedLocations.Count));

            foreach (var row in tableData.Where(r => r != null))
            {
                // get the group and location data
                var rlcId             = row["RLC_ID"] as int?;
                var activityId        = row["Activity_ID"] as int?;
                var rlcName           = row["RLC_Name"] as string;
                var activityGroupId   = row["Activity_Group_ID"] as int?;
                var startAgeAttribute = row["Start_Age_Date"] as DateTime?;
                var endAgeAttribute   = row["End_Age_Date"] as DateTime?;
                var rlcActive         = row["Is_Active"] as Boolean?;
                var roomCode          = row["Room_Code"] as string;
                var roomDescription   = row["Room_Desc"] as string;
                var roomName          = row["Room_Name"] as string;
                var roomCapacity      = row["Max_Capacity"] as int?;
                var buildingName      = row["Building_Name"] as string;

                // get the parent group
                if (activityId.HasValue && !rlcName.Equals("Delete", StringComparison.CurrentCultureIgnoreCase))
                {
                    // get the mid-level activity if exists, otherwise the top-level activity
                    var lookupParentId = activityGroupId ?? activityId;

                    // add the child RLC group and locations
                    var parentGroup = ImportedGroups.FirstOrDefault(g => g.ForeignKey.Equals(lookupParentId.ToStringSafe()));
                    if (parentGroup != null)
                    {
                        if (rlcId.HasValue && !string.IsNullOrWhiteSpace(rlcName))
                        {
                            int?     parentLocationId = null;
                            Location campusLocation   = null;
                            // get the campus from the room, building, or parent
                            var rlcCampusId = GetCampusId(rlcName, false) ?? GetCampusId(buildingName, false) ?? parentGroup.CampusId;
                            if (rlcCampusId.HasValue)
                            {
                                var campus = lookupContext.Campuses.FirstOrDefault(c => c.Id == rlcCampusId);
                                if (campus != null)
                                {
                                    campusLocation = campus.Location ?? importedLocations.FirstOrDefault(l => l.ForeignKey.Equals(campus.ShortCode));
                                    if (campusLocation == null)
                                    {
                                        campusLocation = AddNamedLocation(lookupContext, null, campus.Name, campus.IsActive, null, ImportDateTime, campus.ShortCode, true, ImportPersonAliasId);
                                        importedLocations.Add(campusLocation);
                                        campus.LocationId = campusLocation.Id;
                                        lookupContext.SaveChanges();
                                    }

                                    parentLocationId = campusLocation.Id;
                                }
                            }

                            // set the location structure
                            Location roomLocation = null;
                            if (!string.IsNullOrWhiteSpace(roomName))
                            {
                                // get the building if it exists
                                Location buildingLocation = null;
                                if (!string.IsNullOrWhiteSpace(buildingName))
                                {
                                    buildingLocation = importedLocations.FirstOrDefault(l => l.ForeignKey.Equals(buildingName) && l.ParentLocationId == parentLocationId);
                                    if (buildingLocation == null)
                                    {
                                        buildingLocation = AddNamedLocation(lookupContext, parentLocationId, buildingName, rlcActive, null, ImportDateTime, buildingName, true, ImportPersonAliasId);
                                        importedLocations.Add(buildingLocation);
                                    }

                                    parentLocationId = buildingLocation.Id;
                                }

                                // get the room if it exists in the current structure
                                roomLocation = importedLocations.FirstOrDefault(l => l.ForeignKey.Equals(roomName) && l.ParentLocationId == parentLocationId);
                                if (roomLocation == null)
                                {
                                    roomLocation = AddNamedLocation(null, parentLocationId, roomName, rlcActive, roomCapacity, ImportDateTime, roomName, true, ImportPersonAliasId);
                                    importedLocations.Add(roomLocation);
                                }
                            }

                            // create the rlc group
                            var rlcGroup = ImportedGroups.FirstOrDefault(g => g.ForeignKey.Equals(rlcId.ToString()));
                            if (rlcGroup == null)
                            {
                                // don't save immediately, we'll batch add later
                                rlcGroup = AddGroup(null, parentGroup.GroupTypeId, parentGroup.Id, rlcName, rlcActive ?? true, rlcCampusId, null, rlcId.ToString(), false, ImportPersonAliasId, archivedScheduleId);

                                if (roomLocation != null)
                                {
                                    rlcGroup.GroupLocations.Add(new GroupLocation {
                                        LocationId = roomLocation.Id
                                    });
                                }

                                newGroups.Add(rlcGroup);
                            }
                        }

                        completedItems++;
                        if (completedItems % percentage < 1)
                        {
                            var percentComplete = completedItems / percentage;
                            ReportProgress(percentComplete, string.Format("{0:N0} location groups imported ({1}% complete).", completedItems, percentComplete));
                        }

                        if (completedItems % ReportingNumber < 1)
                        {
                            SaveGroups(newGroups);
                            ImportedGroups.AddRange(newGroups);
                            ReportPartialProgress();

                            // Reset lists and context
                            lookupContext = new RockContext();
                            newGroups.Clear();
                        }
                    }
                }
            }

            if (newGroups.Any())
            {
                SaveGroups(newGroups);
                ImportedGroups.AddRange(newGroups);
            }

            lookupContext.Dispose();
            ReportProgress(100, string.Format("Finished group location import: {0:N0} locations imported.", completedItems));
        }
Exemple #8
0
 public ScheduleController()
 {
     //TODO this should use Dependency Injection
     service = new ScheduleService();
 }
        /// <summary>
        /// opens a connection to the database and initializes necessary services
        /// </summary>
        private void OpenConnection()
        {
            try
            {
                DBConnection.CreateConnection("localhost", "xe", "hr", "hr");
            }
            catch (Exception)
            {
                try
                {
                    DBConnection.CreateConnection("localhost", "ORCL", "hr", "roxana");
                }
                catch (Exception e)
                {
                    throw e;
                }
            }

            credentialsService = new CredentialsService();
            administratorService = new AdministratorService();
            patientService = new PatientService();
            doctorService = new DoctorService();
            departmentService = new DepartmentService();
            appointmentService = new AppointmentService();
            resultService = new ResultsService();
            scheduleService = new ScheduleService();
        }
Exemple #10
0
 public void SetUp()
 {
     _clientMock = new Mock <IClient>();
     _service    = new ScheduleService(_clientMock.Object, _authInfo);
 }
Exemple #11
0
 public JsonDataController()
 {
     _scheduleService = new ScheduleService();
 }
Exemple #12
0
        /// <summary>
        /// Maps the attendance data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        private void MapAttendance(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext            = new RockContext();
            var newAttendances           = new List <Attendance>();
            var importedAttendancesCount = lookupContext.Attendances.AsNoTracking()
                                           .Count(a => a.ForeignKey != null);

            var importedCodes = lookupContext.AttendanceCodes.AsNoTracking()
                                .Where(c => c.ForeignKey != null).ToList();

            var importedDevices = lookupContext.Devices.AsNoTracking()
                                  .Where(d => d.DeviceTypeValueId == DeviceTypeCheckinKioskId).ToList();

            var newOccurrences      = new List <AttendanceOccurrence>();
            var existingOccurrences = new AttendanceOccurrenceService(lookupContext).Queryable().AsNoTracking()
                                      .Select(o => new
            {
                o.Id,
                o.GroupId,
                o.LocationId,
                o.ScheduleId,
                o.OccurrenceDate
            }).ToDictionary(k => $"{k.GroupId}|{k.LocationId}|{k.ScheduleId}|{k.OccurrenceDate}", v => v.Id);

            var archivedScheduleName = "Archived Attendance";
            var archivedSchedule     = new ScheduleService(lookupContext).Queryable()
                                       .FirstOrDefault(s => s.Name.Equals(archivedScheduleName));

            if (archivedSchedule == null)
            {
                archivedSchedule = AddNamedSchedule(lookupContext, archivedScheduleName, null, null, null,
                                                    ImportDateTime, archivedScheduleName.RemoveSpecialCharacters(), true, ImportPersonAliasId);
            }

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var completedItems = 0;
            var percentage     = (totalRows - 1) / 100 + 1;

            ReportProgress(0, $"Verifying attendance import ({importedAttendancesCount:N0} already exist).");

            foreach (var row in tableData.Where(r => r != null))
            {
                var rlcId          = row["RLC_ID"] as int?;
                var individualId   = row["Individual_ID"] as int?;
                var startDate      = row["Start_Date_Time"] as DateTime?;
                var attendanceCode = row["Tag_Code"] as string;
                var attendanceNote = row["BreakoutGroup_Name"] as string;
                var checkinDate    = row["Check_In_Time"] as DateTime?;
                var checkoutDate   = row["Check_Out_Time"] as DateTime?;
                var machineName    = row["Checkin_Machine_Name"] as string;

                // at minimum, attendance needs a person and a date
                var personKeys = GetPersonKeys(individualId, null);
                if (personKeys != null && personKeys.PersonAliasId > 0 && startDate.HasValue)
                {
                    // create the initial attendance
                    var attendance = new Attendance
                    {
                        PersonAliasId   = personKeys.PersonAliasId,
                        DidAttend       = true,
                        Note            = attendanceNote,
                        StartDateTime   = ( DateTime )startDate,
                        EndDateTime     = checkoutDate,
                        CreatedDateTime = checkinDate,
                        ForeignKey      = $"Attendance imported {ImportDateTime}"
                    };

                    // add the RLC info if it exists
                    int?rockGroupId     = null;
                    int?locationId      = null;
                    var startDateString = (( DateTime )startDate).Date;
                    if (rlcId.HasValue)
                    {
                        var rlcGroup = ImportedGroups.FirstOrDefault(g => g.ForeignId.Equals(rlcId));
                        rockGroupId         = rlcGroup?.Id;
                        locationId          = rlcGroup?.GroupLocations.Select(gl => ( int? )gl.LocationId).FirstOrDefault();
                        attendance.CampusId = rlcGroup?.CampusId;
                    }

                    // occurrence is required for attendance
                    int?occurrenceId = existingOccurrences.GetValueOrNull($"{rockGroupId}|{locationId}|{archivedSchedule.Id}|{startDateString}");
                    if (occurrenceId.HasValue)
                    {
                        attendance.OccurrenceId = occurrenceId.Value;
                    }
                    else
                    {
                        var newOccurrence = AddOccurrence(null, ( DateTime )startDate, rockGroupId, archivedSchedule.Id, locationId, true);
                        if (newOccurrence != null)
                        {
                            attendance.OccurrenceId = newOccurrence.Id;
                            existingOccurrences.Add($"{rockGroupId}|{locationId}|{archivedSchedule.Id}|{startDateString}", newOccurrence.Id);
                        }
                    }

                    // add the tag code
                    //if ( !string.IsNullOrWhiteSpace( attendanceCode ) )
                    //{
                    //var issueDatetime = checkinDate ?? (DateTime)startDate;
                    //var code = importedCodes.FirstOrDefault( c => c.Code.Equals( attendanceCode ) && c.IssueDateTime.Equals( issueDatetime ) );
                    //if ( code == null )
                    //{
                    //    code = new AttendanceCode
                    //    {
                    //        Code = attendanceCode,
                    //        IssueDateTime = issueDatetime,
                    //        ForeignKey = string.Format( "Attendance imported {0}", ImportDateTime )
                    //    };

                    //    lookupContext.AttendanceCodes.Add( code );
                    //    lookupContext.SaveChanges();
                    //    importedCodes.Add( code );
                    //}

                    //attendance.AttendanceCodeId = code.Id;
                    //}

                    // add the device
                    //if ( !string.IsNullOrWhiteSpace( machineName ) )
                    //{
                    //    var device = importedDevices.FirstOrDefault( d => d.Name.Equals( machineName, StringComparison.OrdinalIgnoreCase ) );
                    //    if ( device == null )
                    //    {
                    //        device = AddDevice( lookupContext, machineName, null, DeviceTypeCheckinKioskId, null, null, ImportDateTime,
                    //            $"{machineName} imported {ImportDateTime}", true, ImportPersonAliasId );
                    //        importedDevices.Add( device );
                    //    }

                    //    attendance.DeviceId = device.Id;
                    //}

                    newAttendances.Add(attendance);

                    completedItems++;
                    if (completedItems % percentage < 1)
                    {
                        var percentComplete = completedItems / percentage;
                        ReportProgress(percentComplete, $"{completedItems:N0} attendances imported ({percentComplete}% complete).");
                    }

                    if (completedItems % ReportingNumber < 1)
                    {
                        SaveAttendances(newAttendances, false);
                        ReportPartialProgress();

                        // Reset lists and context
                        lookupContext.Dispose();
                        lookupContext = new RockContext();
                        newAttendances.Clear();
                    }
                }
            }

            if (newAttendances.Any())
            {
                SaveAttendances(newAttendances, false);
            }

            lookupContext.Dispose();
            ReportProgress(100, $"Finished attendance import: {completedItems:N0} attendances imported.");
        }
Exemple #13
0
        /// <summary>
        /// Maps the groups attendance data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        private void MapGroupsAttendance(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext            = new RockContext();
            var newAttendances           = new List <Attendance>();
            var importedAttendancesCount = lookupContext.Attendances.AsNoTracking()
                                           .Count(a => a.ForeignKey != null && a.Occurrence.GroupId.HasValue && a.Occurrence.Group.GroupTypeId == GeneralGroupTypeId);

            var archivedScheduleName = "Archived Attendance";
            var archivedSchedule     = new ScheduleService(lookupContext).Queryable()
                                       .FirstOrDefault(s => s.Name.Equals(archivedScheduleName));

            if (archivedSchedule == null)
            {
                archivedSchedule = AddNamedSchedule(lookupContext, archivedScheduleName, null, null, null,
                                                    ImportDateTime, archivedScheduleName.RemoveSpecialCharacters(), true, ImportPersonAliasId);
            }

            var existingOccurrences = new AttendanceOccurrenceService(lookupContext).Queryable().AsNoTracking()
                                      .Select(o => new
            {
                o.Id,
                o.GroupId,
                o.LocationId,
                o.ScheduleId,
                o.OccurrenceDate
            }).ToDictionary(k => $"{k.GroupId}|{k.LocationId}|{k.ScheduleId}|{k.OccurrenceDate}", v => v.Id);

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var completedItems = 0;
            var percentage     = (totalRows - 1) / 100 + 1;

            ReportProgress(0, $"Verifying group attendance import, ({totalRows:N0} found, {importedAttendancesCount:N0} already exist).");

            foreach (var row in tableData.Where(r => r != null))
            {
                var groupId        = row["GroupID"] as int?;
                var startDate      = row["StartDateTime"] as DateTime?;
                var endDate        = row["EndDateTime"] as DateTime?;
                var attendanceNote = row["Comments"] as string;
                var wasPresent     = row["Individual_Present"] as int?;
                var individualId   = row["IndividualID"] as int?;
                var checkinDate    = row["CheckinDateTime"] as DateTime?;
                var checkoutDate   = row["CheckoutDateTime"] as DateTime?;
                var createdDate    = row["AttendanceCreatedDate"] as DateTime?;

                var personKeys = GetPersonKeys(individualId, null);
                if (personKeys != null && personKeys.PersonAliasId > 0 && startDate.HasValue)
                {
                    // create the initial attendance
                    var attendance = new Attendance
                    {
                        PersonAliasId   = personKeys.PersonAliasId,
                        DidAttend       = wasPresent != 0,
                        Note            = attendanceNote,
                        StartDateTime   = ( DateTime )startDate,
                        EndDateTime     = checkoutDate,
                        CreatedDateTime = checkinDate,
                        ForeignKey      = $"Group Attendance imported {ImportDateTime}"
                    };

                    // add the group info if it exists
                    int?rockGroupId     = null;
                    int?locationId      = null;
                    var startDateString = (( DateTime )startDate).Date;
                    if (groupId.HasValue)
                    {
                        var peopleGroup = ImportedGroups.FirstOrDefault(g => g.ForeignId.Equals(groupId));
                        rockGroupId         = peopleGroup?.Id;
                        locationId          = peopleGroup?.GroupLocations.Select(gl => ( int? )gl.LocationId).FirstOrDefault();
                        attendance.CampusId = peopleGroup?.CampusId;
                    }

                    // occurrence is required for attendance
                    int?occurrenceId = existingOccurrences.GetValueOrNull($"{rockGroupId}|{locationId}|{archivedSchedule.Id}|{startDateString}");
                    if (occurrenceId.HasValue)
                    {
                        attendance.OccurrenceId = occurrenceId.Value;
                    }
                    else
                    {
                        var newOccurrence = AddOccurrence(null, ( DateTime )startDate, rockGroupId, archivedSchedule.Id, locationId, true);
                        if (newOccurrence != null)
                        {
                            attendance.OccurrenceId = newOccurrence.Id;
                            existingOccurrences.Add($"{rockGroupId}|{locationId}|{archivedSchedule.Id}|{startDateString}", newOccurrence.Id);
                        }
                    }

                    newAttendances.Add(attendance);

                    completedItems++;
                    if (completedItems % percentage < 1)
                    {
                        var percentComplete = completedItems / percentage;
                        ReportProgress(percentComplete, $"{completedItems:N0} group attendances imported ({percentComplete}% complete).");
                    }

                    if (completedItems % ReportingNumber < 1)
                    {
                        SaveAttendances(newAttendances);
                        ReportPartialProgress();

                        // Reset lists and context
                        lookupContext.Dispose();
                        lookupContext = new RockContext();
                        newAttendances.Clear();
                    }
                }
            }

            if (newAttendances.Any())
            {
                SaveAttendances(newAttendances);
            }

            lookupContext.Dispose();
            ReportProgress(100, $"Finished group attendance import: {completedItems:N0} attendances imported.");
        }
Exemple #14
0
 public ScheduleController()
 {
     _scheduleService = new ScheduleService();
 }
Exemple #15
0
 public Live(StorageService storage, CookieService cookie, ProfileService profile, ScheduleService schedule, FollowService follow, NotificationService notification, EncryptionService encryption)
 {
     storageService      = storage;
     cookieService       = cookie;
     profileService      = profile;
     scheduleService     = schedule;
     followService       = follow;
     notificationService = notification;
     encryptionService   = encryption;
 }
Exemple #16
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap   = context.JobDetail.JobDataMap;
            var        groupType = GroupTypeCache.Read(dataMap.GetString("GroupType").AsGuid());

            if (groupType.TakesAttendance && groupType.SendAttendanceReminder)
            {
                // Get the occurrence dates that apply
                var dates = new List <DateTime>();
                dates.Add(RockDateTime.Today);
                try
                {
                    string[] reminderDays = dataMap.GetString("SendReminders").Split(',');
                    foreach (string reminderDay in reminderDays)
                    {
                        if (reminderDay.Trim() != string.Empty)
                        {
                            var reminderDate = RockDateTime.Today.AddDays(0 - Convert.ToInt32(reminderDay));
                            if (!dates.Contains(reminderDate))
                            {
                                dates.Add(reminderDate);
                            }
                        }
                    }
                }
                catch { }

                var rockContext        = new RockContext();
                var groupService       = new GroupService(rockContext);
                var groupMemberService = new GroupMemberService(rockContext);
                var scheduleService    = new ScheduleService(rockContext);
                var attendanceService  = new AttendanceService(rockContext);

                var startDate = dates.Min();
                var endDate   = dates.Max().AddDays(1);

                // Find all 'occurrences' for the groups that occur on the affected dates
                var occurrences = new Dictionary <int, List <DateTime> >();
                foreach (var group in groupService
                         .Queryable("Schedule").AsNoTracking()
                         .Where(g =>
                                g.GroupTypeId == groupType.Id &&
                                g.IsActive &&
                                g.Schedule != null &&
                                g.Members.Any(m =>
                                              m.GroupMemberStatus == GroupMemberStatus.Active &&
                                              m.GroupRole.IsLeader &&
                                              m.Person.Email != null &&
                                              m.Person.Email != "")))
                {
                    // Add the group
                    occurrences.Add(group.Id, new List <DateTime>());

                    // Check for a iCal schedule
                    DDay.iCal.Event calEvent = group.Schedule.GetCalenderEvent();
                    if (calEvent != null)
                    {
                        // If schedule has an iCal schedule, get occurrences between first and last dates
                        foreach (var occurrence in calEvent.GetOccurrences(startDate, endDate))
                        {
                            var startTime = occurrence.Period.StartTime.Value;
                            if (dates.Contains(startTime.Date))
                            {
                                occurrences[group.Id].Add(startTime);
                            }
                        }
                    }
                    else
                    {
                        // if schedule does not have an iCal, then check for weekly schedule and calculate occurrences starting with first attendance or current week
                        if (group.Schedule.WeeklyDayOfWeek.HasValue)
                        {
                            foreach (var date in dates)
                            {
                                if (date.DayOfWeek == group.Schedule.WeeklyDayOfWeek.Value)
                                {
                                    var startTime = date;
                                    if (group.Schedule.WeeklyTimeOfDay.HasValue)
                                    {
                                        startTime = startTime.Add(group.Schedule.WeeklyTimeOfDay.Value);
                                    }
                                    occurrences[group.Id].Add(startTime);
                                }
                            }
                        }
                    }
                }

                // Remove any occurrences during group type exclusion date ranges
                foreach (var exclusion in groupType.GroupScheduleExclusions)
                {
                    if (exclusion.Start.HasValue && exclusion.End.HasValue)
                    {
                        foreach (var keyVal in occurrences)
                        {
                            foreach (var occurrenceDate in keyVal.Value.ToList())
                            {
                                if (occurrenceDate >= exclusion.Start.Value &&
                                    occurrenceDate < exclusion.End.Value.AddDays(1))
                                {
                                    keyVal.Value.Remove(occurrenceDate);
                                }
                            }
                        }
                    }
                }

                // Remove any 'occurrenes' that already have attendance data entered
                foreach (var occurrence in attendanceService
                         .Queryable().AsNoTracking()
                         .Where(a =>
                                a.StartDateTime >= startDate &&
                                a.StartDateTime < endDate &&
                                occurrences.Keys.Contains(a.GroupId.Value) &&
                                a.ScheduleId.HasValue)
                         .Select(a => new
                {
                    GroupId = a.GroupId.Value,
                    a.StartDateTime
                })
                         .Distinct()
                         .ToList())
                {
                    occurrences[occurrence.GroupId].RemoveAll(d => d.Date == occurrence.StartDateTime.Date);
                }

                // Get the groups that have occurrences
                var groupIds = occurrences.Where(o => o.Value.Any()).Select(o => o.Key).ToList();

                // Get the leaders of those groups
                var leaders = groupMemberService
                              .Queryable("Group,Person").AsNoTracking()
                              .Where(m =>
                                     groupIds.Contains(m.GroupId) &&
                                     m.GroupMemberStatus == GroupMemberStatus.Active &&
                                     m.GroupRole.IsLeader &&
                                     m.Person.Email != null &&
                                     m.Person.Email != "")
                              .ToList();

                // Loop through the leaders
                foreach (var leader in leaders)
                {
                    foreach (var group in occurrences.Where(o => o.Key == leader.GroupId))
                    {
                        var mergeObjects = GlobalAttributesCache.GetMergeFields(leader.Person);
                        mergeObjects.Add("Person", leader.Person);
                        mergeObjects.Add("Group", leader.Group);
                        mergeObjects.Add("Occurrence", group.Value.Max());

                        var recipients = new List <RecipientData>();
                        recipients.Add(new RecipientData(leader.Person.Email, mergeObjects));

                        Email.Send(dataMap.GetString("SystemEmail").AsGuid(), recipients);
                    }
                }
            }
        }
 private void PopulateDepartmentsList()
 {
     _departmentService = new DepartmentService();
     _scheduleService = new ScheduleService();
     List<Department> allDepartments = _departmentService.FindAll();
     ComboBoxItem cbm;
     if (allDepartments != null)
     {
         foreach (Department d in allDepartments)
         {
             cbm = new ComboBoxItem();
             cbm.Content = d.Name;
             cbm.Tag = d.Id;
             comboBoxDepartments.Items.Add(cbm);
         }
     }
 }
Exemple #18
0
        /// <summary>
        /// Maps the activity group data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        private void MapActivityGroup(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext = new RockContext();
            var newGroups     = new List <Group>();

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var archivedScheduleName = "Archived Attendance";
            var archivedScheduleId   = new ScheduleService(lookupContext).Queryable()
                                       .Where(s => s.Name.Equals(archivedScheduleName, StringComparison.CurrentCultureIgnoreCase))
                                       .Select(s => ( int? )s.Id).FirstOrDefault();

            if (!archivedScheduleId.HasValue)
            {
                var archivedSchedule = AddNamedSchedule(lookupContext, archivedScheduleName, null, null, null,
                                                        ImportDateTime, archivedScheduleName.RemoveSpecialCharacters(), true, ImportPersonAliasId);
                archivedScheduleId = archivedSchedule.Id;
            }

            var completedItems = 0;
            var percentage     = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying activity import ({0:N0} found, {1:N0} already exist).", totalRows, ImportedGroups.Count));

            foreach (var row in tableData.Where(r => r != null))
            {
                // get the group data
                var activityId        = row["Activity_ID"] as int?;
                var activityGroupId   = row["Activity_Group_ID"] as int?;
                var superGroupId      = row["Activity_Super_Group_ID"] as int?;
                var activityGroupName = row["Activity_Group_Name"] as string;
                var superGroupName    = row["Activity_Super_Group"] as string;
                var balanceType       = row["CheckinBalanceType"] as string;

                // get the top-level activity group
                if (activityId.HasValue && !activityGroupName.Equals("Delete", StringComparison.CurrentCultureIgnoreCase))
                {
                    var parentGroup = ImportedGroups.FirstOrDefault(g => g.ForeignKey.Equals(activityId.ToString()));
                    if (parentGroup != null)
                    {
                        // add a level for the super group activity if it exists
                        int?parentGroupId = parentGroup.Id;
                        if (superGroupId.HasValue && !string.IsNullOrWhiteSpace(superGroupName))
                        {
                            var superGroup = ImportedGroups.FirstOrDefault(g => g.ForeignKey.Equals(superGroupId.ToString()));
                            if (superGroup == null)
                            {
                                superGroup = AddGroup(lookupContext, parentGroup.GroupTypeId, parentGroupId, superGroupName, parentGroup.IsActive, parentGroup.CampusId, null, superGroupId.ToString(), true, ImportPersonAliasId, archivedScheduleId);
                                ImportedGroups.Add(superGroup);
                                // set parent guid to super group
                                parentGroupId = superGroup.Id;
                            }
                        }

                        // add the child activity group
                        if (activityGroupId.HasValue && !string.IsNullOrWhiteSpace(activityGroupName))
                        {
                            var activityGroup = ImportedGroups.FirstOrDefault(g => g.ForeignKey.Equals(activityGroupId.ToString()));
                            if (activityGroup == null)
                            {
                                // don't save immediately, we'll batch add later
                                activityGroup = AddGroup(null, parentGroup.GroupTypeId, parentGroupId, activityGroupName, parentGroup.IsActive, parentGroup.CampusId, null, activityGroupId.ToString(), false, ImportPersonAliasId, archivedScheduleId);
                                newGroups.Add(activityGroup);
                            }
                        }

                        // #TODO: if Rock ever supports room balancing, check the F1 BalanceType

                        completedItems++;
                        if (completedItems % percentage < 1)
                        {
                            var percentComplete = completedItems / percentage;
                            ReportProgress(percentComplete, string.Format("{0:N0} activities imported ({1}% complete).", completedItems, percentComplete));
                        }

                        if (completedItems % ReportingNumber < 1)
                        {
                            SaveGroups(newGroups);
                            ReportPartialProgress();
                            ImportedGroups.AddRange(newGroups);

                            // Reset lists and context
                            lookupContext = new RockContext();
                            newGroups.Clear();
                        }
                    }
                }
            }

            if (newGroups.Any())
            {
                SaveGroups(newGroups);
                ImportedGroups.AddRange(newGroups);
            }

            lookupContext.Dispose();
            ReportProgress(100, string.Format("Finished activity group import: {0:N0} activities imported.", completedItems));
        }
Exemple #19
0
        /// <summary>
        /// Maps the home group membership data.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        private void MapGroups(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext        = new RockContext();
            var newGroupMembers      = new List <GroupMember>();
            var importedGroupMembers = lookupContext.GroupMembers.Count(gm => gm.ForeignKey != null && gm.Group.GroupTypeId == GeneralGroupTypeId);
            var groupRoleMember      = GroupTypeCache.Get(GeneralGroupTypeId).Roles.FirstOrDefault(r => r.Name.Equals("Member"));

            var archivedScheduleName = "Archived Attendance";
            var archivedScheduleId   = new ScheduleService(lookupContext).Queryable()
                                       .Where(s => s.Name.Equals(archivedScheduleName, StringComparison.CurrentCultureIgnoreCase))
                                       .Select(s => ( int? )s.Id).FirstOrDefault();

            if (!archivedScheduleId.HasValue)
            {
                var archivedSchedule = AddNamedSchedule(lookupContext, archivedScheduleName, null, null, null,
                                                        ImportDateTime, archivedScheduleName.RemoveSpecialCharacters(), true, ImportPersonAliasId);
                archivedScheduleId = archivedSchedule.Id;
            }

            var groupsParentName = "Archived Groups";
            var archivedGroups   = ImportedGroups.FirstOrDefault(g => g.ForeignKey.Equals(groupsParentName.RemoveWhitespace()));

            if (archivedGroups == null)
            {
                archivedGroups = AddGroup(lookupContext, GeneralGroupTypeId, null, groupsParentName, true, null, ImportDateTime, groupsParentName.RemoveWhitespace(), true, ImportPersonAliasId);
                ImportedGroups.Add(archivedGroups);
            }

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var completedItems = 0;
            var percentage     = (totalRows - 1) / 100 + 1;

            ReportProgress(0, string.Format("Verifying people groups import ({0:N0} found, {1:N0} already exist).", totalRows, importedGroupMembers));

            foreach (var row in tableData.Where(r => r != null))
            {
                var groupId      = row["Group_ID"] as int?;
                var groupName    = row["Group_Name"] as string;
                var individualId = row["Individual_ID"] as int?;
                var groupCreated = row["Created_Date"] as DateTime?;
                var groupType    = row["Group_Type_Name"] as string;

                // require at least a group id and name
                if (groupId.HasValue && !string.IsNullOrWhiteSpace(groupName) && !groupName.Equals("Delete", StringComparison.CurrentCultureIgnoreCase))
                {
                    var peopleGroup = ImportedGroups.FirstOrDefault(g => g.ForeignKey.Equals(groupId.ToString()));
                    if (peopleGroup == null)
                    {
                        int?campusId           = null;
                        var parentGroupId      = archivedGroups.Id;
                        var currentGroupTypeId = GeneralGroupTypeId;
                        if (!string.IsNullOrWhiteSpace(groupType))
                        {
                            // check for a campus on the grouptype
                            campusId = GetCampusId(groupType, true, SearchDirection.Ends);
                            if (campusId.HasValue)
                            {
                                groupType = StripSuffix(groupType, campusId);
                            }

                            // add the grouptype if it doesn't exist
                            var currentGroupType = ImportedGroupTypes.FirstOrDefault(t => t.ForeignKey.Equals(groupType, StringComparison.CurrentCultureIgnoreCase));
                            if (currentGroupType == null)
                            {
                                // save immediately so we can use the grouptype for a group
                                currentGroupType = AddGroupType(lookupContext, groupType, string.Format("{0} imported {1}", groupType, ImportDateTime), null,
                                                                null, null, true, true, true, true, typeForeignKey: groupType);
                                ImportedGroupTypes.Add(currentGroupType);
                            }

                            // create a placeholder group for the grouptype if it doesn't exist
                            var groupTypePlaceholder = ImportedGroups.FirstOrDefault(g => g.GroupTypeId == currentGroupType.Id && g.ForeignKey.Equals(groupType.RemoveWhitespace()));
                            if (groupTypePlaceholder == null)
                            {
                                groupTypePlaceholder = AddGroup(lookupContext, currentGroupType.Id, archivedGroups.Id, groupType, true, null, ImportDateTime,
                                                                groupType.RemoveWhitespace(), true, ImportPersonAliasId);
                                ImportedGroups.Add(groupTypePlaceholder);
                            }

                            parentGroupId      = groupTypePlaceholder.Id;
                            currentGroupTypeId = currentGroupType.Id;
                        }

                        // put the current group under a campus parent if it exists
                        campusId = campusId ?? GetCampusId(groupName);
                        if (campusId.HasValue)
                        {
                            // create a campus level parent for the home group
                            var campus      = CampusList.FirstOrDefault(c => c.Id == campusId);
                            var campusGroup = ImportedGroups.FirstOrDefault(g => g.ForeignKey.Equals(campus.ShortCode) && g.ParentGroupId == parentGroupId);
                            if (campusGroup == null)
                            {
                                campusGroup = AddGroup(lookupContext, currentGroupTypeId, parentGroupId, campus.Name, true, campus.Id, ImportDateTime, campus.ShortCode, true, ImportPersonAliasId);
                                ImportedGroups.Add(campusGroup);
                            }

                            parentGroupId = campusGroup.Id;
                        }

                        // add the group, finally
                        peopleGroup = AddGroup(lookupContext, currentGroupTypeId, parentGroupId, groupName, true, campusId, null, groupId.ToString(), true, ImportPersonAliasId, archivedScheduleId);
                        ImportedGroups.Add(peopleGroup);
                    }

                    // add the group member
                    var personKeys = GetPersonKeys(individualId, null);
                    if (personKeys != null)
                    {
                        newGroupMembers.Add(new GroupMember
                        {
                            IsSystem          = false,
                            GroupId           = peopleGroup.Id,
                            PersonId          = personKeys.PersonId,
                            GroupRoleId       = groupRoleMember.Id,
                            GroupMemberStatus = GroupMemberStatus.Active,
                            ForeignKey        = string.Format("Membership imported {0}", ImportDateTime)
                        });

                        completedItems++;
                    }

                    if (completedItems % percentage < 1)
                    {
                        var percentComplete = completedItems / percentage;
                        ReportProgress(percentComplete, string.Format("{0:N0} group members imported ({1}% complete).", completedItems, percentComplete));
                    }

                    if (completedItems % ReportingNumber < 1)
                    {
                        SaveGroupMembers(newGroupMembers);
                        ReportPartialProgress();

                        // Reset lists and context
                        lookupContext = new RockContext();
                        newGroupMembers.Clear();
                    }
                }
            }

            if (newGroupMembers.Any())
            {
                SaveGroupMembers(newGroupMembers);
            }

            lookupContext.Dispose();
            ReportProgress(100, string.Format("Finished people groups import: {0:N0} members imported.", completedItems));
        }
 //Construct for dependency
 public SchedulesController(ScheduleService scheduleService, TeamService teamService)
 {
     _scheduleService = scheduleService;
     _teamService     = teamService;
 }