Пример #1
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                AttendanceCode attendanceCode = null;
                DateTime       startDateTime  = RockDateTime.Now;

                bool reuseCodeForFamily = GetAttributeValue(action, "ReuseCodeForFamily").AsBoolean();

                int securityCodeLength = 3;
                if (!int.TryParse(GetAttributeValue(action, "SecurityCodeLength"), out securityCodeLength))
                {
                    securityCodeLength = 3;
                }

                var attendanceCodeService = new AttendanceCodeService(rockContext);
                var attendanceService     = new AttendanceService(rockContext);
                var groupMemberService    = new GroupMemberService(rockContext);
                var personAliasService    = new PersonAliasService(rockContext);

                foreach (var family in checkInState.CheckIn.Families.Where(f => f.Selected))
                {
                    foreach (var person in family.People.Where(p => p.Selected))
                    {
                        if (reuseCodeForFamily && attendanceCode != null)
                        {
                            person.SecurityCode = attendanceCode.Code;
                        }
                        else
                        {
                            attendanceCode      = AttendanceCodeService.GetNew(securityCodeLength);
                            person.SecurityCode = attendanceCode.Code;
                        }

                        foreach (var groupType in person.GroupTypes.Where(g => g.Selected))
                        {
                            foreach (var group in groupType.Groups.Where(g => g.Selected))
                            {
                                foreach (var location in group.Locations.Where(l => l.Selected))
                                {
                                    if (groupType.GroupType.AttendanceRule == AttendanceRule.AddOnCheckIn &&
                                        groupType.GroupType.DefaultGroupRoleId.HasValue &&
                                        !groupMemberService.GetByGroupIdAndPersonId(group.Group.Id, person.Person.Id, true).Any())
                                    {
                                        var groupMember = new GroupMember();
                                        groupMember.GroupId     = group.Group.Id;
                                        groupMember.PersonId    = person.Person.Id;
                                        groupMember.GroupRoleId = groupType.GroupType.DefaultGroupRoleId.Value;
                                        groupMemberService.Add(groupMember);
                                    }

                                    foreach (var schedule in location.Schedules.Where(s => s.Selected))
                                    {
                                        // Only create one attendance record per day for each person/schedule/group/location
                                        var attendance = attendanceService.Get(startDateTime, location.Location.Id, schedule.Schedule.Id, group.Group.Id, person.Person.Id);
                                        if (attendance == null)
                                        {
                                            var primaryAlias = personAliasService.GetPrimaryAlias(person.Person.Id);
                                            if (primaryAlias != null)
                                            {
                                                attendance                   = rockContext.Attendances.Create();
                                                attendance.LocationId        = location.Location.Id;
                                                attendance.CampusId          = location.CampusId;
                                                attendance.ScheduleId        = schedule.Schedule.Id;
                                                attendance.GroupId           = group.Group.Id;
                                                attendance.PersonAlias       = primaryAlias;
                                                attendance.PersonAliasId     = primaryAlias.Id;
                                                attendance.DeviceId          = checkInState.Kiosk.Device.Id;
                                                attendance.SearchTypeValueId = checkInState.CheckIn.SearchType.Id;
                                                attendanceService.Add(attendance);
                                            }
                                        }

                                        attendance.AttendanceCodeId = attendanceCode.Id;
                                        attendance.StartDateTime    = startDateTime;
                                        attendance.EndDateTime      = null;
                                        attendance.DidAttend        = true;

                                        KioskLocationAttendance.AddAttendance(attendance);
                                    }
                                }
                            }
                        }
                    }
                }

                rockContext.SaveChanges();
                return(true);
            }

            return(false);
        }
Пример #2
0
        protected void btnRecord_Click(object sender, EventArgs e)
        {
            var peopleIds = new List <int>();

            foreach (GridViewRow row in gResults.Rows)
            {
                CheckBox cb = (CheckBox)row.FindControl("chkSelect");
                if (cb.Checked)
                {
                    string dataKey = gResults.DataKeys[row.RowIndex].Value.ToString();
                    if (!String.IsNullOrEmpty(dataKey))
                    {
                        peopleIds.Add(Convert.ToInt32(dataKey));
                    }
                }
            }
            var campusWorshipAttendance = Session["campus-worship-attendance"] as List <CampusWorshipAttendance>;
            CampusWorshipAttendance selectedWorshipService = null;

            if (campusWorshipAttendance != null)
            {
                selectedWorshipService = campusWorshipAttendance.Find(m => m.Text == ddlWorshipService.SelectedValue);
            }
            Guid?groupGuid  = null;
            Guid?campusGuid = null;

            if (selectedWorshipService != null)
            {
                groupGuid  = selectedWorshipService.WorshipService.AsGuid();
                campusGuid = selectedWorshipService.Campus.AsGuid();
            }
            else
            {
                lblMessage.Text = "Could not record attendance, campus worship attendance not set";
                return;
            }
            var people = new PersonService(ctx).GetByIds(peopleIds);

            foreach (Person person in people)
            {
                var lastSunday        = GetLastSunday((DateTime)dpAttendanceDate.SelectedDate);
                var attendanceService = new AttendanceService(ctx);
                var attendance        = attendanceService.Queryable().Where(a => a.PersonAliasId == person.PrimaryAliasId &&
                                                                            a.SundayDate.Year == lastSunday.Year &&
                                                                            a.SundayDate.Month == lastSunday.Month &&
                                                                            a.SundayDate.Day == lastSunday.Day &&
                                                                            a.Group.Guid == groupGuid.Value &&
                                                                            a.Campus.Guid == campusGuid.Value).FirstOrDefault();
                if (attendance == null)
                {
                    attendanceService.Add(new Rock.Model.Attendance
                    {
                        PersonAlias   = person.PrimaryAlias,
                        StartDateTime = (DateTime)dpAttendanceDate.SelectedDate,
                        Group         = new GroupService(ctx).Get(groupGuid.Value),
                        Campus        = new CampusService(ctx).Get(campusGuid.Value),
                        DidAttend     = true
                    });
                    if (lblMessage.Text.Contains("Attendance Recorded For"))
                    {
                        lblMessage.Text += ", " + person.FirstName + " " + person.LastName;
                    }
                    else
                    {
                        lblMessage.Text += "Attendance Recorded For: " + person.FirstName + " " + person.LastName;
                    }
                }
                else
                {
                    lblMessage.Text += "Attendance Already Exists for " + person.FirstName + " " + person.LastName + "<BR>";
                }
            }

            ctx.SaveChanges();

            clearForm();
            clearResults();
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            RockPage.AddScriptLink("~/Scripts/CheckinClient/checkin-core.js");

            var bodyTag = this.Page.Master.FindControl("bodyTag") as HtmlGenericControl;

            if (bodyTag != null)
            {
                bodyTag.AddCssClass("checkin-groupselect-bg");
            }

            if (CurrentWorkflow == null || CurrentCheckInState == null)
            {
                NavigateToHomePage();
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    ClearSelection();

                    var person = CurrentCheckInState.CheckIn.CurrentPerson;
                    if (person == null)
                    {
                        GoBack();
                    }

                    var schedule = person.CurrentSchedule;

                    var groupTypes = person.SelectedGroupTypes(schedule);
                    if (groupTypes == null || !groupTypes.Any())
                    {
                        GoBack();
                    }

                    lTitle.Text = string.Format(GetAttributeValue("Title"), GetPersonScheduleSubTitle());

                    string groupTypeNames = groupTypes
                                            .Where(t => t.GroupType != null)
                                            .Select(t => t.GroupType.Name)
                                            .ToList().AsDelimited(", ");
                    lSubTitle.Text = string.Format(GetAttributeValue("SubTitle"), groupTypeNames);

                    lCaption.Text = GetAttributeValue("Caption");
                    var availGroups = groupTypes.SelectMany(t => t.GetAvailableGroups(schedule)).ToList();
                    //qr express checkin code - Ethan
                    var rockContext       = new RockContext();
                    var attendanceService = new AttendanceService(rockContext);
                    var availGroupsFromQR = attendanceService.Queryable()
                                            .Where(a =>
                                                   a.ForeignKey == CurrentCheckInState.CheckIn.SearchValue)
                                            .Select(a => a.Occurrence.Group.Id).FirstOrDefault();
                    availGroups.RemoveAll(g => g.Group.Id != availGroupsFromQR);
                    //


                    if (availGroups.Any())
                    {
                        if (availGroups.Count == 1)
                        {
                            if (UserBackedUp)
                            {
                                GoBack();
                            }
                            else
                            {
                                var group = availGroups.First();
                                if (schedule == null)
                                {
                                    group.Selected = true;
                                }
                                else
                                {
                                    group.SelectedForSchedule.Add(schedule.Schedule.Id);
                                }

                                ProcessSelection(person, schedule);
                            }
                        }
                        else
                        {
                            rSelection.DataSource = availGroups
                                                    .OrderBy(g => g.Group.Order)
                                                    .ToList();

                            rSelection.DataBind();
                        }
                    }
                    else
                    {
                        if (UserBackedUp)
                        {
                            GoBack();
                        }
                        else
                        {
                            pnlNoOptions.Visible   = true;
                            rSelection.Visible     = false;
                            lNoOptionName.Text     = person.Person.NickName;
                            lNoOptionSchedule.Text = person.CurrentSchedule != null?person.CurrentSchedule.ToString() : "this time";
                        }
                    }
                }
            }
        }
