/// <summary>
        /// Execute method to write transaction to the database.
        /// </summary>
        public void Execute()
        {
            using (var rockContext = new RockContext())
            {
                var documentService    = new SignatureDocumentService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var appliesPerson      = personAliasService.GetPerson(AppliesToPersonAliasId);
                var assignedPerson     = personAliasService.GetPerson(AssignedToPersonAliasId);

                if (!documentService.Queryable().Any(d =>
                                                     d.SignatureDocumentTemplateId == SignatureDocumentTemplateId &&
                                                     d.AppliesToPersonAliasId.HasValue &&
                                                     d.AppliesToPersonAliasId.Value == AppliesToPersonAliasId &&
                                                     d.Status == SignatureDocumentStatus.Signed))
                {
                    var documentTypeService       = new SignatureDocumentTemplateService(rockContext);
                    var SignatureDocumentTemplate = documentTypeService.Get(SignatureDocumentTemplateId);

                    var errorMessages = new List <string>();
                    if (documentTypeService.SendDocument(SignatureDocumentTemplate, appliesPerson, assignedPerson, DocumentName, Email, out errorMessages))
                    {
                        rockContext.SaveChanges();
                    }
                }
            }
        }
        /// <summary>
        /// Populates the person lava.
        /// </summary>
        /// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
        private void PopulatePersonLava(RowEventArgs e)
        {
            var hfRecipientPersonAliasId = ( HiddenField )e.Row.FindControl("hfRecipientPersonAliasId");
            int?recipientPersonAliasId   = hfSelectedRecipientPersonAliasId.Value.AsIntegerOrNull();

            var    hfMessageKey  = ( HiddenField )e.Row.FindControl("hfMessageKey");
            var    lblName       = ( Label )e.Row.FindControl("lblName");
            string html          = lblName.Text;
            string unknownPerson = " (Unknown Person)";
            var    lava          = GetAttributeValue(AttributeKey.PersonInfoLavaTemplate);

            if (!recipientPersonAliasId.HasValue || recipientPersonAliasId.Value == -1)
            {
                // We don't have a person to do the lava merge so just display the formatted phone number
                html = PhoneNumber.FormattedNumber(string.Empty, hfMessageKey.Value) + unknownPerson;
                litSelectedRecipientDescription.Text = html;
            }
            else
            {
                // Merge the person and lava
                using (var rockContext = new RockContext())
                {
                    var personAliasService = new PersonAliasService(rockContext);
                    var recipientPerson    = personAliasService.GetPerson(recipientPersonAliasId.Value);
                    var mergeFields        = Rock.Lava.LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);
                    mergeFields.Add("Person", recipientPerson);

                    html = lava.ResolveMergeFields(mergeFields);
                }
            }

            litSelectedRecipientDescription.Text = string.Format("<div class='header-lava pull-left'>{0}</div>", html);
        }
        /// <summary>
        /// Handles the SaveClick event of the mdNewMessage 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 mdNewMessage_SaveClick(object sender, EventArgs e)
        {
            string message = tbSMSTextMessage.Text.Trim();

            if (message.IsNullOrWhiteSpace())
            {
                return;
            }

            nbNoSms.Visible = false;

            int toPersonAliasId    = ppRecipient.PersonAliasId.Value;
            var personAliasService = new PersonAliasService(new RockContext());
            var toPerson           = personAliasService.GetPerson(toPersonAliasId);

            if (!toPerson.PhoneNumbers.Where(p => p.IsMessagingEnabled).Any())
            {
                nbNoSms.Visible = true;
                return;
            }

            SendMessage(toPersonAliasId, message, true);

            mdNewMessage.Hide();
            LoadResponseListing();
        }