Пример #4
0
        public PrintSessionLabelsResponse PrintSessionLabels([FromUri] string session, [FromUri] int?kioskId = null, [FromUri] int?printerId = null, [FromUri] PrintSessionLabelsPrinterOverride printerOverride = PrintSessionLabelsPrinterOverride.Client)
        {
            List <Guid?> sessionGuids;
            bool         overrideClientPrinter = printerOverride == PrintSessionLabelsPrinterOverride.Client || printerOverride == PrintSessionLabelsPrinterOverride.Both;
            bool         overrideServerPrinter = printerOverride == PrintSessionLabelsPrinterOverride.Server || printerOverride == PrintSessionLabelsPrinterOverride.Both;

            //
            // The session data is a comma separated list of Guid values.
            //
            try
            {
                sessionGuids = session.SplitDelimitedValues()
                               .Select(a =>
                {
                    var guid = a.AsGuidOrNull();

                    //
                    // Check if this is a standard Guid format.
                    //
                    if (guid.HasValue)
                    {
                        return(guid.Value);
                    }

                    return(GuidHelper.FromShortStringOrNull(a));
                })
                               .ToList();
            }
            catch
            {
                sessionGuids = null;
            }

            //
            // If no session guids were found or an error occurred trying to
            // parse them, or the list was only nulls, then return an error.
            //
            if (sessionGuids == null || sessionGuids.Count == 0 || !sessionGuids.Any(i => i != null))
            {
                return(new PrintSessionLabelsResponse
                {
                    Labels = new List <CheckInLabel>(),
                    Messages = new List <string>
                    {
                        "No check-in sessions were specified."
                    }
                });
            }

            using (var rockContext = new RockContext())
            {
                KioskDevice printer = null;

                //
                // If they specified a kiosk, attempt to load the printer for
                // that kiosk.
                //
                if (printerId.HasValue && printerId.Value != 0)
                {
                    //
                    // We aren't technically loading a kiosk, but this lets us
                    // load the printer IP address from cache rather than hitting
                    // the database each time.
                    //
                    printer = KioskDevice.Get(printerId.Value, null);
                }
                else if (kioskId.HasValue && kioskId.Value != 0)
                {
                    var kiosk = KioskDevice.Get(kioskId.Value, null);
                    if ((kiosk?.Device?.PrinterDeviceId).HasValue)
                    {
                        //
                        // We aren't technically loading a kiosk, but this lets us
                        // load the printer IP address from cache rather than hitting
                        // the database each time.
                        //
                        printer = KioskDevice.Get(kiosk.Device.PrinterDeviceId.Value, null);
                    }
                }

                var attendanceService = new AttendanceService(rockContext);

                //
                // Retrieve all session label data from the database, then deserialize
                // it, then make one giant list of labels and finally order it.
                //
                var labels = attendanceService.Queryable()
                             .AsNoTracking()
                             .Where(a => sessionGuids.Contains(a.AttendanceCheckInSession.Guid) && a.AttendanceData != null)
                             .DistinctBy(a => a.AttendanceCheckInSessionId)
                             .Select(a => a.AttendanceData.LabelData)
                             .ToList()
                             .Select(a => a.FromJsonOrNull <List <CheckInLabel> >())
                             .Where(a => a != null)
                             .SelectMany(a => a)
                             .OrderBy(a => a.PersonId)
                             .ThenBy(a => a.Order)
                             .ToList();

                //
                // If there are no labels, then there is nothing more to do here.
                //
                if (!labels.Any())
                {
                    return(new PrintSessionLabelsResponse
                    {
                        Labels = new List <CheckInLabel>(),
                        Messages = new List <string>
                        {
                            "No labels to print. You're all set."
                        }
                    });
                }

                //
                // If the client has specified a printer override setting then we need to
                // check all labels and modify the target printer for any matching labels.
                //
                if (printer != null)
                {
                    foreach (var label in labels)
                    {
                        //
                        // If we are overriding client printed labels then update.
                        //
                        if (label.PrintTo == PrintTo.Kiosk && label.PrintFrom == PrintFrom.Client && overrideClientPrinter)
                        {
                            label.PrinterDeviceId = printer.Device.Id;
                            label.PrinterAddress  = printer.Device.IPAddress;
                        }

                        //
                        // If we are overriding server printed labels then update.
                        //
                        if (label.PrintTo == PrintTo.Kiosk && label.PrintFrom == PrintFrom.Server && overrideServerPrinter)
                        {
                            label.PrinterDeviceId = printer.Device.Id;
                            label.PrinterAddress  = printer.Device.IPAddress;
                        }
                    }
                }

                var response = new PrintSessionLabelsResponse
                {
                    Labels = labels.Where(l => l.PrintFrom == PrintFrom.Client).ToList()
                };

                //
                // Update any labels to convert the relative URL path to an absolute URL
                // path for client printing.
                //
                if (response.Labels.Any())
                {
                    var urlRoot = Request.RequestUri.GetLeftPart(UriPartial.Authority);

                    if (Request.Headers.Contains("X-Forwarded-Proto") && Request.Headers.Contains("X-Forwarded-Host"))
                    {
                        urlRoot = $"{Request.Headers.GetValues( "X-Forwarded-Proto" ).First()}://{Request.Headers.GetValues( "X-Forwarded-Host" ).First()}";
                    }
#if DEBUG
                    // This is extremely useful when debugging with ngrok and an iPad on the local network.
                    // X-Original-Host will contain the name of your ngrok hostname, therefore the labels will
                    // get a LabelFile url that will actually work with that iPad.
                    if (Request.Headers.Contains("X-Forwarded-Proto") && Request.Headers.Contains("X-Original-Host"))
                    {
                        urlRoot = $"{Request.Headers.GetValues( "X-Forwarded-Proto" ).First()}://{Request.Headers.GetValues( "X-Original-Host" ).First()}";
                    }
#endif
                    response.Labels.ForEach(l => l.LabelFile = urlRoot + l.LabelFile);
                }

                var printFromServer = labels.Where(l => l.PrintFrom == PrintFrom.Server).ToList();

                if (printFromServer.Any())
                {
                    var messages = ZebraPrint.PrintLabels(printFromServer);
                    response.Messages = messages;
                }

                return(response);
            }
        }
Пример #5
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (CurrentWorkflow == null || CurrentCheckInState == null)
            {
                NavigateToHomePage();
            }
            else
            {
                if (!Page.IsPostBack)
                {
                    try
                    {
                        lTitle.Text = GetAttributeValue("Title");

                        var printFromClient = new List <CheckInLabel>();
                        var printFromServer = new List <CheckInLabel>();

                        using (var rockContext = new RockContext())
                        {
                            var attendanceService = new AttendanceService(rockContext);

                            var now = RockDateTime.Now;

                            // Print the labels
                            foreach (var family in CurrentCheckInState.CheckIn.Families.Where(f => f.Selected))
                            {
                                foreach (var person in family.CheckOutPeople.Where(p => p.Selected))
                                {
                                    foreach (var attendance in attendanceService.Queryable()
                                             .Where(a => person.AttendanceIds.Contains(a.Id))
                                             .ToList())
                                    {
                                        attendance.EndDateTime = now;

                                        if (attendance.Group != null &&
                                            attendance.Location != null &&
                                            attendance.Schedule != null)
                                        {
                                            var li = new HtmlGenericControl("li");
                                            li.InnerText = string.Format(GetAttributeValue("DetailMessage"),
                                                                         person.ToString(), attendance.Group.ToString(), attendance.Location.ToString(), attendance.Schedule.Name);

                                            phResults.Controls.Add(li);
                                        }
                                    }

                                    if (person.Labels != null && person.Labels.Any())
                                    {
                                        printFromClient.AddRange(person.Labels.Where(l => l.PrintFrom == Rock.Model.PrintFrom.Client));
                                        printFromServer.AddRange(person.Labels.Where(l => l.PrintFrom == Rock.Model.PrintFrom.Server));
                                    }
                                }
                            }

                            rockContext.SaveChanges();
                        }

                        if (printFromClient.Any())
                        {
                            var urlRoot = string.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority);
                            printFromClient
                            .OrderBy(l => l.PersonId)
                            .ThenBy(l => l.Order)
                            .ToList()
                            .ForEach(l => l.LabelFile = urlRoot + l.LabelFile);
                            AddLabelScript(printFromClient.ToJson());
                        }

                        if (printFromServer.Any())
                        {
                            Socket socket    = null;
                            string currentIp = string.Empty;

                            foreach (var label in printFromServer
                                     .OrderBy(l => l.PersonId)
                                     .ThenBy(l => l.Order))
                            {
                                var labelCache = KioskLabel.Read(label.FileGuid);
                                if (labelCache != null)
                                {
                                    if (!string.IsNullOrWhiteSpace(label.PrinterAddress))
                                    {
                                        if (label.PrinterAddress != currentIp)
                                        {
                                            if (socket != null && socket.Connected)
                                            {
                                                socket.Shutdown(SocketShutdown.Both);
                                                socket.Close();
                                            }

                                            currentIp = label.PrinterAddress;
                                            var printerIp = new IPEndPoint(IPAddress.Parse(currentIp), 9100);

                                            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                                            IAsyncResult result  = socket.BeginConnect(printerIp, null, null);
                                            bool         success = result.AsyncWaitHandle.WaitOne(5000, true);
                                        }

                                        string printContent = labelCache.FileContent;
                                        foreach (var mergeField in label.MergeFields)
                                        {
                                            if (!string.IsNullOrWhiteSpace(mergeField.Value))
                                            {
                                                printContent = Regex.Replace(printContent, string.Format(@"(?<=\^FD){0}(?=\^FS)", mergeField.Key), ZebraFormatString(mergeField.Value));
                                            }
                                            else
                                            {
                                                // Remove the box preceding merge field
                                                printContent = Regex.Replace(printContent, string.Format(@"\^FO.*\^FS\s*(?=\^FT.*\^FD{0}\^FS)", mergeField.Key), string.Empty);
                                                // Remove the merge field
                                                printContent = Regex.Replace(printContent, string.Format(@"\^FD{0}\^FS", mergeField.Key), "^FD^FS");
                                            }
                                        }

                                        if (socket.Connected)
                                        {
                                            var    ns     = new NetworkStream(socket);
                                            byte[] toSend = System.Text.Encoding.ASCII.GetBytes(printContent);
                                            ns.Write(toSend, 0, toSend.Length);
                                        }
                                        else
                                        {
                                            phResults.Controls.Add(new LiteralControl("<br/>NOTE: Could not connect to printer!"));
                                        }
                                    }
                                }
                            }

                            if (socket != null && socket.Connected)
                            {
                                socket.Shutdown(SocketShutdown.Both);
                                socket.Close();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogException(ex);
                    }
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?    groupGuid          = null;
            Person   person             = null;
            DateTime attendanceDateTime = DateTime.MinValue;
            bool     addToGroup         = true;

            // get the group attribute
            Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid();

            if (!groupAttributeGuid.IsEmpty())
            {
                groupGuid = action.GetWorklowAttributeValue(groupAttributeGuid).AsGuidOrNull();

                if (!groupGuid.HasValue)
                {
                    errorMessages.Add("The group could not be found!");
                }
            }

            // get person alias guid
            Guid   personAliasGuid = Guid.Empty;
            string personAttribute = GetAttributeValue(action, "Person");

            Guid guid = personAttribute.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string value = action.GetWorklowAttributeValue(guid);
                    personAliasGuid = value.AsGuid();
                }

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable().AsNoTracking()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();
                }
                else
                {
                    errorMessages.Add("The person could not be found in the attribute!");
                }
            }

            // get attendance date
            Guid dateTimeAttributeGuid = GetAttributeValue(action, "AttendanceDatetime").AsGuid();

            if (!dateTimeAttributeGuid.IsEmpty())
            {
                string attributeDatetime = action.GetWorklowAttributeValue(dateTimeAttributeGuid);

                if (string.IsNullOrWhiteSpace(attributeDatetime))
                {
                    attendanceDateTime = RockDateTime.Now;
                }
                else
                {
                    if (!DateTime.TryParse(attributeDatetime, out attendanceDateTime))
                    {
                        errorMessages.Add(string.Format("Could not parse the date provided {0}.", attributeDatetime));
                    }
                }
            }

            // get add to group
            addToGroup = GetAttributeValue(action, "AddToGroup").AsBoolean();

            // get location
            Guid locationGuid          = Guid.Empty;
            Guid locationAttributeGuid = GetAttributeValue(action, "Location").AsGuid();

            if (!locationAttributeGuid.IsEmpty())
            {
                var locationAttribute = AttributeCache.Read(locationAttributeGuid, rockContext);

                if (locationAttribute != null)
                {
                    locationGuid = action.GetWorklowAttributeValue(locationAttributeGuid).AsGuid();
                }
            }

            // set attribute
            if (groupGuid.HasValue && person != null && attendanceDateTime != DateTime.MinValue)
            {
                var group = new GroupService(rockContext).Queryable("GroupType.DefaultGroupRole")
                            .Where(g => g.Guid == groupGuid)
                            .FirstOrDefault();
                if (group != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);

                    // get group member
                    var groupMember = groupMemberService.Queryable()
                                      .Where(m => m.Group.Guid == groupGuid &&
                                             m.PersonId == person.Id)
                                      .FirstOrDefault();
                    if (groupMember == null)
                    {
                        if (addToGroup)
                        {
                            if (group != null)
                            {
                                groupMember                   = new GroupMember();
                                groupMember.GroupId           = group.Id;
                                groupMember.PersonId          = person.Id;
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                groupMember.GroupRole         = group.GroupType.DefaultGroupRole;
                                groupMemberService.Add(groupMember);
                                rockContext.SaveChanges();
                            }
                        }
                        else
                        {
                            action.AddLogEntry(string.Format("{0} was not a member of the group {1} and the action was not configured to add them.", person.FullName, group.Name));
                            return(true);
                        }
                    }

                    AttendanceService attendanceService = new AttendanceService(rockContext);

                    Attendance attendance = new Attendance();
                    attendance.GroupId       = group.Id;
                    attendance.PersonAliasId = person.PrimaryAliasId;
                    attendance.StartDateTime = attendanceDateTime;
                    attendance.DidAttend     = true;

                    if (locationGuid != Guid.Empty)
                    {
                        var location = new LocationService(rockContext).Queryable().AsNoTracking()
                                       .Where(l => l.Guid == locationGuid)
                                       .FirstOrDefault();

                        if (location != null)
                        {
                            attendance.LocationId = location.Id;
                        }
                    }

                    attendanceService.Add(attendance);
                    rockContext.SaveChanges();

                    if (attendance.LocationId.HasValue)
                    {
                        Rock.CheckIn.KioskLocationAttendance.Flush(attendance.LocationId.Value);
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("Could not find group matching the guid '{0}'.", groupGuid));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
Пример #7
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] options = selection.Split('|');
            if (options.Length < 4)
            {
                return(null);
            }

            Guid           groupTypeGuid  = options[0].AsGuid();
            ComparisonType comparisonType = options[1].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo);
            int?           attended       = options[2].AsIntegerOrNull();
            string         slidingDelimitedValues;

            if (options[3].AsIntegerOrNull().HasValue)
            {
                //// selection was from when it just simply a LastXWeeks instead of Sliding Date Range
                // Last X Weeks was treated as "LastXWeeks * 7" days, so we have to convert it to a SlidingDateRange of Days to keep consistent behavior
                int lastXWeeks = options[3].AsIntegerOrNull() ?? 1;
                var fakeSlidingDateRangePicker = new SlidingDateRangePicker();
                fakeSlidingDateRangePicker.SlidingDateRangeMode = SlidingDateRangePicker.SlidingDateRangeType.Last;
                fakeSlidingDateRangePicker.TimeUnit             = SlidingDateRangePicker.TimeUnitType.Day;
                fakeSlidingDateRangePicker.NumberOfTimeUnits    = lastXWeeks * 7;
                slidingDelimitedValues = fakeSlidingDateRangePicker.DelimitedValues;
            }
            else
            {
                slidingDelimitedValues = options[3].Replace(',', '|');
            }

            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues);

            bool includeChildGroupTypes = options.Length >= 5 ? options[4].AsBooleanOrNull() ?? false : false;

            var groupTypeService = new GroupTypeService(new RockContext());

            var        groupType    = groupTypeService.Get(groupTypeGuid);
            List <int> groupTypeIds = new List <int>();

            if (groupType != null)
            {
                groupTypeIds.Add(groupType.Id);

                if (includeChildGroupTypes)
                {
                    var childGroupTypes = groupTypeService.GetAllAssociatedDescendents(groupType.Guid);
                    if (childGroupTypes.Any())
                    {
                        groupTypeIds.AddRange(childGroupTypes.Select(a => a.Id));

                        // get rid of any duplicates
                        groupTypeIds = groupTypeIds.Distinct().ToList();
                    }
                }
            }

            var rockContext   = serviceInstance.Context as RockContext;
            var attendanceQry = new AttendanceService(rockContext).Queryable().Where(a => a.DidAttend.HasValue && a.DidAttend.Value);

            if (dateRange.Start.HasValue)
            {
                var startDate = dateRange.Start.Value;
                attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate >= startDate);
            }

            if (dateRange.End.HasValue)
            {
                var endDate = dateRange.End.Value;
                attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate < endDate);
            }

            if (groupTypeIds.Count == 1)
            {
                int groupTypeId = groupTypeIds[0];
                attendanceQry = attendanceQry.Where(a => a.Occurrence.Group.GroupTypeId == groupTypeId);
            }
            else if (groupTypeIds.Count > 1)
            {
                attendanceQry = attendanceQry.Where(a => groupTypeIds.Contains(a.Occurrence.Group.GroupTypeId));
            }
            else
            {
                // no group type selected, so return nothing
                return(Expression.Constant(false));
            }

            var qry = new PersonService(rockContext).Queryable()
                      .Where(p => attendanceQry.Where(xx => xx.PersonAlias.PersonId == p.Id).Count() == attended);

            BinaryExpression compareEqualExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p") as BinaryExpression;
            BinaryExpression result = FilterExpressionExtractor.AlterComparisonType(comparisonType, compareEqualExpression, null);

            return(result);
        }
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            if (CurrentGroup != null)
            {
                if (ddlOccurence.SelectedValue.AsInteger() != 0)
                {
                    //The drop down stores the time in unix time
                    var occurenceDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)
                                        .AddSeconds(ddlOccurence.SelectedValue.AsInteger());

                    var attendanceData = new AttendanceService(_rockContext)
                                         .Queryable("PersonAlias")
                                         .Where(a => a.Occurrence.GroupId == CurrentGroup.Id && a.StartDateTime == occurenceDate);


                    var attendanceOccurenceService = new AttendanceOccurrenceService(_rockContext);
                    if (cbDidNotMeet.Checked == true)
                    {
                        var occurrence = attendanceOccurenceService.Get(occurenceDate.Date, CurrentGroup.Id, null, CurrentGroup.ScheduleId);
                        if (occurrence == null)
                        {
                            occurrence = new AttendanceOccurrence();
                            occurrence.OccurrenceDate = occurenceDate;
                            occurrence.GroupId        = CurrentGroup.Id;
                            occurrence.ScheduleId     = CurrentGroup.ScheduleId;
                            attendanceOccurenceService.Add(occurrence);
                        }
                        occurrence.DidNotOccur = true;
                        foreach (var attendee in occurrence.Attendees)
                        {
                            attendee.DidAttend = false;
                        }
                    }
                    else
                    {
                        var attendanceService  = new AttendanceService(_rockContext);
                        var personAliasService = new PersonAliasService(_rockContext);

                        foreach (var item in lvMembers.Items)
                        {
                            var hfMember       = item.FindControl("hfMember") as HiddenField;
                            var cbMember       = item.FindControl("cbMember") as HtmlInputCheckBox;
                            var personId       = hfMember.Value.AsInteger();
                            var attendanceItem = attendanceData.Where(a => a.PersonAlias.PersonId == personId)
                                                 .FirstOrDefault();
                            if (attendanceItem == null)
                            {
                                var attendancePerson = new PersonService(_rockContext).Get(personId);
                                if (attendancePerson != null && attendancePerson.PrimaryAliasId.HasValue)
                                {
                                    attendanceItem = attendanceService.AddOrUpdate(attendancePerson.PrimaryAliasId.Value, occurenceDate, CurrentGroup.Id, null, CurrentGroup.ScheduleId, CurrentGroup.CampusId);
                                }
                            }

                            if (attendanceItem != null)
                            {
                                attendanceItem.DidAttend = cbMember.Checked;
                            }
                        }
                    }
                }


                _rockContext.SaveChanges();
                nbNotice.Text = "Attendance Saved";
                nbNotice.NotificationBoxType = NotificationBoxType.Success;
                nbNotice.Visible             = true;
                nbNotice.Dismissable         = true;
            }
        }
Пример #9
0
 public AttendanceController(PeoheDbContext context, AttendanceService attendanceService)
 {
     dbContext = context;
     this.attendanceService = attendanceService;
 }