Ejemplo n.º 4
0
        // helper functional methods (like BindGrid(), etc.)

        private void Import()
        {
            string attributeKey             = GetAttributeValue("SponsorKey");
            int    personEntityTypeId       = EntityTypeCache.Read(typeof(Person)).Id;
            var    rockContext              = new RockContext();
            var    followUpSponsorAttribute = new AttributeService(rockContext)
                                              .Queryable()
                                              .AsNoTracking()
                                              .FirstOrDefault(a => a.Key == attributeKey && a.EntityTypeId == personEntityTypeId);

            if (followUpSponsorAttribute == null)
            {
                nbInfo.NotificationBoxType = NotificationBoxType.Danger;
                nbInfo.Title = "Failure";
                nbInfo.Text  = "Cannot fetch the Sponsor Person Attribute";
                return;
            }

            var attributeValueService      = new AttributeValueService(rockContext);
            var personService              = new PersonService(rockContext);
            var personAliasService         = new PersonAliasService(rockContext);
            var peopleWithFollowUpSponsors = attributeValueService.GetByAttributeId(followUpSponsorAttribute.Id).Where(av => av.EntityId != null).Select(av => new { PersonId = av.EntityId, SponsorAliasGuid = av.Guid });

            foreach (var pair in peopleWithFollowUpSponsors)
            {
                var followUp = personService.Get(pair.PersonId.Value);
                var sponsor  = personAliasService.GetPerson(pair.SponsorAliasGuid);
                if (!followUp.HasConsolidator())
                {
                    followUp.SetConsolidator(sponsor);
                }
            }
            lbImport.Enabled = false;
            lbImport.Text    = "Done";
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Shows the grid.
        /// </summary>
        protected void ShowGrid()
        {
            gData.Visible = true;
            var schedulerGroupMembers = new List <SchedulerGroupMember>();

            using (var rockContext = new RockContext())
            {
                var personAliasService = new PersonAliasService(rockContext);

                foreach (var personAliasId in attendances.Select(a => a.PersonAliasId).Distinct())
                {
                    var schedulerGroupMember = new SchedulerGroupMember();
                    schedulerGroupMember.Name            = personAliasService.GetPerson(personAliasId.Value).FullName;
                    schedulerGroupMember.Scheduled       = attendances.Where(a => a.PersonAliasId == personAliasId.Value).Count();
                    schedulerGroupMember.NoResponse      = attendances.Where(a => a.PersonAliasId == personAliasId.Value && a.RSVP == RSVP.Unknown).Count();
                    schedulerGroupMember.Declines        = attendances.Where(a => a.PersonAliasId == personAliasId.Value && a.RSVP == RSVP.No).Count();
                    schedulerGroupMember.Attended        = attendances.Where(a => a.PersonAliasId == personAliasId.Value && a.DidAttend == true).Count();
                    schedulerGroupMember.CommittedNoShow = attendances.Where(a => a.PersonAliasId == personAliasId.Value && a.RSVP == RSVP.Yes && a.DidAttend == false).Count();

                    schedulerGroupMembers.Add(schedulerGroupMember);
                }
            }

            gData.DataSource = schedulerGroupMembers;
            gData.DataBind();
        }
        /// <summary>
        /// Handles the SaveClick event of the mdLinkConversation 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 mdLinkToPerson_SaveClick(object sender, EventArgs e)
        {
            using (var rockContext = new RockContext())
            {
                var personAliasService = new PersonAliasService(rockContext);
                var personService      = new PersonService(rockContext);

                // Get the Person Record from the selected conversation. (It should be a 'NamelessPerson' record type)
                int    namelessPersonAliasId = hfSelectedRecipientPersonAliasId.Value.AsInteger();
                var    phoneNumberService    = new PhoneNumberService(rockContext);
                Person namelessPerson        = personAliasService.GetPerson(namelessPersonAliasId);

                if (namelessPerson == null)
                {
                    // shouldn't happen, but just in case
                    return;
                }

                EntitySet mergeRequest = null;
                if (pnlLinkToExistingPerson.Visible)
                {
                    var existingPersonId = ppPerson.PersonId;
                    if (!existingPersonId.HasValue)
                    {
                        return;
                    }

                    var existingPerson = personService.Get(existingPersonId.Value);
                    mergeRequest = namelessPerson.CreateMergeRequest(existingPerson);
                    var entitySetService = new EntitySetService(rockContext);
                    entitySetService.Add(mergeRequest);

                    rockContext.SaveChanges();
                    hfSelectedRecipientPersonAliasId.Value = existingPerson.PrimaryAliasId.ToString();
                }
                else
                {
                    // new Person and new family
                    var newPerson = new Person();

                    newPersonEditor.UpdatePerson(newPerson, rockContext);

                    personService.Add(newPerson);
                    rockContext.SaveChanges();

                    mergeRequest = namelessPerson.CreateMergeRequest(newPerson);
                    var entitySetService = new EntitySetService(rockContext);
                    entitySetService.Add(mergeRequest);
                    rockContext.SaveChanges();

                    hfSelectedRecipientPersonAliasId.Value = newPerson.PrimaryAliasId.ToString();
                }

                RedirectToMergeRequest(mergeRequest);
            }

            mdLinkToPerson.Hide();
            LoadResponseListing();
        }
        /// <summary>
        /// Handles the SelectPerson event of the ppRecipient 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 ppRecipient_SelectPerson(object sender, EventArgs e)
        {
            nbNoSms.Visible = false;

            int toPersonAliasId    = ppRecipient.PersonAliasId.Value;
            var personAliasService = new PersonAliasService(new RockContext());
            var toPerson           = personAliasService.GetPerson(toPersonAliasId);

            if (!toPerson.PhoneNumbers.Where(p => p.IsMessagingEnabled).Any())
            {
                nbNoSms.Visible = true;
            }
        }
        /// <summary>
        /// Handles the Click event of the lbViewMergeRequest 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 lbViewMergeRequest_Click(object sender, EventArgs e)
        {
            var namelessPersonAliasId = hfSelectedRecipientPersonAliasId.Value.AsInteger();

            using (var rockContext = new RockContext())
            {
                var personAliasService = new PersonAliasService(rockContext);
                var namelessPerson     = personAliasService.GetPerson(namelessPersonAliasId);

                var mergeRequest = namelessPerson.GetMergeRequest(rockContext);

                RedirectToMergeRequest(mergeRequest);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Gets the requestor person either from the attribute or using person matching if allowed
        /// </summary>
        /// <returns></returns>
        private Person GetRequestor()
        {
            Person person;
            var    personAliasGuid = GetGuidFromTextOrAttribute(AttributeKey.Requestor);

            if (personAliasGuid.HasValue)
            {
                var personAliasService = new PersonAliasService(_rockContext);
                person = personAliasService.GetPerson(personAliasGuid.Value);

                if (person != null)
                {
                    return(person);
                }
            }

            if (GetBoolean(AttributeKey.IsPersonMatchingEnabled) != true)
            {
                return(null);
            }

            var email     = GetTextFromSelectedAttribute(AttributeKey.Email);
            var firstName = GetTextFromSelectedAttribute(AttributeKey.FirstName);
            var lastName  = GetTextFromSelectedAttribute(AttributeKey.LastName);

            // Email, first, and last name are all required to do person matching
            if (email.IsNullOrWhiteSpace() || firstName.IsNullOrWhiteSpace() || lastName.IsNullOrWhiteSpace())
            {
                return(null);
            }

            var personService = new PersonService(_rockContext);
            var query         = new PersonService.PersonMatchQuery(firstName, lastName, email, null);

            return(personService.FindPerson(query, false, true, false));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Show the details for the given person.
        /// </summary>
        /// <param name="personGuid"></param>
        private void ShowDetail(Guid personGuid)
        {
            btnReprintLabels.Visible = GetAttributeValue(AttributeKey.AllowLabelReprinting).AsBoolean();

            using (var rockContext = new RockContext())
            {
                var personService = new PersonService(rockContext);

                var person = personService.Queryable(true, true).Include(a => a.PhoneNumbers).Include(a => a.RecordStatusValue)
                             .FirstOrDefault(a => a.Guid == personGuid);

                if (person == null)
                {
                    return;
                }

                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(AttributeKey.SMSFrom).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(AttributeKey.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 start datetime 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(AttributeKey.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();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Show the details for the given person.
        /// </summary>
        /// <param name="personGuid"></param>
        private void ShowDetail(Guid personGuid)
        {
            btnReprintLabels.Visible = GetAttributeValue(AttributeKey.AllowLabelReprinting).AsBoolean();

            using (var rockContext = new RockContext())
            {
                var personService = new PersonService(rockContext);

                var person = personService.Queryable(true, true).Include(a => a.PhoneNumbers).Include(a => a.RecordStatusValue)
                             .FirstOrDefault(a => a.Guid == personGuid);

                if (person == null)
                {
                    return;
                }

                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 ?
                               string.Format(@"<div class=""text-semibold text-uppercase"">{0}</div>", person.Gender.ConvertToString().Substring(0, 1)) : string.Empty;

                if (person.BirthDate.HasValue)
                {
                    string ageText = (person.BirthYear.HasValue && person.BirthYear != DateTime.MinValue.Year) ?
                                     string.Format(@"<div class=""text-semibold"">{0}yrs</div>", person.BirthDate.Value.Age()) : string.Empty;
                    lAge.Text = string.Format(@"{0}<div class=""text-sm text-muted"">{1}</div>", ageText, person.BirthDate.Value.ToShortDateString());
                }
                else
                {
                    lAge.Text = string.Empty;
                }

                string   grade      = person.GradeFormatted;
                string[] gradeParts = grade.Split(' ');
                if (gradeParts.Length >= 2)
                {
                    // Note that Grade names might be different in other countries. See  https://separatedbyacommonlanguage.blogspot.com/2006/12/types-of-schools-school-years.html for examples
                    var firstWord      = gradeParts[0];
                    var remainderWords = gradeParts.Skip(1).ToList().AsDelimited(" ");
                    if (firstWord.Equals("Year", StringComparison.OrdinalIgnoreCase))
                    {
                        // MDP 2020-10-21 (at request of GJ)
                        // Special case if formatted grade is 'Year 1', 'Year 2', etc (see https://separatedbyacommonlanguage.blogspot.com/2006/12/types-of-schools-school-years.html)
                        // Make the word Year on the top
                        grade = string.Format(@"<div class=""text-semibold"">{0}</div><div class=""text-sm text-muted"">{1}</div>", remainderWords, firstWord);
                    }
                    else
                    {
                        grade = string.Format(@"<div class=""text-semibold"">{0}</div><div class=""text-sm text-muted"">{1}</div>", firstWord, remainderWords);
                    }
                }

                lGrade.Text = grade;

                lEmail.Visible = !string.IsNullOrWhiteSpace(person.Email);
                lEmail.Text    = string.Format(@"<div class=""text-truncate"">{0}</div>", person.GetEmailTag(ResolveRockUrl("/"), "text-color"));

                BindAttribute(person);

                // Text Message
                var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.IsMessagingEnabled && n.Number.IsNotNullOrWhiteSpace());
                if (GetAttributeValue(AttributeKey.SMSFrom).IsNotNullOrWhiteSpace() && phoneNumber != null)
                {
                    SmsPhoneNumberId = phoneNumber.Id;
                }
                else
                {
                    SmsPhoneNumberId = 0;
                }

                // 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 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 PersonInfo
                {
                    PhotoTag = Rock.Model.Person.GetPersonPhotoImageTag(m.Person, 64, 64, className: "d-block mb-1"),
                    Url      = GetRelatedPersonUrl(person, m.Person.Guid, m.Person.Id),
                    NickName = m.Person.NickName,
                    //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();

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

                pnlRelationships.Visible = false;
                if (GetAttributeValue(AttributeKey.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 PersonInfo
                        {
                            PhotoTag = Rock.Model.Person.GetPersonPhotoImageTag(m.Person, 50, 50, className: "rounded"),
                            Url      = GetRelatedPersonUrl(person, m.Person.Guid, m.Person.Id),
                            NickName = m.Person.NickName,
                            //FullName = m.Person.FullName,
                            //Gender = m.Person.Gender,
                            //Note = " (" + m.GroupRole.Name + ")"
                        })
                                             .ToList();

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

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

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

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

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

                PersonAliasService personAliasService = new PersonAliasService(rockContext);

                var attendances = new AttendanceService(rockContext)
                                  .Queryable("Occurrence.Schedule,Occurrence.Group,Occurrence.Location,AttendanceCode")
                                  .Where(a =>
                                         a.PersonAliasId.HasValue &&
                                         personAliasIds.Contains(a.PersonAliasId.Value) &&
                                         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 start datetime 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,
                        GroupName = a.Occurrence.Group.Name,
                        LocationId = a.Occurrence.LocationId.Value,
                        LocationName = a.Occurrence.Location.Name,
                        ScheduleName = 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 qryParams = new Dictionary <string, string>
                {
                    { PageParameterKey.LocationId, string.Empty }
                };

                // If an Area Guid was passed to the Page, pass it back.
                string areaGuid = PageParameter(PageParameterKey.AreaGuid);
                if (areaGuid.IsNotNullOrWhiteSpace())
                {
                    qryParams.Add(PageParameterKey.AreaGuid, areaGuid);
                }

                foreach (var attendance in attendances)
                {
                    if (attendance.IsActive)
                    {
                        qryParams[PageParameterKey.LocationId] = attendance.LocationId.ToString();
                        attendance.LocationNameHtml            = string.Format(
                            "<a href='{0}'>{1}</a>",
                            LinkedPageUrl(AttributeKey.ManagerPage, qryParams),
                            attendance.LocationName);
                    }
                    else
                    {
                        attendance.LocationNameHtml = attendance.LocationName;
                    }
                }

                pnlCheckinHistory.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();
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Show the details for the given person.
        /// </summary>
        /// <param name="personGuid"></param>
        private void ShowDetail(Guid personGuid)
        {
            btnReprintLabels.Visible = GetAttributeValue(AttributeKey.AllowLabelReprinting).AsBoolean() && this.IsUserAuthorized(SecurityActionKey.ReprintLabels);

            using (var rockContext = new RockContext())
            {
                var personService = new PersonService(rockContext);

                var person = personService.Queryable(true, true).Include(a => a.PhoneNumbers).Include(a => a.RecordStatusValue)
                             .FirstOrDefault(a => a.Guid == personGuid);

                if (person == null)
                {
                    return;
                }

                lGender.Text = person.Gender != Gender.Unknown ?
                               string.Format(@"<div class=""text-semibold text-uppercase"">{0}</div>", person.Gender.ConvertToString().Substring(0, 1)) : string.Empty;

                if (person.BirthDate.HasValue)
                {
                    string ageText = (person.BirthYear.HasValue && person.BirthYear != DateTime.MinValue.Year) ?
                                     string.Format(@"<div class=""text-semibold"">{0}yrs</div>", person.BirthDate.Value.Age()) : string.Empty;
                    lAge.Text = string.Format(@"{0}<div class=""text-sm text-muted"">{1}</div>", ageText, person.BirthDate.Value.ToShortDateString());
                }
                else
                {
                    lAge.Text = string.Empty;
                }

                string   grade      = person.GradeFormatted;
                string[] gradeParts = grade.Split(' ');
                if (gradeParts.Length >= 2)
                {
                    // Note that Grade names might be different in other countries.
                    // See  https://separatedbyacommonlanguage.blogspot.com/2006/12/types-of-schools-school-years.html for examples.
                    var firstWord      = gradeParts[0];
                    var remainderWords = gradeParts.Skip(1).ToList().AsDelimited(" ");
                    if (firstWord.Equals("Year", StringComparison.OrdinalIgnoreCase))
                    {
                        // MDP 2020-10-21 (at request of GJ)
                        // Special case if formatted grade is 'Year 1', 'Year 2', etc (see https://separatedbyacommonlanguage.blogspot.com/2006/12/types-of-schools-school-years.html)
                        // Make the word Year on the top.
                        grade = string.Format(@"<div class=""text-semibold"">{0}</div><div class=""text-sm text-muted"">{1}</div>", remainderWords, firstWord);
                    }
                    else
                    {
                        grade = string.Format(@"<div class=""text-semibold"">{0}</div><div class=""text-sm text-muted"">{1}</div>", firstWord, remainderWords);
                    }
                }

                lGrade.Text = grade;

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

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

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

                PersonAliasService personAliasService = new PersonAliasService(rockContext);

                var attendances = new AttendanceService(rockContext)
                                  .Queryable("Occurrence.Schedule,Occurrence.Group,Occurrence.Location,AttendanceCode")
                                  .Where(a =>
                                         a.PersonAliasId.HasValue &&
                                         personAliasIds.Contains(a.PersonAliasId.Value) &&
                                         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 start datetime 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,
                        GroupName = a.Occurrence.Group.Name,
                        LocationId = a.Occurrence.LocationId.Value,
                        LocationName = a.Occurrence.Location.Name,
                        ScheduleName = a.Occurrence.Schedule.Name,
                        IsActive = a.IsCurrentlyCheckedIn,
                        Code = a.AttendanceCode != null ? a.AttendanceCode.Code : string.Empty,
                        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 qryParams = new Dictionary <string, string>
                {
                    { PageParameterKey.LocationId, string.Empty }
                };

                // If an Area Guid was passed to the Page, pass it back.
                string areaGuid = PageParameter(PageParameterKey.AreaGuid);
                if (areaGuid.IsNotNullOrWhiteSpace())
                {
                    qryParams.Add(PageParameterKey.AreaGuid, areaGuid);
                }

                foreach (var attendance in attendances)
                {
                    if (attendance.IsActive)
                    {
                        qryParams[PageParameterKey.LocationId] = attendance.LocationId.ToString();
                        attendance.LocationNameHtml            = string.Format(
                            "<a href='{0}'>{1}</a>",
                            LinkedPageUrl(AttributeKey.ManagerPage, qryParams),
                            attendance.LocationName);
                    }
                    else
                    {
                        attendance.LocationNameHtml = attendance.LocationName;
                    }
                }

                pnlCheckinHistory.Visible = attendances.Any();

                gAttendanceHistory.DataSource = attendances;
                gAttendanceHistory.DataBind();
            }
        }
Ejemplo n.º 13
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var personAliasService = new PersonAliasService(rockContext);

            // get person
            Person person = null;
            var    guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    var attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value).AsGuidOrNull();
                    if (attributePersonValue.HasValue)
                    {
                        person = personAliasService.GetPerson(attributePersonValue.Value);
                        if (person == null)
                        {
                            errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute));
                            return(false);
                        }
                    }
                }
            }

            Person relatedPerson = null;

            var guidRelatedPersonAttribute = GetAttributeValue(action, "RelationshipTo").AsGuidOrNull();

            if (guidRelatedPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidRelatedPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    var attributePersonValue = action.GetWorklowAttributeValue(guidRelatedPersonAttribute.Value).AsGuidOrNull();
                    if (attributePersonValue.HasValue)
                    {
                        relatedPerson = personAliasService.GetPerson(attributePersonValue.Value);
                        if (relatedPerson == null)
                        {
                            errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute));
                            return(false);
                        }
                    }
                }
            }


            var groupTypeRoleService = new GroupTypeRoleService(rockContext);

            GroupTypeRole relationshipType     = null;
            var           relationshipRoleGuid = GetActionAttributeValue(action, "RelationshipType").AsGuidOrNull();

            if (relationshipRoleGuid.HasValue)
            {
                relationshipType = groupTypeRoleService.Get(relationshipRoleGuid.Value);
                if (relationshipType == null)
                {
                    errorMessages.Add(string.Format("GroupTypeRole (Relationship Type) could not be found for selected value ('{0}')!", relationshipRoleGuid));
                    return(false);
                }
            }

            var groupMemberService = new GroupMemberService(rockContext);

            // Check if relationship already exists
            if (
                groupMemberService.GetKnownRelationship(person.Id, relationshipType.Id)
                .Any(gm => gm.Person.Id == relatedPerson.Id))
            {
                errorMessages.Add(string.Format("Relationship of {0} already exists between {1} and {2}", relationshipType.Name, person.FullName, relatedPerson.FullName));
                return(false);
            }

            groupMemberService.CreateKnownRelationship(person.Id, relatedPerson.Id, relationshipType.Id);

            // Create inverse relationship if it doesn't exist.
            if (relationshipType.Attributes.ContainsKey("InverseRelationship"))
            {
                var inverseRelationshipTypeGuid =
                    relationshipType.GetAttributeValue("InverseRelationship").AsGuidOrNull();
                if (inverseRelationshipTypeGuid.HasValue)
                {
                    var inverseRelationshipType = groupTypeRoleService.Get(inverseRelationshipTypeGuid.Value);
                    // Ensure relationship doesn't already exist
                    if (!groupMemberService.GetKnownRelationship(relatedPerson.Id, inverseRelationshipType.Id)
                        .Any(gm => gm.Person.Id == person.Id))
                    {
                        groupMemberService.CreateKnownRelationship(relatedPerson.Id, person.Id, inverseRelationshipType.Id);
                    }
                }
            }


            return(true);
        }