Пример #10
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState == null)
            {
                return(false);
            }

            AttendanceCode attendanceCode = null;

            bool reuseCodeForFamily             = checkInState.CheckInType != null && checkInState.CheckInType.ReuseSameCode;
            int  securityCodeAlphaNumericLength = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaNumericLength : 3;
            int  securityCodeAlphaLength        = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaLength : 0;
            int  securityCodeNumericLength      = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeNumericLength : 0;
            bool securityCodeNumericRandom      = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeNumericRandom : true;

            var attendanceCodeService = new AttendanceCodeService(rockContext);
            var attendanceService     = new AttendanceService(rockContext);
            var groupMemberService    = new GroupMemberService(rockContext);
            var personAliasService    = new PersonAliasService(rockContext);
            var attendanceRecords     = new List <Attendance>();

            AttendanceCheckInSession attendanceCheckInSession = new AttendanceCheckInSession()
            {
                DeviceId        = checkInState.DeviceId,
                ClientIpAddress = RockPage.GetClientIpAddress()
            };

            checkInState.Messages.Clear();

            var family = checkInState.CheckIn.CurrentFamily;

            if (family != null)
            {
                var currentOccurrences = new List <OccurrenceRecord>();
                foreach (var person in family.GetPeople(true))
                {
                    if (reuseCodeForFamily && attendanceCode != null)
                    {
                        person.SecurityCode = attendanceCode.Code;
                    }
                    else
                    {
                        attendanceCode      = AttendanceCodeService.GetNew(securityCodeAlphaNumericLength, securityCodeAlphaLength, securityCodeNumericLength, securityCodeNumericRandom);
                        person.SecurityCode = attendanceCode.Code;
                    }

                    foreach (var groupType in person.GetGroupTypes(true))
                    {
                        foreach (var group in groupType.GetGroups(true))
                        {
                            if (groupType.GroupType.AttendanceRule == AttendanceRule.AddOnCheckIn &&
                                groupType.GroupType.DefaultGroupRoleId.HasValue &&
                                !groupMemberService.GetByGroupIdAndPersonId(group.Group.Id, person.Person.Id, true).Any())
                            {
                                var groupMember = new GroupMember();
                                groupMember.GroupId     = group.Group.Id;
                                groupMember.PersonId    = person.Person.Id;
                                groupMember.GroupRoleId = groupType.GroupType.DefaultGroupRoleId.Value;
                                groupMemberService.Add(groupMember);
                            }

                            foreach (var location in group.GetLocations(true))
                            {
                                bool isCheckedIntoLocation = false;
                                foreach (var schedule in location.GetSchedules(true))
                                {
                                    var startDateTime = schedule.CampusCurrentDateTime;

                                    // If we're enforcing strict location thresholds, then before we create an attendance record
                                    // we need to check the location-schedule's current count.
                                    if (GetAttributeValue(action, "EnforceStrictLocationThreshold").AsBoolean() && location.Location.SoftRoomThreshold.HasValue)
                                    {
                                        var thresHold = location.Location.SoftRoomThreshold.Value;
                                        if (checkInState.ManagerLoggedIn && location.Location.FirmRoomThreshold.HasValue && location.Location.FirmRoomThreshold.Value > location.Location.SoftRoomThreshold.Value)
                                        {
                                            thresHold = location.Location.FirmRoomThreshold.Value;
                                        }

                                        var currentOccurrence = GetCurrentOccurrence(currentOccurrences, location, schedule, startDateTime.Date);

                                        // The totalAttended is the number of people still checked in (not people who have been checked-out)
                                        // not counting the current person who may already be checked in,
                                        // + the number of people we have checked in so far (but haven't been saved yet).
                                        var attendanceQry = attendanceService.GetByDateOnLocationAndSchedule(startDateTime.Date, location.Location.Id, schedule.Schedule.Id)
                                                            .AsNoTracking()
                                                            .Where(a => a.EndDateTime == null);

                                        // Only process if the current person is NOT already checked-in to this location and schedule
                                        if (!attendanceQry.Where(a => a.PersonAlias.PersonId == person.Person.Id).Any())
                                        {
                                            var totalAttended = attendanceQry.Count() + (currentOccurrence == null ? 0 : currentOccurrence.Count);

                                            // If over capacity, remove the schedule and add a warning message.
                                            if (totalAttended >= thresHold)
                                            {
                                                // Remove the schedule since the location was full for this schedule.
                                                location.Schedules.Remove(schedule);

                                                var message = new CheckInMessage()
                                                {
                                                    MessageType = MessageType.Warning
                                                };

                                                var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null);
                                                mergeFields.Add("Person", person.Person);
                                                mergeFields.Add("Group", group.Group);
                                                mergeFields.Add("Location", location.Location);
                                                mergeFields.Add("Schedule", schedule.Schedule);
                                                message.MessageText = GetAttributeValue(action, "NotChecked-InMessageFormat").ResolveMergeFields(mergeFields);

                                                // Now add it to the check-in state message list for others to see.
                                                checkInState.Messages.Add(message);
                                                continue;
                                            }
                                            else
                                            {
                                                // Keep track of anyone who was checked in so far.
                                                if (currentOccurrence == null)
                                                {
                                                    currentOccurrence = new OccurrenceRecord()
                                                    {
                                                        Date       = startDateTime.Date,
                                                        LocationId = location.Location.Id,
                                                        ScheduleId = schedule.Schedule.Id
                                                    };
                                                    currentOccurrences.Add(currentOccurrence);
                                                }

                                                currentOccurrence.Count += 1;
                                            }
                                        }
                                    }

                                    // Only create one attendance record per day for each person/schedule/group/location
                                    var attendance = attendanceService.Get(startDateTime, location.Location.Id, schedule.Schedule.Id, group.Group.Id, person.Person.Id);
                                    if (attendance == null)
                                    {
                                        var primaryAlias = personAliasService.GetPrimaryAlias(person.Person.Id);
                                        if (primaryAlias != null)
                                        {
                                            attendance = attendanceService.AddOrUpdate(primaryAlias.Id, startDateTime.Date, group.Group.Id,
                                                                                       location.Location.Id, schedule.Schedule.Id, location.CampusId,
                                                                                       checkInState.Kiosk.Device.Id, checkInState.CheckIn.SearchType.Id,
                                                                                       checkInState.CheckIn.SearchValue, family.Group.Id, attendanceCode.Id);

                                            attendance.PersonAlias = primaryAlias;
                                        }
                                    }

                                    attendance.AttendanceCheckInSession = attendanceCheckInSession;

                                    attendance.DeviceId                 = checkInState.Kiosk.Device.Id;
                                    attendance.SearchTypeValueId        = checkInState.CheckIn.SearchType.Id;
                                    attendance.SearchValue              = checkInState.CheckIn.SearchValue;
                                    attendance.CheckedInByPersonAliasId = checkInState.CheckIn.CheckedInByPersonAliasId;
                                    attendance.SearchResultGroupId      = family.Group.Id;
                                    attendance.AttendanceCodeId         = attendanceCode.Id;
                                    attendance.StartDateTime            = startDateTime;
                                    attendance.EndDateTime              = null;
                                    attendance.DidAttend                = true;
                                    attendance.Note = group.Notes;

                                    KioskLocationAttendance.AddAttendance(attendance);
                                    isCheckedIntoLocation = true;

                                    // Keep track of attendance (Ids) for use by other actions later in the workflow pipeline
                                    attendanceRecords.Add(attendance);
                                }

                                // If the person was NOT checked into the location for any schedule then remove the location
                                if (!isCheckedIntoLocation)
                                {
                                    group.Locations.Remove(location);
                                }
                            }
                        }
                    }
                }
            }

            rockContext.SaveChanges();

            // Now that the records are persisted, take the Ids and save them to the temp CheckInFamliy object
            family.AttendanceIds = attendanceRecords.Select(a => a.Id).ToList();
            family.AttendanceCheckinSessionGuid = attendanceCheckInSession.Guid;
            attendanceRecords = null;

            return(true);
        }
Пример #11
0
        /// <summary>
        /// Renders the specified writer.
        /// </summary>
        /// <param name="badge">The badge.</param>
        /// <param name="writer">The writer.</param>
        public override void Render(BadgeCache badge, System.Web.UI.HtmlTextWriter writer)
        {
            if (Person == null)
            {
                return;
            }

            Guid?groupTypeGuid = GetAttributeValue(badge, "GroupType").AsGuidOrNull();

            if (groupTypeGuid.HasValue)
            {
                var lavaTemplate = this.GetAttributeValue(badge, "LavaTemplate");
                var slidingDateRangeDelimitedValues = this.GetAttributeValue(badge, "DateRange");
                var dateRange        = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDateRangeDelimitedValues);
                var dateRangeSummary = SlidingDateRangePicker.FormatDelimitedValues(slidingDateRangeDelimitedValues);

                var mergeFields = Lava.LavaHelper.GetCommonMergeFields(null, null, new Lava.CommonMergeFieldsOptions {
                    GetLegacyGlobalMergeFields = false
                });
                mergeFields.Add("Person", this.Person);
                using (var rockContext = new RockContext())
                {
                    var groupType   = GroupTypeCache.Get(groupTypeGuid.Value);
                    int groupTypeId = groupType?.Id ?? 0;
                    mergeFields.Add("GroupType", groupType);
                    mergeFields.Add("Badge", badge);
                    mergeFields.Add("DateRange", new { Dates = dateRange, Summary = dateRangeSummary });

                    var personAliasIds = Person.Aliases.Select(a => a.Id).ToList();

                    var attendanceQuery = new AttendanceService(rockContext)
                                          .Queryable()
                                          .Where(a =>
                                                 a.Occurrence.Group != null &&
                                                 a.Occurrence.Group.GroupTypeId == groupTypeId &&
                                                 a.DidAttend == true &&
                                                 personAliasIds.Contains(a.PersonAliasId.Value));

                    if (dateRange.Start.HasValue)
                    {
                        attendanceQuery = attendanceQuery.Where(a => a.StartDateTime >= dateRange.Start.Value);
                    }

                    if (dateRange.End.HasValue)
                    {
                        attendanceQuery = attendanceQuery.Where(a => a.StartDateTime < dateRange.End.Value);
                    }

                    var attendanceDateTimes = attendanceQuery.Select(a => a.StartDateTime).ToList();

                    if (attendanceDateTimes.Any())
                    {
                        var attendanceResult = new
                        {
                            Count        = attendanceDateTimes.Count(),
                            LastDateTime = attendanceDateTimes.Max()
                        };

                        mergeFields.Add("Attendance", attendanceResult);
                    }

                    string output = lavaTemplate.ResolveMergeFields(mergeFields);

                    writer.Write(output);
                }
            }
        }
Пример #12
0
        /// <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
                });
            }
        }
Пример #13
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);
                    }
                }
            }
        }
Пример #14
0
        public static List <CheckInLabel> GenerateLabels(List <Person> people, Device kioskDevice, Guid?aggregateLabelGuid)
        {
            var labels            = new List <CheckInLabel>();
            var globalAttributes  = Rock.Web.Cache.GlobalAttributesCache.Get();
            var globalMergeValues = Rock.Lava.LavaHelper.GetCommonMergeFields(null);

            RockContext       rockContext       = new RockContext();
            AttendanceService attendanceService = new AttendanceService(rockContext);

            foreach (var person in people)
            {
                var attendances = AttendanceCache.All()
                                  .Where(a => a.PersonId == person.Id && a.AttendanceState != AttendanceState.CheckedOut)
                                  .ToList();

                if (!attendances.Any())
                {
                    continue;
                }

                var groupIds = attendances.Select(a => a.GroupId).Distinct().ToList();

                GroupService groupService = new GroupService(new RockContext());
                var          groupTypeIds = groupService.Queryable()
                                            .Where(g => groupIds.Contains(g.Id))
                                            .Select(g => g.GroupTypeId)
                                            .Distinct()
                                            .ToList();

                var groupTypes = groupTypeIds
                                 .Select(i => GroupTypeCache.Get(i))
                                 .OrderBy(gt => gt.Order)
                                 .ToList();

                List <Guid> labelGuids = new List <Guid>();

                var mergeObjects = new Dictionary <string, object>();
                foreach (var keyValue in globalMergeValues)
                {
                    mergeObjects.Add(keyValue.Key, keyValue.Value);
                }

                var checkinPerson = new CheckInPerson
                {
                    Person       = person,
                    SecurityCode = attendances.OrderByDescending(a => a.CreatedDateTime).FirstOrDefault().Code
                };

                mergeObjects.Add("Person", checkinPerson);
                mergeObjects.Add("GroupTypes", groupTypes);
                List <Rock.Model.Group> mergeGroups    = new List <Rock.Model.Group>();
                List <Location>         mergeLocations = new List <Location>();
                List <Schedule>         mergeSchedules = new List <Schedule>();

                var sets = attendanceService
                           .Queryable().AsNoTracking().Where(a =>
                                                             a.PersonAlias.Person.Id == person.Id &&
                                                             a.StartDateTime >= Rock.RockDateTime.Today &&
                                                             a.EndDateTime == null &&
                                                             a.Occurrence.Group != null &&
                                                             a.Occurrence.Schedule != null &&
                                                             a.Occurrence.Location != null
                                                             )
                           .Select(a =>
                                   new
                {
                    Group          = a.Occurrence.Group,
                    Location       = a.Occurrence.Location,
                    Schedule       = a.Occurrence.Schedule,
                    AttendanceGuid = a.Guid
                }
                                   )
                           .ToList()
                           .OrderBy(a => a.Schedule.StartTimeOfDay);

                //Load breakout group
                var breakoutGroupItems = GetBreakoutGroupItems(person);

                //Add in an empty object as a placeholder for our breakout group
                mergeObjects.Add("BreakoutGroup", "");

                //Add in GUID for QR code
                if (sets.Any())
                {
                    mergeObjects.Add("AttendanceGuid", sets.FirstOrDefault().AttendanceGuid.ToString());
                }

                foreach (var set in sets)
                {
                    mergeGroups.Add(set.Group);
                    mergeLocations.Add(set.Location);
                    mergeSchedules.Add(set.Schedule);

                    //Add the breakout group mergefield
                    if (breakoutGroupItems.Any())
                    {
                        var breakoutGroupItem = breakoutGroupItems.Where(g => g.ScheduleId == set.Schedule.Id).FirstOrDefault();
                        if (breakoutGroupItem != null)
                        {
                            mergeObjects["BreakoutGroup"] = breakoutGroupItem.Letter;
                        }
                    }
                }
                mergeObjects.Add("Groups", mergeGroups);
                mergeObjects.Add("Locations", mergeLocations);
                mergeObjects.Add("Schedules", mergeSchedules);

                foreach (var groupType in groupTypes)
                {
                    var groupTypeLabels = new List <CheckInLabel>();

                    GetGroupTypeLabels(groupType, groupTypeLabels, mergeObjects, labelGuids);

                    var PrinterIPs = new Dictionary <int, string>();

                    foreach (var label in groupTypeLabels)
                    {
                        label.PrintFrom = kioskDevice.PrintFrom;
                        label.PrintTo   = kioskDevice.PrintToOverride;

                        if (label.PrintTo == PrintTo.Default)
                        {
                            label.PrintTo = groupType.AttendancePrintTo;
                        }

                        if (label.PrintTo == PrintTo.Kiosk)
                        {
                            var device = kioskDevice;
                            if (device != null)
                            {
                                label.PrinterDeviceId = device.PrinterDeviceId;
                            }
                        }

                        if (label.PrinterDeviceId.HasValue)
                        {
                            if (PrinterIPs.ContainsKey(label.PrinterDeviceId.Value))
                            {
                                label.PrinterAddress = PrinterIPs[label.PrinterDeviceId.Value];
                            }
                            else
                            {
                                var printerDevice = new DeviceService(rockContext).Get(label.PrinterDeviceId.Value);
                                if (printerDevice != null)
                                {
                                    PrinterIPs.Add(printerDevice.Id, printerDevice.IPAddress);
                                    label.PrinterAddress = printerDevice.IPAddress;
                                }
                            }
                        }
                        labels.Add(label);
                    }
                }
            }
            if (aggregateLabelGuid.HasValue)
            {
                labels.AddRange(GenerateAggregateLabel(aggregateLabelGuid.Value, kioskDevice, people));
            }

            return(labels);
        }
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] options = selection.Split('|');
            if (options.Length < 4)
            {
                return(null);
            }

            Guid groupTypeGuid = options[0].AsGuid();

            var        campusGuidList = options[0].Split(',').AsGuidList();
            List <int> campusIds      = new List <int>();

            foreach (var campusGuid in campusGuidList)
            {
                var campus = CampusCache.Get(campusGuid);
                if (campus != null)
                {
                    campusIds.Add(campus.Id);
                }
            }

            if (!campusIds.Any())
            {
                return(null);
            }

            ComparisonType comparisonType = options[1].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo);
            int?           attended       = options[2].AsIntegerOrNull();
            string         slidingDelimitedValues;

            if (options[3].AsIntegerOrNull().HasValue)
            {
                //// selection was from when it just simply a LastXWeeks instead of Sliding Date Range
                // Last X Weeks was treated as "LastXWeeks * 7" days, so we have to convert it to a SlidingDateRange of Days to keep consistent behavior
                int lastXWeeks = options[3].AsIntegerOrNull() ?? 1;
                var fakeSlidingDateRangePicker = new SlidingDateRangePicker();
                fakeSlidingDateRangePicker.SlidingDateRangeMode = SlidingDateRangePicker.SlidingDateRangeType.Last;
                fakeSlidingDateRangePicker.TimeUnit             = SlidingDateRangePicker.TimeUnitType.Day;
                fakeSlidingDateRangePicker.NumberOfTimeUnits    = lastXWeeks * 7;
                slidingDelimitedValues = fakeSlidingDateRangePicker.DelimitedValues;
            }
            else
            {
                slidingDelimitedValues = options[3].Replace(',', '|');
            }

            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues);

            var rockContext   = serviceInstance.Context as RockContext;
            var attendanceQry = new AttendanceService(rockContext).Queryable().Where(a => a.DidAttend.HasValue && a.DidAttend.Value);

            attendanceQry = attendanceQry.Where(a => a.CampusId.HasValue && campusIds.Contains((int)a.CampusId));

            if (dateRange.Start.HasValue)
            {
                var startDate = dateRange.Start.Value;
                attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate >= startDate);
            }

            if (dateRange.End.HasValue)
            {
                var endDate = dateRange.End.Value;
                attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate < endDate);
            }

            var qry = new PersonService(rockContext).Queryable()
                      .Where(p => attendanceQry.Count(xx => xx.PersonAlias.PersonId == p.Id) == attended);

            var compareEqualExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p") as BinaryExpression;
            var result = FilterExpressionExtractor.AlterComparisonType(comparisonType, compareEqualExpression, null);

            return(result);
        }
        private void BindDropDown()
        {
            RockContext rockContext = new RockContext();

            if (CurrentGroup.Schedule != null)
            {
                AttendanceService attendanceService = new AttendanceService(rockContext);
                var occurances = attendanceService.Queryable().Where(a => a.Occurrence.GroupId == CurrentGroup.Id)
                                 .DistinctBy(s => s.StartDateTime)
                                 .Select(s => s.StartDateTime)
                                 .Take(50)
                                 .ToList()
                                 .Select(s => new
                {
                    Id   = (s - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds,
                    Name = s.ToString("MMM d, yyyy -  h:mmtt")
                })
                                 .ToList();

                if (CurrentGroup.Schedule.ScheduleType == ScheduleType.Named ||
                    CurrentGroup.Schedule.ScheduleType == ScheduleType.Custom)
                {
                    var prevSchedules = CurrentGroup.Schedule
                                        .GetScheduledStartTimes(Rock.RockDateTime.Today.AddYears(-1), Rock.RockDateTime.Today.AddDays(1))
                                        .OrderByDescending(o => o)
                                        .Take(10)
                                        .Select(s => new
                    {
                        Id   = (s - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds,
                        Name = s.ToString("MMM d, yyyy -  h:mmtt")
                    })
                                        .Where(a => !occurances.Select(o => o.Id).Contains(a.Id))
                                        .ToList();
                    occurances.AddRange(prevSchedules);
                }
                else if (CurrentGroup.Schedule.ScheduleType == ScheduleType.Weekly)
                {
                    var schedules = new List <DateTime>();

                    DateTime lastSchedule = Rock.RockDateTime.Today;
                    //Crawl backward to find the last time this occured
                    while (lastSchedule.DayOfWeek != CurrentGroup.Schedule.WeeklyDayOfWeek)
                    {
                        lastSchedule = lastSchedule.AddDays(-1);
                    }
                    lastSchedule = lastSchedule.AddMinutes(CurrentGroup.Schedule.WeeklyTimeOfDay.Value.TotalMinutes);
                    schedules.Add(lastSchedule);
                    for (int i = 1; i < 10; i++)
                    {
                        schedules.Add(lastSchedule.AddDays(i * -7));
                    }
                    occurances.AddRange(schedules
                                        .Select(s => new
                    {
                        Id   = (s - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds,
                        Name = s.ToString("MMM d, yyyy -  h:mmtt")
                    }
                                                )
                                        .Where(a => !occurances.Select(o => o.Id).Contains(a.Id))
                                        );
                }

                ddlOccurence.DataSource = occurances.OrderByDescending(o => o.Id);
                ddlOccurence.DataBind();

                //Drop down for filter values
                ddlFilter.Visible = (GetAttributeValue("ShowFilters").AsBoolean() && CurrentGroupFilters.Any());
                if (ddlFilter.Visible)
                {
                    ddlFilter.DataSource = CurrentGroupFilterValues
                                           .Select(s => new
                    {
                        Id   = s,
                        Name = s,
                    }
                                                   );
                    ddlFilter.DataBind();
                    CurrentGroupMember.LoadAttributes();
                    ddlFilter.SelectedValue = CurrentGroupMember.GetAttributeValue(CurrentGroupFilters.FirstOrDefault());
                }
            }
        }
Пример #17
0
        /// <summary>
        /// Save RSVP response data from grid (to Attendance records).
        /// </summary>
        protected bool SaveRSVPData()
        {
            var attendees = new List <RSVPAttendee>();

            foreach (GridViewRow row in gAttendees.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    RockCheckBox     rcbAccept         = row.FindControl("rcbAccept") as RockCheckBox;
                    RockCheckBox     rcbDecline        = row.FindControl("rcbDecline") as RockCheckBox;
                    DataDropDownList rddlDeclineReason = row.FindControl("rddlDeclineReason") as DataDropDownList;
                    RockTextBox      tbDeclineNote     = row.FindControl("tbDeclineNote") as RockTextBox;
                    int    declineReason = int.Parse(rddlDeclineReason.SelectedValue);
                    string declineNote   = tbDeclineNote.Text;

                    attendees.Add(
                        new RSVPAttendee()
                    {
                        Accept        = rcbAccept.Checked,
                        Decline       = rcbDecline.Checked,
                        DeclineNote   = declineNote,
                        DeclineReason = declineReason,
                        PersonId      = ( int )gAttendees.DataKeys[row.RowIndex].Value
                    }
                        );
                }
            }
            using (var rockContext = new RockContext())
            {
                var occurrenceService  = new AttendanceOccurrenceService(rockContext);
                var attendanceService  = new AttendanceService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);

                AttendanceOccurrence occurrence = null;

                int?groupId      = PageParameter(PageParameterKey.GroupId).AsIntegerOrNull();
                int?occurrenceId = PageParameter(PageParameterKey.OccurrenceId).AsIntegerOrNull();

                if ((occurrenceId == null) || (occurrenceId == 0))
                {
                    occurrenceId = hfNewOccurrenceId.Value.AsIntegerOrNull();
                    if ((occurrenceId == null) || (occurrenceId == 0))
                    {
                        throw new Exception("The AttendanceOccurrence does not exist.");
                    }
                }

                occurrence = occurrenceService.Get(occurrenceId.Value);

                var existingAttendees = occurrence.Attendees.ToList();

                foreach (var attendee in attendees)
                {
                    var attendance = existingAttendees
                                     .Where(a => a.PersonAlias.PersonId == attendee.PersonId)
                                     .FirstOrDefault();

                    if (attendance == null)
                    {
                        int?personAliasId = personAliasService.GetPrimaryAliasId(attendee.PersonId);
                        if (personAliasId.HasValue)
                        {
                            attendance = new Attendance();
                            attendance.PersonAliasId = personAliasId;
                            attendance.StartDateTime = occurrence.Schedule != null && occurrence.Schedule.HasSchedule() ? occurrence.OccurrenceDate.Date.Add(occurrence.Schedule.StartTimeOfDay) : occurrence.OccurrenceDate;
                            occurrence.Attendees.Add(attendance);
                        }
                    }

                    if (attendance != null)
                    {
                        if (attendee.Accept)
                        {
                            var groupMember = occurrence.Group.Members.Where(gm => gm.PersonId == attendee.PersonId).FirstOrDefault();
                            if (groupMember == null)
                            {
                                groupMember             = new GroupMember();
                                groupMember.PersonId    = attendee.PersonId;
                                groupMember.GroupId     = occurrence.Group.Id;
                                groupMember.GroupRoleId = occurrence.Group.GroupType.DefaultGroupRoleId ?? 0;

                                new GroupMemberService(rockContext).Add(groupMember);
                                rockContext.SaveChanges();
                            }

                            // only set the RSVP and Date if the value is changing
                            if (attendance.RSVP != Rock.Model.RSVP.Yes)
                            {
                                attendance.RSVPDateTime = RockDateTime.Now;
                                attendance.RSVP         = Rock.Model.RSVP.Yes;
                            }
                            attendance.Note = string.Empty;
                            attendance.DeclineReasonValueId = null;
                        }
                        else if (attendee.Decline)
                        {
                            // only set the RSVP and Date if the value is changing
                            if (attendance.RSVP != Rock.Model.RSVP.No)
                            {
                                attendance.RSVPDateTime = RockDateTime.Now;
                                attendance.RSVP         = Rock.Model.RSVP.No;
                            }

                            attendance.Note = attendee.DeclineNote;
                            if (attendee.DeclineReason != 0)
                            {
                                attendance.DeclineReasonValueId = attendee.DeclineReason;
                            }
                        }
                        else
                        {
                            attendance.RSVPDateTime         = null;
                            attendance.RSVP                 = Rock.Model.RSVP.Unknown;
                            attendance.Note                 = string.Empty;
                            attendance.DeclineReasonValueId = null;
                        }
                    }
                }

                rockContext.SaveChanges();

                if (occurrence.LocationId.HasValue)
                {
                    Rock.CheckIn.KioskLocationAttendance.Remove(occurrence.LocationId.Value);
                }
            }

            return(true);
        }
        /// <summary>
        /// Binds the group members grid.
        /// </summary>
        protected void ShowDetails()
        {
            if (CurrentGroup == null)
            {
                NavigateToHomePage();
                return;
            }

            nbNotice.Visible     = false;
            lMembers.Text        = CurrentGroup.GroupType.GroupMemberTerm.Pluralize();
            lPendingMembers.Text = "Pending " + lMembers.Text;

            if (ddlOccurence.SelectedValue.AsInteger() != 0)
            {
                //The drop down stores the time in unix time
                var occurenceDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)
                                    .AddSeconds(ddlOccurence.SelectedValue.AsInteger());

                var attendanceData = new AttendanceService(_rockContext)
                                     .Queryable()
                                     .Where(a => a.Occurrence.GroupId == CurrentGroup.Id && a.StartDateTime == occurenceDate)
                                     .ToList();

                lvMembers.Items.Clear();

                List <GroupMember> groupMembers;

                if (ddlFilter.Visible)
                {
                    groupMembers = GetFilteredMembers(ddlFilter.SelectedValue);
                }
                else
                {
                    groupMembers = CurrentGroupMembers;
                }

                var items = groupMembers
                            .Where(gm => gm.GroupMemberStatus == GroupMemberStatus.Active)
                            .OrderBy(gm => gm.Person.LastName)
                            .ThenBy(gm => gm.Person.NickName)
                            .Select(m => new
                {
                    PersonId = m.PersonId.ToString(),
                    FullName = m.ToString(),
                    Active   = (attendanceData.Where(a => a.PersonAlias.PersonId == m.PersonId).Any() &&
                                (attendanceData.Where(a => a.PersonAlias.PersonId == m.PersonId).FirstOrDefault().DidAttend ?? false)) ? "active" : "",
                    Attended = (attendanceData.Where(a => a.PersonAlias.PersonId == m.PersonId).Any() &&
                                (attendanceData.Where(a => a.PersonAlias.PersonId == m.PersonId).FirstOrDefault().DidAttend ?? false))
                }
                                    )
                            .ToList();

                lvMembers.DataSource = items;
                lvMembers.DataBind();

                AttendanceOccurrenceService attendanceOccurenceService = new AttendanceOccurrenceService(_rockContext);
                var occurrence = attendanceOccurenceService.Get(occurenceDate.Date, CurrentGroup.Id, null, CurrentGroup.ScheduleId);

                cbDidNotMeet.Checked = (
                    (attendanceData.Where(a => a.DidAttend == true).Count() <= 0 &&
                     attendanceData.Where(a => a.Occurrence.DidNotOccur == true).Count() > 0) ||
                    (occurrence != null && occurrence.DidNotOccur == true)
                    );
                if (cbDidNotMeet.Checked)
                {
                    lbDidNotMeet.AddCssClass("active");
                }
            }


            GroupMemberService groupMemberService = new GroupMemberService(_rockContext);
            // Bind the pending members
            var pendingMembers = groupMemberService
                                 .Queryable().AsNoTracking()
                                 .Where(m =>
                                        m.GroupId == CurrentGroup.Id &&
                                        m.GroupMemberStatus == GroupMemberStatus.Pending)
                                 .OrderBy(m => m.Person.LastName)
                                 .ThenBy(m => m.Person.NickName)
                                 .Select(m => new
            {
                Id       = m.PersonId,
                FullName = m.Person.NickName + " " + m.Person.LastName
            })
                                 .ToList();

            pnlPendingMembers.Visible   = pendingMembers.Any();
            lvPendingMembers.DataSource = pendingMembers;
            lvPendingMembers.DataBind();
        }
Пример #19
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] selectionValues = selection.Split('|');
            var      rockContext     = ( RockContext )serviceInstance.Context;

            if (selectionValues.Length >= 2)
            {
                GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                List <Guid>        groupGuids         = selectionValues[0].Split(',').AsGuidList();
                var groupService = new GroupService(rockContext);
                var groupIds     = groupService.GetByGuids(groupGuids).Select(a => a.Id).Distinct().ToList();

                bool includeChildGroups = false;
                bool includeChildGroupsIncludeSelected = false;
                bool includeChildGroupsPlusDescendants = false;
                bool includeInactiveGroups             = false;
                if (selectionValues.Length >= 3)
                {
                    includeChildGroups = selectionValues[2].AsBooleanOrNull() ?? false;
                }

                if (selectionValues.Length >= 6)
                {
                    includeChildGroupsIncludeSelected = selectionValues[4].AsBooleanOrNull() ?? false;
                    includeChildGroupsPlusDescendants = selectionValues[5].AsBooleanOrNull() ?? false;
                }
                else if (includeChildGroups)
                {
                    // in case the selection was saved before these options where added
                    includeChildGroupsIncludeSelected = true;
                    includeChildGroupsPlusDescendants = true;
                }

                if (selectionValues.Length >= 7)
                {
                    includeInactiveGroups = selectionValues[6].AsBooleanOrNull() ?? true;
                }
                else
                {
                    // if options where saved before this option was added, set to false, even though it would have included inactive before
                    includeInactiveGroups = false;
                }

                GroupMemberStatus?groupMemberStatus = null;
                if (selectionValues.Length >= 4)
                {
                    groupMemberStatus = selectionValues[3].ConvertToEnumOrNull <GroupMemberStatus>();
                }

                var groupMemberServiceQry = groupMemberService.Queryable();

                List <int> childGroupIds = new List <int>();

                if (includeChildGroups)
                {
                    foreach (var groupId in groupIds)
                    {
                        if (includeChildGroupsPlusDescendants)
                        {
                            // get all children and descendants of the selected group(s)
                            var descendants = groupService.GetAllDescendents(groupId);
                            if (!includeInactiveGroups)
                            {
                                descendants = descendants.Where(a => a.IsActive == true);
                            }

                            childGroupIds.AddRange(descendants.Select(a => a.Id).Distinct().ToList());
                        }
                        else
                        {
                            // get only immediate children of the selected group(s)
                            var childGroups = groupService.Queryable().Where(a => a.ParentGroupId == groupId);
                            if (!includeInactiveGroups)
                            {
                                childGroups = childGroups.Where(a => a.IsActive == true);
                            }

                            childGroupIds.AddRange(childGroups.Select(a => a.Id));
                        }
                    }

                    if (includeChildGroupsIncludeSelected)
                    {
                        groupMemberServiceQry = groupMemberServiceQry.Where(xx => groupIds.Contains(xx.GroupId) || childGroupIds.Contains(xx.GroupId));
                    }
                    else
                    {
                        groupMemberServiceQry = groupMemberServiceQry.Where(xx => childGroupIds.Contains(xx.GroupId));
                    }
                }
                else
                {
                    groupMemberServiceQry = groupMemberServiceQry.Where(xx => groupIds.Contains(xx.GroupId));
                }

                if (groupMemberStatus.HasValue)
                {
                    groupMemberServiceQry = groupMemberServiceQry.Where(xx => xx.GroupMemberStatus == groupMemberStatus.Value);
                }

                var groupRoleGuids = selectionValues[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(n => n.AsGuid()).ToList();
                if (groupRoleGuids.Count() > 0)
                {
                    var groupRoleIds = new GroupTypeRoleService(( RockContext )serviceInstance.Context).Queryable().Where(a => groupRoleGuids.Contains(a.Guid)).Select(a => a.Id).ToList();
                    groupMemberServiceQry = groupMemberServiceQry.Where(xx => groupRoleIds.Contains(xx.GroupRoleId));
                }

                if (selectionValues.Length >= 8)
                {
                    string    addedOnSlidingDelimitedValues = selectionValues[7].Replace(',', '|');
                    DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(addedOnSlidingDelimitedValues);
                    if (dateRange.Start.HasValue)
                    {
                        groupMemberServiceQry = groupMemberServiceQry.Where(xx => xx.DateTimeAdded >= dateRange.Start.Value);
                    }

                    if (dateRange.End.HasValue)
                    {
                        groupMemberServiceQry = groupMemberServiceQry.Where(xx => xx.DateTimeAdded < dateRange.End.Value);
                    }
                }

                IQueryable <PersonIdFirstAttendance> firstAttendanceDateQry = null;
                IQueryable <PersonIdLastAttendance>  lastAttendanceDateQry  = null;

                if (selectionValues.Length >= 10)
                {
                    List <int> attendanceGroupIds = null;
                    if (includeChildGroups)
                    {
                        if (includeChildGroupsIncludeSelected)
                        {
                            attendanceGroupIds = new List <int>();
                            attendanceGroupIds.AddRange(groupIds);
                            attendanceGroupIds.AddRange(childGroupIds);
                        }
                        else
                        {
                            attendanceGroupIds = childGroupIds;
                        }
                    }
                    else
                    {
                        attendanceGroupIds = groupIds;
                    }

                    var groupAttendanceQuery = new AttendanceService(rockContext).Queryable().Where(a => a.DidAttend == true && a.GroupId.HasValue && attendanceGroupIds.Contains(a.GroupId.Value));

                    string    firstAttendanceSlidingDelimitedValues = selectionValues[8].Replace(',', '|');
                    DateRange firstAttendanceDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(firstAttendanceSlidingDelimitedValues);

                    if (firstAttendanceDateRange.Start.HasValue || firstAttendanceDateRange.End.HasValue)
                    {
                        firstAttendanceDateQry = groupAttendanceQuery
                                                 .GroupBy(xx => xx.PersonAlias.PersonId)
                                                 .Select(ss => new PersonIdFirstAttendance
                        {
                            PersonId = ss.Key,
                            FirstAttendanceSundayDate = ss.Min(a => a.SundayDate)
                        });

                        if (firstAttendanceDateRange.Start.HasValue)
                        {
                            firstAttendanceDateQry = firstAttendanceDateQry.Where(xx => xx.FirstAttendanceSundayDate >= firstAttendanceDateRange.Start.Value);
                        }

                        if (firstAttendanceDateRange.End.HasValue)
                        {
                            firstAttendanceDateQry = firstAttendanceDateQry.Where(xx => xx.FirstAttendanceSundayDate < firstAttendanceDateRange.End.Value);
                        }
                    }

                    string    lastAttendanceSlidingDelimitedValues = selectionValues[9].Replace(',', '|');
                    DateRange lastAttendanceDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(lastAttendanceSlidingDelimitedValues);

                    if (lastAttendanceDateRange.Start.HasValue || lastAttendanceDateRange.End.HasValue)
                    {
                        lastAttendanceDateQry = groupAttendanceQuery
                                                .GroupBy(xx => xx.PersonAlias.PersonId)
                                                .Select(ss => new PersonIdLastAttendance
                        {
                            PersonId = ss.Key,
                            LastAttendanceSundayDate = ss.Max(a => a.SundayDate)
                        });

                        if (lastAttendanceDateRange.Start.HasValue)
                        {
                            lastAttendanceDateQry = lastAttendanceDateQry.Where(xx => xx.LastAttendanceSundayDate >= lastAttendanceDateRange.Start.Value);
                        }

                        if (lastAttendanceDateRange.End.HasValue)
                        {
                            lastAttendanceDateQry = lastAttendanceDateQry.Where(xx => xx.LastAttendanceSundayDate < lastAttendanceDateRange.End.Value);
                        }
                    }
                }

                IQueryable <Rock.Model.Person> qry = null;
                if (lastAttendanceDateQry == null && firstAttendanceDateQry == null)
                {
                    qry = new PersonService(( RockContext )serviceInstance.Context).Queryable()
                          .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id));
                }
                else
                {
                    if (firstAttendanceDateQry != null && lastAttendanceDateQry != null)
                    {
                        qry = new PersonService(( RockContext )serviceInstance.Context).Queryable()
                              .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id) &&
                                     firstAttendanceDateQry.Any(aa => aa.PersonId == p.Id) && lastAttendanceDateQry.Any(bb => bb.PersonId == p.Id));
                    }
                    else if (firstAttendanceDateQry != null)
                    {
                        qry = new PersonService(( RockContext )serviceInstance.Context).Queryable()
                              .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id) &&
                                     firstAttendanceDateQry.Any(aa => aa.PersonId == p.Id));
                    }
                    else if (lastAttendanceDateQry != null)
                    {
                        qry = new PersonService(( RockContext )serviceInstance.Context).Queryable()
                              .Where(p => groupMemberServiceQry.Any(xx => xx.PersonId == p.Id) &&
                                     lastAttendanceDateQry.Any(aa => aa.PersonId == p.Id));
                    }
                }

                Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p");

                return(extractedFilterExpression);
            }

            return(null);
        }
Пример #20
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Rock.Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                AttendanceCode attendanceCode = null;
                DateTime       startDateTime  = Rock.RockDateTime.Now;
                DateTime       today          = startDateTime.Date;
                DateTime       tomorrow       = startDateTime.AddDays(1);

                bool reuseCodeForFamily = checkInState.CheckInType != null && checkInState.CheckInType.ReuseSameCode;
                int  securityCodeLength = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaNumericLength : 3;

                var attendanceCodeService = new AttendanceCodeService(rockContext);
                var attendanceService     = new AttendanceService(rockContext);
                var groupMemberService    = new GroupMemberService(rockContext);
                var personAliasService    = new PersonAliasService(rockContext);

                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    foreach (var person in family.GetPeople(true))
                    {
                        if (reuseCodeForFamily && attendanceCode != null)
                        {
                            person.SecurityCode = attendanceCode.Code;
                        }
                        else
                        {
                            attendanceCode      = AttendanceCodeService.GetNew(securityCodeLength);
                            person.SecurityCode = attendanceCode.Code;
                        }

                        foreach (var groupType in person.GetGroupTypes(true))
                        {
                            foreach (var group in groupType.GetGroups(true))
                            {
                                if (groupType.GroupType.AttendanceRule == AttendanceRule.AddOnCheckIn &&
                                    groupType.GroupType.DefaultGroupRoleId.HasValue &&
                                    !groupMemberService.GetByGroupIdAndPersonId(group.Group.Id, person.Person.Id, true).Any())
                                {
                                    var groupMember = new GroupMember();
                                    groupMember.GroupId     = group.Group.Id;
                                    groupMember.PersonId    = person.Person.Id;
                                    groupMember.GroupRoleId = groupType.GroupType.DefaultGroupRoleId.Value;
                                    groupMemberService.Add(groupMember);
                                }

                                foreach (var location in group.GetLocations(true))
                                {
                                    foreach (var schedule in location.GetSchedules(true))
                                    {
                                        var primaryAlias = personAliasService.GetPrimaryAlias(person.Person.Id);
                                        if (primaryAlias != null)
                                        {
                                            // If a like attendance service exists close it before creating another one.
                                            var oldAttendance = attendanceService.Queryable()
                                                                .Where(a =>
                                                                       a.StartDateTime >= today &&
                                                                       a.StartDateTime < tomorrow &&
                                                                       a.LocationId == location.Location.Id &&
                                                                       a.ScheduleId == schedule.Schedule.Id &&
                                                                       a.GroupId == group.Group.Id &&
                                                                       a.PersonAlias.PersonId == person.Person.Id)
                                                                .FirstOrDefault();

                                            if (oldAttendance != null)
                                            {
                                                oldAttendance.EndDateTime = Rock.RockDateTime.Now;
                                                oldAttendance.DidAttend   = false;
                                            }
                                            var attendance = rockContext.Attendances.Create();
                                            attendance.LocationId          = location.Location.Id;
                                            attendance.CampusId            = location.CampusId;
                                            attendance.ScheduleId          = schedule.Schedule.Id;
                                            attendance.GroupId             = group.Group.Id;
                                            attendance.PersonAliasId       = primaryAlias.Id;
                                            attendance.DeviceId            = checkInState.Kiosk.Device.Id;
                                            attendance.SearchTypeValueId   = checkInState.CheckIn.SearchType.Id;
                                            attendance.SearchValue         = checkInState.CheckIn.SearchValue;
                                            attendance.SearchResultGroupId = family.Group.Id;
                                            attendance.AttendanceCodeId    = attendanceCode.Id;
                                            attendance.StartDateTime       = startDateTime;
                                            attendance.EndDateTime         = null;
                                            attendance.DidAttend           = groupType.GroupType.GetAttributeValue("SetDidAttend").AsBoolean();
                                            attendanceService.Add(attendance);
                                            CheckInCountCache.AddAttendance(attendance);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                rockContext.SaveChanges();
                return(true);
            }

            return(false);
        }
Пример #21
0
        /// <summary>
        /// Saves the attendance data.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="group">The group.</param>
        /// <param name="date">The date.</param>
        /// <param name="attendees">The attendees.</param>
        /// <param name="didNotMeet">if set to <c>true</c> then the group is marked as having not met.</param>
        /// <param name="notes">Contains the note text to save with the occurrence.</param>
        private void SaveAttendanceData(RockContext rockContext, Group group, DateTime date, List <Attendee> attendees, bool didNotMeet, string notes)
        {
            var attendanceService  = new AttendanceService(rockContext);
            var personAliasService = new PersonAliasService(rockContext);

            var occurrence        = GetOccurrence(rockContext, group, date, true);
            var existingAttendees = occurrence.Attendees.ToList();

            if (didNotMeet)
            {
                if (!occurrence.ScheduleId.HasValue)
                {
                    //
                    // If the attendance is not part of a schedule, just delete all the records.
                    //
                    foreach (var attendance in existingAttendees)
                    {
                        attendanceService.Delete(attendance);
                    }
                }
                else
                {
                    //
                    // If the occurrence is based on a schedule, clear the DidAttend property.
                    //
                    foreach (var attendance in existingAttendees)
                    {
                        attendance.DidAttend = null;
                    }
                }
            }
            else
            {
                foreach (var attendee in attendees)
                {
                    var attendance = existingAttendees
                                     .Where(a => a.PersonAlias.Person.Guid == attendee.PersonGuid)
                                     .FirstOrDefault();

                    if (attendance == null)
                    {
                        int?personAliasId = personAliasService.GetPrimaryAliasId(attendee.PersonGuid);
                        if (personAliasId.HasValue)
                        {
                            attendance = new Attendance
                            {
                                PersonAliasId = personAliasId,
                                CampusId      = null,
                                StartDateTime = occurrence.Schedule != null && occurrence.Schedule.HasSchedule() ? occurrence.OccurrenceDate.Date.Add(occurrence.Schedule.StartTimeOfDay) : occurrence.OccurrenceDate,
                                DidAttend     = attendee.Attended
                            };

                            occurrence.Attendees.Add(attendance);
                        }
                    }
                    else
                    {
                        // Otherwise, only record that they attended -- don't change their attendance startDateTime
                        attendance.DidAttend = attendee.Attended;
                    }
                }
            }

            occurrence.DidNotOccur = didNotMeet;

            // Only update the occurrence Notes if 'notes' is not null.
            occurrence.Notes = notes ?? occurrence.Notes;

            rockContext.SaveChanges();
        }
Пример #22
0
        private void ShowDetail(Guid personGuid)
        {
            using (var rockContext = new RockContext())
            {
                var personService = new PersonService(rockContext);

                var person = personService.Queryable("PhoneNumbers.NumberTypeValue,RecordTypeValue", true, true)
                             .FirstOrDefault(a => a.Guid == personGuid);

                if (person != null)
                {
                    lName.Text = person.FullName;

                    string photoTag = Rock.Model.Person.GetPersonPhotoImageTag(person, 200, 200);
                    if (person.PhotoId.HasValue)
                    {
                        lPhoto.Text = string.Format("<div class='photo'><a href='{0}'>{1}</a></div>", person.PhotoUrl, photoTag);
                    }
                    else
                    {
                        lPhoto.Text = photoTag;
                    }

                    var campus = person.GetCampus();
                    if (campus != null)
                    {
                        hlCampus.Visible = true;
                        hlCampus.Text    = campus.Name;
                    }
                    else
                    {
                        hlCampus.Visible = false;
                    }

                    lGender.Text = person.Gender != Gender.Unknown ? person.Gender.ConvertToString() : "";

                    if (person.BirthDate.HasValue)
                    {
                        string ageText = (person.BirthYear.HasValue && person.BirthYear != DateTime.MinValue.Year) ?
                                         string.Format("{0} yrs old ", person.BirthDate.Value.Age()) : string.Empty;
                        lAge.Text = string.Format("{0} <small>({1})</small><br/>", ageText, person.BirthDate.Value.ToShortDateString());
                    }
                    else
                    {
                        lAge.Text = string.Empty;
                    }

                    lGrade.Text = person.GradeFormatted;

                    lEmail.Visible = !string.IsNullOrWhiteSpace(person.Email);
                    lEmail.Text    = person.GetEmailTag(ResolveRockUrl("/"), "btn btn-default", "<i class='fa fa-envelope'></i>");

                    BindAttribute(person);
                    // Text Message
                    var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.IsMessagingEnabled && n.Number.IsNotNullOrWhiteSpace());
                    if (GetAttributeValue(SMS_FROM_KEY).IsNotNullOrWhiteSpace() && phoneNumber != null)
                    {
                        btnSms.Text          = string.Format("<i class='fa fa-mobile'></i> {0} <small>({1})</small>", phoneNumber.NumberFormatted, phoneNumber.NumberTypeValue);
                        btnSms.Visible       = true;
                        rcwTextMessage.Label = "Text Message";
                    }
                    else
                    {
                        btnSms.Visible       = false;
                        rcwTextMessage.Label = string.Empty;
                    }

                    // Get all family member from all families ( including self )
                    var allFamilyMembers = personService.GetFamilyMembers(person.Id, true).ToList();

                    // Add flag for this person in each family indicating if they are a child in family.
                    var childGuid     = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid();
                    var isFamilyChild = new Dictionary <int, bool>();
                    foreach (var thisPerson in allFamilyMembers.Where(m => m.PersonId == person.Id))
                    {
                        isFamilyChild.Add(thisPerson.GroupId, thisPerson.GroupRole.Guid.Equals(childGuid));
                    }

                    // Get the current url's root (without the person's guid)
                    string urlRoot = Request.Url.ToString().ReplaceCaseInsensitive(personGuid.ToString(), "");

                    // Get the other family members and the info needed for rendering
                    var familyMembers = allFamilyMembers.Where(m => m.PersonId != person.Id)
                                        .OrderBy(m => m.GroupId)
                                        .ThenBy(m => m.Person.BirthDate)
                                        .Select(m => new
                    {
                        Url        = urlRoot + m.Person.Guid.ToString(),
                        FullName   = m.Person.FullName,
                        Gender     = m.Person.Gender,
                        FamilyRole = m.GroupRole,
                        Note       = isFamilyChild[m.GroupId] ?
                                     (m.GroupRole.Guid.Equals(childGuid) ? " (Sibling)" : "(Parent)") :
                                     (m.GroupRole.Guid.Equals(childGuid) ? " (Child)" : "")
                    })
                                        .ToList();

                    rcwFamily.Visible     = familyMembers.Any();
                    rptrFamily.DataSource = familyMembers;
                    rptrFamily.DataBind();

                    rcwRelationships.Visible = false;
                    if (GetAttributeValue("ShowRelatedPeople").AsBoolean())
                    {
                        var roles   = new List <int>();
                        var krRoles = new GroupTypeRoleService(rockContext)
                                      .Queryable().AsNoTracking()
                                      .Where(r => r.GroupType.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS)))
                                      .ToList();

                        foreach (var role in krRoles)
                        {
                            role.LoadAttributes(rockContext);
                            if (role.GetAttributeValue("CanCheckin").AsBoolean() &&
                                role.Attributes.ContainsKey("InverseRelationship"))
                            {
                                var inverseRoleGuid = role.GetAttributeValue("InverseRelationship").AsGuidOrNull();
                                if (inverseRoleGuid.HasValue)
                                {
                                    var inverseRole = krRoles.FirstOrDefault(r => r.Guid == inverseRoleGuid.Value);
                                    if (inverseRole != null)
                                    {
                                        roles.Add(inverseRole.Id);
                                    }
                                }
                            }
                        }

                        if (roles.Any())
                        {
                            var relatedMembers = personService.GetRelatedPeople(new List <int> {
                                person.Id
                            }, roles)
                                                 .OrderBy(m => m.Person.LastName)
                                                 .ThenBy(m => m.Person.NickName)
                                                 .Select(m => new
                            {
                                Url      = urlRoot + m.Person.Guid.ToString(),
                                FullName = m.Person.FullName,
                                Gender   = m.Person.Gender,
                                Note     = " (" + m.GroupRole.Name + ")"
                            })
                                                 .ToList();

                            rcwRelationships.Visible     = relatedMembers.Any();
                            rptrRelationships.DataSource = relatedMembers;
                            rptrRelationships.DataBind();
                        }
                    }

                    var phoneNumbers = person.PhoneNumbers.Where(p => !p.IsUnlisted).ToList();
                    rptrPhones.DataSource = phoneNumbers;
                    rptrPhones.DataBind();
                    rcwPhone.Visible = phoneNumbers.Any();

                    var schedules = new ScheduleService(rockContext)
                                    .Queryable().AsNoTracking()
                                    .Where(s => s.CheckInStartOffsetMinutes.HasValue)
                                    .ToList();

                    var scheduleIds = schedules.Select(s => s.Id).ToList();

                    int?personAliasId = person.PrimaryAliasId;

                    PersonAliasService personAliasService = new PersonAliasService(rockContext);
                    if (!personAliasId.HasValue)
                    {
                        personAliasId = personAliasService.GetPrimaryAliasId(person.Id);
                    }

                    var attendances = new AttendanceService(rockContext)
                                      .Queryable("Occurrence.Schedule,Occurrence.Group,Occurrence.Location,AttendanceCode")
                                      .Where(a =>
                                             a.PersonAliasId.HasValue &&
                                             a.PersonAliasId == personAliasId &&
                                             a.Occurrence.ScheduleId.HasValue &&
                                             a.Occurrence.GroupId.HasValue &&
                                             a.Occurrence.LocationId.HasValue &&
                                             a.DidAttend.HasValue &&
                                             a.DidAttend.Value &&
                                             scheduleIds.Contains(a.Occurrence.ScheduleId.Value))
                                      .OrderByDescending(a => a.StartDateTime)
                                      .Take(20)
                                      .ToList()                                               // Run query to get recent most 20 checkins
                                      .OrderByDescending(a => a.Occurrence.OccurrenceDate)    // Then sort again by startdatetime and schedule start (which is not avail to sql query )
                                      .ThenByDescending(a => a.Occurrence.Schedule.StartTimeOfDay)
                                      .ToList()
                                      .Select(a =>
                    {
                        var checkedInByPerson = a.CheckedInByPersonAliasId.HasValue ? personAliasService.GetPerson(a.CheckedInByPersonAliasId.Value) : null;

                        return(new AttendanceInfo
                        {
                            Id = a.Id,
                            Date = a.StartDateTime,
                            GroupId = a.Occurrence.Group.Id,
                            Group = a.Occurrence.Group.Name,
                            LocationId = a.Occurrence.LocationId.Value,
                            Location = a.Occurrence.Location.Name,
                            Schedule = a.Occurrence.Schedule.Name,
                            IsActive = a.IsCurrentlyCheckedIn,
                            Code = a.AttendanceCode != null ? a.AttendanceCode.Code : "",
                            CheckInByPersonName = checkedInByPerson != null ? checkedInByPerson.FullName : string.Empty,
                            CheckInByPersonGuid = checkedInByPerson != null ? checkedInByPerson.Guid : ( Guid? )null
                        });
                    }
                                              ).ToList();

                    // Set active locations to be a link to the room in manager page
                    var qryParam = new Dictionary <string, string>();
                    qryParam.Add("Group", "");
                    qryParam.Add("Location", "");
                    foreach (var attendance in attendances.Where(a => a.IsActive))
                    {
                        qryParam["Group"]    = attendance.GroupId.ToString();
                        qryParam["Location"] = attendance.LocationId.ToString();
                        attendance.Location  = string.Format("<a href='{0}'>{1}</a>",
                                                             LinkedPageUrl("ManagerPage", qryParam), attendance.Location);
                    }

                    rcwCheckinHistory.Visible = attendances.Any();

                    // Get the index of the delete column
                    var deleteField = gHistory.Columns.OfType <Rock.Web.UI.Controls.DeleteField>().First();
                    _deleteFieldIndex = gHistory.Columns.IndexOf(deleteField);

                    gHistory.DataSource = attendances;
                    gHistory.DataBind();
                }
            }
        }
Пример #23
0
        public static void CloneAttendance(Attendance attendance, bool isSubroom, Location location, AttendanceService attendanceService, Request req)
        {
            Attendance newAttendance = null;

            if (!isSubroom)
            {
                newAttendance = attendanceService.AddOrUpdate(attendance.PersonAliasId, attendance.StartDateTime.Date, attendance.Occurrence.GroupId,
                                                              location.Id, attendance.Occurrence.ScheduleId, location.CampusId,
                                                              null, null, null, null, null, null);
            }
            else
            {
                newAttendance = attendanceService.AddOrUpdate(attendance.PersonAliasId, attendance.StartDateTime.Date, attendance.Occurrence.GroupId,
                                                              location.ParentLocationId, attendance.Occurrence.ScheduleId, location.CampusId,
                                                              null, null, null, null, null, null);
            }
            newAttendance.StartDateTime    = Rock.RockDateTime.Now;
            newAttendance.EndDateTime      = null;
            newAttendance.DidAttend        = true;
            newAttendance.AttendanceCodeId = attendance.AttendanceCodeId;
            if (isSubroom)
            {
                newAttendance.ForeignId = location.Id;
            }
            else
            {
                newAttendance.ForeignId = null;
            }
            attendanceService.Add(newAttendance);
            var stayedFifteenMinutes = (Rock.RockDateTime.Now - attendance.StartDateTime) > new TimeSpan(0, 15, 0);

            attendance.DidAttend   = stayedFifteenMinutes;
            attendance.EndDateTime = Rock.RockDateTime.Now;

            attendanceService.Context.SaveChanges();

            AttendanceCache.RemoveWithParent(attendance.PersonAlias.PersonId);
            AttendanceCache.AddOrUpdate(newAttendance);
            AttendanceCache.AddOrUpdate(attendance);
        }