コード例 #1
0
        public void RenderPage()
        {
            var                   pairs                 = GetAttributeValue("GroupIds").ToKeyValuePairList();
            RockContext           rockContext           = new RockContext();
            GroupMemberService    groupMemberService    = new GroupMemberService(rockContext);
            AttributeValueService attributeValueService = new AttributeValueService(rockContext);
            List <GroupMember>    members               = new List <GroupMember>();

            foreach (var pair in pairs)
            {
                var volunteerId = pair.Key.AsInteger();
                var volunteers  = groupMemberService.GetByGroupIdAndPersonId(volunteerId, CurrentPerson.Id);
                foreach (var volunteer in volunteers)
                {
                    //Add the volunteer and any other volunteers
                    members.Add(volunteer);
                    volunteer.LoadAttributes();
                    var campGroupName   = volunteer.GetAttributeValue(GetAttributeValue("VolunteerGroupKey"));
                    var otherVolunteers = groupMemberService.GetByGroupId(volunteer.GroupId);
                    var volunterGroupAttributeValues = attributeValueService.GetByAttributeId(volunteer.Attributes[GetAttributeValue("VolunteerGroupKey")].Id).ToList();

                    foreach (var otherVolunteer in otherVolunteers)
                    {
                        if (volunterGroupAttributeValues.Where(av => av.EntityId == otherVolunteer.Id && av.Value == campGroupName).Any())
                        {
                            members.Add(otherVolunteer);
                        }
                    }

                    //Now add matching students
                    var students = groupMemberService.GetByGroupId((( string )pair.Value).AsInteger());
                    if (students.Any())
                    {
                        var firstStudent = students.FirstOrDefault();
                        firstStudent.LoadAttributes();
                        var studentGroupAttributeValues = attributeValueService.GetByAttributeId(firstStudent.Attributes[GetAttributeValue("StudentGroupKey")].Id).ToList();
                        foreach (var student in students)
                        {
                            if (studentGroupAttributeValues.Where(av => av.EntityId == student.Id && av.Value == campGroupName).Any())
                            {
                                members.Add(student);
                            }
                        }
                    }
                }
            }
            members = members.DistinctBy(gm => gm.PersonId).ToList();
            var enabledCommands = GetAttributeValue("EnabledLavaCommands");
            var mergeObjects    = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, CurrentPerson);

            mergeObjects.Add("GroupMembers", members);
            ltOutput.Text = GetAttributeValue("Lava").ResolveMergeFields(mergeObjects, enabledCommands);
        }
コード例 #2
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";
        }
コード例 #3
0
ファイル: StaffMemberData.cs プロジェクト: secc/RockPlugins
        /// <summary>
        /// Get Staff members by Ministry Area
        /// </summary>
        /// <param name="ministryAID">The Ministry Attribute ID.</param>
        /// <param name="positionAID">The position Attribute ID.</param>
        /// <param name="ministryID">The ministry DefinedType ID.</param>
        /// <returns></returns>
        public DataTable GetStaffMembersDTByMinistryID(int ministryAID, int positionAID, Guid?ministryID)
        {
            Rock.Data.RockContext context = new Rock.Data.RockContext();
            AttributeValueService attributeValueService = new AttributeValueService(context);
            AttributeService      attributeService      = new AttributeService(context);

            Rock.Model.Attribute ministryAttribute = attributeService.Get(ministryAID);
            Rock.Model.Attribute positionAttribute = attributeService.Get(positionAID);

            var matchingAttributes = attributeValueService.GetByAttributeId(ministryAttribute.Id).Where(av => av.Value == ministryID.ToString());

            DataTable results = new DataTable();

            results.Columns.Add("PersonAliasId");
            results.Columns.Add("Name");
            results.Columns.Add("Ministry Area");
            results.Columns.Add("Position");
            foreach (AttributeValue attributeValue in matchingAttributes)
            {
                PersonService personService = new PersonService(context);

                Person person = personService.Get(attributeValue.EntityId.Value);
                person.LoadAttributes();
                if (person.RecordStatusValue.Value != "Inactive")
                {
                    DataRow dr = results.NewRow();
                    dr["PersonAliasId"] = person.PrimaryAliasId;
                    dr["Name"]          = person.FullName;
                    if (person.AttributeValues[ministryAttribute.Key] != null)
                    {
                        dr["Ministry Area"] = person.AttributeValues[ministryAttribute.Key].Value;
                    }
                    else
                    {
                        dr["Ministry Area"] = "N/A";
                    }
                    if (person.AttributeValues[positionAttribute.Key] != null)
                    {
                        dr["Position"] = person.AttributeValues[positionAttribute.Key].Value;
                    }
                    else
                    {
                        dr["Position"] = "N/A";
                    }
                    results.Rows.Add(dr);
                }
            }
            return(results);
        }
コード例 #4
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var lookupContext         = new RockContext();
            var attributeValueService = new AttributeValueService(lookupContext);
            var attributeService      = new AttributeService(lookupContext);

            IntegerFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.INTEGER)).Id;
            TextFieldTypeId    = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT)).Id;
            PersonEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id;
            CampusList         = CampusCache.All(lookupContext);

            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            int batchEntityTypeId     = EntityTypeCache.Read("Rock.Model.FinancialBatch").Id;
            int userLoginTypeId       = EntityTypeCache.Read("Rock.Model.UserLogin").Id;

            int visitInfoCategoryId = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                      .Where(c => c.Name == "Visit Information").Select(c => c.Id).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).ToList();

            var householdAttribute = personAttributes.FirstOrDefault(a => a.Key == "F1HouseholdId");

            if (householdAttribute == null)
            {
                householdAttribute                           = new Rock.Model.Attribute();
                householdAttribute.Key                       = "F1HouseholdId";
                householdAttribute.Name                      = "F1 Household Id";
                householdAttribute.FieldTypeId               = IntegerFieldTypeId;
                householdAttribute.EntityTypeId              = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue  = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description               = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue              = string.Empty;
                householdAttribute.IsMultiValue              = false;
                householdAttribute.IsRequired                = false;
                householdAttribute.Order                     = 0;

                lookupContext.Attributes.Add(householdAttribute);
                lookupContext.SaveChanges(DisableAudit);
                personAttributes.Add(householdAttribute);
            }

            var individualAttribute = personAttributes.FirstOrDefault(a => a.Key == "F1IndividualId");

            if (individualAttribute == null)
            {
                individualAttribute                           = new Rock.Model.Attribute();
                individualAttribute.Key                       = "F1IndividualId";
                individualAttribute.Name                      = "F1 Individual Id";
                individualAttribute.FieldTypeId               = IntegerFieldTypeId;
                individualAttribute.EntityTypeId              = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue  = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description               = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue              = string.Empty;
                individualAttribute.IsMultiValue              = false;
                individualAttribute.IsRequired                = false;
                individualAttribute.Order                     = 0;

                lookupContext.Attributes.Add(individualAttribute);
                lookupContext.SaveChanges(DisableAudit);
                personAttributes.Add(individualAttribute);
            }

            var secondaryEmailAttribute = personAttributes.FirstOrDefault(a => a.Key == "SecondaryEmail");

            if (secondaryEmailAttribute == null)
            {
                secondaryEmailAttribute                           = new Rock.Model.Attribute();
                secondaryEmailAttribute.Key                       = "SecondaryEmail";
                secondaryEmailAttribute.Name                      = "Secondary Email";
                secondaryEmailAttribute.FieldTypeId               = TextFieldTypeId;
                secondaryEmailAttribute.EntityTypeId              = PersonEntityTypeId;
                secondaryEmailAttribute.EntityTypeQualifierValue  = string.Empty;
                secondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty;
                secondaryEmailAttribute.Description               = "The secondary email for this person";
                secondaryEmailAttribute.DefaultValue              = string.Empty;
                secondaryEmailAttribute.IsMultiValue              = false;
                secondaryEmailAttribute.IsRequired                = false;
                secondaryEmailAttribute.Order                     = 0;

                lookupContext.Attributes.Add(secondaryEmailAttribute);
                var visitInfoCategory = new CategoryService(lookupContext).Get(visitInfoCategoryId);
                secondaryEmailAttribute.Categories.Add(visitInfoCategory);
                lookupContext.SaveChanges(DisableAudit);
            }

            IndividualAttributeId     = individualAttribute.Id;
            HouseholdAttributeId      = householdAttribute.Id;
            SecondaryEmailAttributeId = secondaryEmailAttribute.Id;

            ReportProgress(0, "Checking for existing data...");
            var listHouseholdId  = attributeValueService.GetByAttributeId(householdAttribute.Id).Select(av => new { PersonId = av.EntityId, HouseholdId = av.Value }).ToList();
            var listIndividualId = attributeValueService.GetByAttributeId(individualAttribute.Id).Select(av => new { PersonId = av.EntityId, IndividualId = av.Value }).ToList();

            // var listHouseholdId = new PersonService().Queryable().Select( )

            ImportedPeople = listHouseholdId.GroupJoin(listIndividualId,
                                                       household => household.PersonId,
                                                       individual => individual.PersonId,
                                                       (household, individual) => new ImportedPerson
            {
                PersonAliasId = household.PersonId,
                HouseholdId   = household.HouseholdId.AsType <int?>(),
                IndividualId  = individual.Select(i => i.IndividualId.AsType <int?>()).FirstOrDefault()
            }
                                                       ).ToList();

            ImportedBatches = new FinancialBatchService(lookupContext).Queryable()
                              .Where(b => b.ForeignId != null)
                              .Select(b => new { F1Id = b.ForeignId, BatchId = b.Id })
                              .ToDictionary(t => t.F1Id.AsType <int>(), t => (int?)t.BatchId);
        }
コード例 #5
0
        private List <MedicalItem> GetMedicalItems(bool overrideHideDistributed = false)
        {
            RockContext                rockContext                = new RockContext();
            GroupService               groupService               = new GroupService(rockContext);
            AttributeMatrixService     attributeMatrixService     = new AttributeMatrixService(rockContext);
            AttributeValueService      attributeValueService      = new AttributeValueService(rockContext);
            AttributeMatrixItemService attributeMatrixItemService = new AttributeMatrixItemService(rockContext);
            NoteService                noteService                = new NoteService(rockContext);

            var groupIdStrings = GetAttributeValue("GroupIds").SplitDelimitedValues();
            var groupIds       = new List <int>();

            foreach (var id in groupIdStrings)
            {
                groupIds.Add(id.AsInteger());
            }

            var groups = groupService.GetByIds(groupIds);

            if (cpCampus.SelectedCampusId != null && cpCampus.SelectedCampusId != 0)
            {
                groups = groups.Where(g => g.CampusId == cpCampus.SelectedCampusId);
            }

            var groupTypeIds = groups.ToList().Select(g => g.GroupTypeId.ToString()).Distinct();

            var personEntityid      = EntityTypeCache.GetId <Rock.Model.Person>().Value;
            var groupMemberEntityid = EntityTypeCache.GetId <Rock.Model.GroupMember>().Value;
            var key = GetAttributeValue("MedicationMatrixKey");

            var days       = GetAttributeValue(AttributeKey.Days).AsIntegerOrNull() ?? 14;
            var cutoffDate = Rock.RockDateTime.Today.AddDays(-days);

            var lastMedicationCheckinAttribute = AttributeCache.Get(Constants.PERSON_ATTRIBUTE_LASTMEDICATIONCHECKIN.AsGuid());


            var allowedPersonIds = attributeValueService.GetByAttributeId(lastMedicationCheckinAttribute.Id)
                                   .Where(av => av.ValueAsDateTime != null && av.ValueAsDateTime >= cutoffDate)
                                   .Select(av => av.EntityId);

            var groupMembers = groups
                               .SelectMany(g => g.Members)
                               .Where(gm => allowedPersonIds.Contains(gm.PersonId));

            AttributeService attributeService = new AttributeService(rockContext);

            List <int> attributeIds = attributeService.Queryable()
                                      .Where(a =>
                                             a.EntityTypeId == personEntityid &&
                                             a.Key == key)
                                      .Select(a => a.Id).ToList();

            if (attributeIds == null)
            {
                nbAlert.Visible = true;
                nbAlert.Text    = "Medication attribute not found";
                return(null);
            }

            List <int> filterAttributeIds = null;
            var        filterAttributeKey = GetAttributeValue("GroupMemberAttributeFilter");

            if (!string.IsNullOrWhiteSpace(filterAttributeKey))
            {
                filterAttributeIds = attributeService.Queryable()
                                     .Where(a =>
                                            (groupIdStrings.Contains(a.EntityTypeQualifierValue) || groupTypeIds.Contains(a.EntityTypeQualifierValue)) &&
                                            a.Key == filterAttributeKey &&
                                            a.EntityTypeId == groupMemberEntityid)
                                     .Select(a => a.Id).ToList();
            }

            var attributeMatrixItemEntityId = EntityTypeCache.GetId <AttributeMatrixItem>();

            var qry = groupMembers
                      .Join(
                attributeValueService.Queryable().Where(av => attributeIds.Contains(av.AttributeId)),
                m => m.PersonId,
                av => av.EntityId.Value,
                (m, av) => new { Person = m.Person, Member = m, AttributeValue = av.Value }
                )
                      .Join(
                attributeMatrixService.Queryable(),
                m => m.AttributeValue,
                am => am.Guid.ToString(),
                (m, am) => new { Person = m.Person, Member = m.Member, AttributeMatrix = am }
                )
                      .Join(
                attributeMatrixItemService.Queryable(),
                m => m.AttributeMatrix.Id,
                ami => ami.AttributeMatrixId,
                (m, ami) => new { Person = m.Person, Member = m.Member, AttributeMatrixItem = ami, TemplateId = ami.AttributeMatrix.AttributeMatrixTemplateId }
                )
                      .Join(
                attributeService.Queryable(),
                m => new { TemplateIdString = m.TemplateId.ToString(), EntityTypeId = attributeMatrixItemEntityId },
                a => new { TemplateIdString = a.EntityTypeQualifierValue, EntityTypeId = a.EntityTypeId },
                (m, a) => new { Person = m.Person, Member = m.Member, AttributeMatrixItem = m.AttributeMatrixItem, Attribute = a }
                )
                      .Join(
                attributeValueService.Queryable(),
                m => new { EntityId = m.AttributeMatrixItem.Id, AttributeId = m.Attribute.Id },
                av => new { EntityId = av.EntityId ?? 0, AttributeId = av.AttributeId },
                (m, av) => new { Person = m.Person, Member = m.Member, Attribute = m.Attribute, AttributeValue = av, MatrixItemId = m.AttributeMatrixItem.Id, FilterValue = "" }
                );

            if (filterAttributeIds != null && pnlAttribute.Visible && !string.IsNullOrWhiteSpace(ddlAttribute.SelectedValue))
            {
                var filterValue = ddlAttribute.SelectedValue;
                qry = qry
                      .Join(
                    attributeValueService.Queryable().Where(av => filterAttributeIds.Contains(av.AttributeId)),
                    m => new { Id = m.Member.Id, Value = filterValue },
                    av => new { Id = av.EntityId ?? 0, Value = av.Value },
                    (m, av) => new { Person = m.Person, Member = m.Member, Attribute = m.Attribute, AttributeValue = m.AttributeValue, MatrixItemId = m.MatrixItemId, FilterValue = av.Value });
            }
            var members = qry.ToList().GroupBy(a => a.Person).ToList();

            var firstDay = (dpDate.SelectedDate ?? Rock.RockDateTime.Today).Date;
            var nextday  = firstDay.AddDays(1);

            var personIds = members.Select(m => m.Key.Id);
            var attributeMatrixEntityTypeId = EntityTypeCache.GetId <AttributeMatrixItem>().Value;

            var noteType = NoteTypeCache.Get(GetAttributeValue("NoteType").AsGuid());

            if (noteType == null)
            {
                return(new List <MedicalItem>());
            }

            var noteItems = noteService.Queryable()
                            .Where(n => n.NoteTypeId == noteType.Id)
                            .Where(n => personIds.Contains(n.EntityId ?? 0))
                            .Where(h => h.CreatedDateTime >= firstDay && h.CreatedDateTime < nextday)
                            .Where(h => h.ForeignId != null)
                            .ToList();

            foreach (var member in members)
            {
                if (!string.IsNullOrWhiteSpace(tbName.Text) &&
                    !member.Key.FullName.ToLower().Contains(tbName.Text.ToLower()) &&
                    !member.Key.FullNameReversed.ToLower().Contains(tbName.Text.ToLower()))
                {
                    continue;
                }

                var medicines = member.GroupBy(m => m.MatrixItemId);
                foreach (var medicine in medicines)
                {
                    var scheduleAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Schedule");
                    if (scheduleAtt == null || scheduleAtt.AttributeValue.Value == null)
                    {
                        continue;
                    }
                    var schedules = scheduleAtt.AttributeValue.Value.SplitDelimitedValues();
                    foreach (var schedule in schedules)
                    {
                        if (ddlSchedule.SelectedValue != "" && ddlSchedule.SelectedValue.AsGuid() != schedule.AsGuid())
                        {
                            continue;
                        }

                        var medicalItem = new MedicalItem()
                        {
                            Person          = member.Key.FullNameReversed,
                            GroupMemberId   = member.Key.Id,
                            GroupMember     = member.Key.Members.FirstOrDefault(),
                            PersonId        = member.Key.Id,
                            FilterAttribute = member.FirstOrDefault().FilterValue,
                        };

                        if (!string.IsNullOrWhiteSpace(schedule))
                        {
                            var dv = DefinedValueCache.Get(schedule.AsGuid());
                            if (dv != null)
                            {
                                medicalItem.Schedule     = dv.Value;
                                medicalItem.ScheduleGuid = dv.Guid;
                            }
                        }

                        var medAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Medication");
                        if (medAtt != null)
                        {
                            medicalItem.Medication = medAtt.AttributeValue.Value;
                        }

                        var instructionAtt = medicine.FirstOrDefault(m => m.Attribute.Key == "Instructions");
                        if (instructionAtt != null)
                        {
                            medicalItem.Instructions = instructionAtt.AttributeValue.Value;
                        }
                        medicalItem.Key = string.Format("{0}|{1}|{2}", medicalItem.PersonId, medicine.Key, medicalItem.ScheduleGuid);

                        var notes = noteItems
                                    .Where(n => n.EntityId == medicalItem.PersonId && n.ForeignId == medicine.Key && n.ForeignGuid == medicalItem.ScheduleGuid);

                        if (notes.Any())
                        {
                            medicalItem.Distributed = true;
                            medicalItem.History     = string.Join("<br>", notes.Select(n => n.Text));
                        }

                        medicalItems.Add(medicalItem);
                    }
                }
                if (overrideHideDistributed == false && cbHideDistributed.Checked == true)
                {
                    medicalItems = medicalItems.Where(i => i.Distributed == false).ToList();
                }
            }

            SortProperty sortProperty = gGrid.SortProperty;

            if (sortProperty != null)
            {
                if (sortProperty.Property == "Person")
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        medicalItems = medicalItems.OrderBy(mi => mi.Person).ToList();
                    }
                    else
                    {
                        medicalItems = medicalItems.OrderByDescending(mi => mi.Person).ToList();
                    }
                }
            }
            else
            {
                medicalItems       = medicalItems.OrderBy(mi => mi.Person).ToList();
                gGrid.SortProperty = new SortProperty()
                {
                    Property = "Person"
                };
            }

            return(medicalItems);
        }
コード例 #6
0
        public static IEnumerable <Person> GetByMatch(this PersonService personService, String firstName, String lastName, DateTime?birthDate, String email = null, String phone = null, String street1 = null, String postalCode = null)
        {
            using (Rock.Data.RockContext context = new Rock.Data.RockContext())
            {
                //FirstName LastName and (DOB or email or phone or street address) are required. If not return an empty list.
                if (firstName.IsNullOrWhiteSpace() || lastName.IsNullOrWhiteSpace() ||
                    (!birthDate.HasValue &&
                     string.IsNullOrWhiteSpace(email) &&
                     string.IsNullOrWhiteSpace(phone) &&
                     string.IsNullOrWhiteSpace(street1)))
                {
                    return(new List <Person>());
                }

                LocationService       locationService       = new LocationService(context);
                AttributeValueService attributeValueService = new AttributeValueService(context);
                List <AttributeValue> attributeValues       = attributeValueService.GetByAttributeId(AttributeCache.Get(GOES_BY_ATTRIBUTE.AsGuid()).Id).ToList();
                var diminutiveName = DefinedTypeCache.Get(DIMINUTIVE_NAMES.AsGuid());

                firstName = firstName ?? string.Empty;
                lastName  = lastName ?? string.Empty;
                email     = email.ToLower() ?? string.Empty;
                phone     = PhoneNumber.CleanNumber(phone ?? string.Empty);
                List <Person> matchingPersons = new List <Person>();

                // Do a quick check to see if we get a match right up front
                List <Person> persons = new List <Person>();
                if (birthDate.HasValue || !string.IsNullOrEmpty(email))
                {
                    var fastQuery = personService.Queryable(false, false).Where(p => (p.FirstName.ToLower() == firstName.ToLower() || p.NickName.ToLower() == firstName.ToLower()) && p.LastName == lastName);
                    if (birthDate.HasValue)
                    {
                        fastQuery = fastQuery.Where(p => p.BirthDate == birthDate);
                    }
                    if (!String.IsNullOrEmpty(email))
                    {
                        fastQuery = fastQuery.Where(p => p.Email.ToLower() == email);
                    }
                    persons = fastQuery.ToList();

                    // We have an exact match.  Just be done.
                    if (persons.Count == 1)
                    {
                        return(persons);
                    }
                }

                // Go ahead and do this more leniant search if we get this far
                persons = personService.Queryable(false, false)
                          .Where(p =>
                                 p.LastName == lastName &&
                                 (!birthDate.HasValue || p.BirthDate == null || (birthDate.HasValue && p.BirthDate.Value == birthDate.Value)))
                          .ToList();

                // Set a placeholder for the location so we only geocode it 1 time
                Location location = null;

                foreach (Person person in persons)
                {
                    // Check to see if the phone exists anywhere in the family
                    Boolean phoneExists = !string.IsNullOrWhiteSpace(phone) && person.GetFamilies().Where(f => f.Members.Where(m => m.Person.PhoneNumbers.Where(pn => pn.Number == phone).Any()).Any()).Any();

                    // Check to see if the email exists anywhere in the family
                    Boolean emailExists = !string.IsNullOrWhiteSpace(email) && person.GetFamilies().Where(f => f.Members.Where(m => m.Person.Email == email).Any()).Any();

                    Boolean addressMatches = false;
                    // Check the address if it was passed
                    if (!string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode))
                    {
                        if (person.GetHomeLocation() != null)
                        {
                            if (person.GetHomeLocation().Street1 == street1)
                            {
                                addressMatches = true;
                            }
                            // If it doesn't match, we need to geocode it and check it again
                            if (location == null && !string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode))
                            {
                                location            = new Location();
                                location.Street1    = street1;
                                location.PostalCode = postalCode;
                                locationService.Verify(location, true);
                            }
                            if (location != null && !addressMatches && person.GetHomeLocation().Street1 == location.Street1)
                            {
                                addressMatches = true;
                            }
                        }
                    }

                    // At least phone, email, or address have to match
                    if (phoneExists || emailExists || addressMatches)
                    {
                        matchingPersons.Add(person);
                    }
                }

                List <Person> firstNameMatchingPersons = new List <Person>();

                // Now narrow down the list by looking for the first name (or diminutive name)
                foreach (Person matchingPerson in matchingPersons)
                {
                    if (firstName != null && ((matchingPerson.FirstName != null && matchingPerson.FirstName.ToLower() != firstName.ToLower()) || (matchingPerson.NickName != null && matchingPerson.NickName.ToLower() != firstName.ToLower())))
                    {
                        foreach (DefinedValueCache dv in diminutiveName.DefinedValues)
                        {
                            AttributeValue av       = attributeValues.Where(av2 => av2.EntityId == dv.Id).FirstOrDefault();
                            List <string>  nameList = new List <string>();
                            nameList = av.Value.Split('|').ToList();
                            nameList.Add(dv.Value);
                            if (nameList.Contains(firstName.ToLower()) &&
                                (nameList.Contains(matchingPerson.FirstName.ToLower()) || nameList.Contains(matchingPerson.NickName.ToLower())))
                            {
                                firstNameMatchingPersons.Add(matchingPerson);
                                break;
                            }
                        }
                    }
                    else
                    {
                        firstNameMatchingPersons.Add(matchingPerson);
                    }
                }

                return(firstNameMatchingPersons);
            }
        }
コード例 #7
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        private void LoadExistingRockData()
        {
            var lookupContext         = new RockContext();
            var attributeValueService = new AttributeValueService(lookupContext);
            var attributeService      = new AttributeService(lookupContext);

            IntegerFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.INTEGER)).Id;
            TextFieldTypeId    = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT)).Id;
            PersonEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id;
            CampusList         = CampusCache.All();

            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            int batchEntityTypeId     = EntityTypeCache.Read("Rock.Model.FinancialBatch").Id;
            int userLoginTypeId       = EntityTypeCache.Read("Rock.Model.UserLogin").Id;

            int visitInfoCategoryId = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                      .Where(c => c.Name == "Visit Information").Select(c => c.Id).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).AsNoTracking().ToList();

            var householdAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("F1HouseholdId", StringComparison.InvariantCultureIgnoreCase));

            if (householdAttribute == null)
            {
                householdAttribute                           = new Rock.Model.Attribute();
                householdAttribute.Key                       = "F1HouseholdId";
                householdAttribute.Name                      = "F1 Household Id";
                householdAttribute.FieldTypeId               = IntegerFieldTypeId;
                householdAttribute.EntityTypeId              = PersonEntityTypeId;
                householdAttribute.EntityTypeQualifierValue  = string.Empty;
                householdAttribute.EntityTypeQualifierColumn = string.Empty;
                householdAttribute.Description               = "The FellowshipOne household identifier for the person that was imported";
                householdAttribute.DefaultValue              = string.Empty;
                householdAttribute.IsMultiValue              = false;
                householdAttribute.IsRequired                = false;
                householdAttribute.Order                     = 0;

                lookupContext.Attributes.Add(householdAttribute);
                lookupContext.SaveChanges(DisableAuditing);
                personAttributes.Add(householdAttribute);
            }

            var individualAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("F1IndividualId", StringComparison.InvariantCultureIgnoreCase));

            if (individualAttribute == null)
            {
                individualAttribute                           = new Rock.Model.Attribute();
                individualAttribute.Key                       = "F1IndividualId";
                individualAttribute.Name                      = "F1 Individual Id";
                individualAttribute.FieldTypeId               = IntegerFieldTypeId;
                individualAttribute.EntityTypeId              = PersonEntityTypeId;
                individualAttribute.EntityTypeQualifierValue  = string.Empty;
                individualAttribute.EntityTypeQualifierColumn = string.Empty;
                individualAttribute.Description               = "The FellowshipOne individual identifier for the person that was imported";
                individualAttribute.DefaultValue              = string.Empty;
                individualAttribute.IsMultiValue              = false;
                individualAttribute.IsRequired                = false;
                individualAttribute.Order                     = 0;

                lookupContext.Attributes.Add(individualAttribute);
                lookupContext.SaveChanges(DisableAuditing);
                personAttributes.Add(individualAttribute);
            }

            var secondaryEmailAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("SecondaryEmail", StringComparison.InvariantCultureIgnoreCase));

            if (secondaryEmailAttribute == null)
            {
                secondaryEmailAttribute                           = new Rock.Model.Attribute();
                secondaryEmailAttribute.Key                       = "SecondaryEmail";
                secondaryEmailAttribute.Name                      = "Secondary Email";
                secondaryEmailAttribute.FieldTypeId               = TextFieldTypeId;
                secondaryEmailAttribute.EntityTypeId              = PersonEntityTypeId;
                secondaryEmailAttribute.EntityTypeQualifierValue  = string.Empty;
                secondaryEmailAttribute.EntityTypeQualifierColumn = string.Empty;
                secondaryEmailAttribute.Description               = "The secondary email for this person";
                secondaryEmailAttribute.DefaultValue              = string.Empty;
                secondaryEmailAttribute.IsMultiValue              = false;
                secondaryEmailAttribute.IsRequired                = false;
                secondaryEmailAttribute.Order                     = 0;

                lookupContext.Attributes.Add(secondaryEmailAttribute);
                var visitInfoCategory = new CategoryService(lookupContext).Get(visitInfoCategoryId);
                secondaryEmailAttribute.Categories.Add(visitInfoCategory);
                lookupContext.SaveChanges(DisableAuditing);
            }

            var infellowshipLoginAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("InFellowshipLogin", StringComparison.InvariantCultureIgnoreCase));

            if (infellowshipLoginAttribute == null)
            {
                infellowshipLoginAttribute                           = new Rock.Model.Attribute();
                infellowshipLoginAttribute.Key                       = "InFellowshipLogin";
                infellowshipLoginAttribute.Name                      = "InFellowship Login";
                infellowshipLoginAttribute.FieldTypeId               = TextFieldTypeId;
                infellowshipLoginAttribute.EntityTypeId              = PersonEntityTypeId;
                infellowshipLoginAttribute.EntityTypeQualifierValue  = string.Empty;
                infellowshipLoginAttribute.EntityTypeQualifierColumn = string.Empty;
                infellowshipLoginAttribute.Description               = "The InFellowship login for this person";
                infellowshipLoginAttribute.DefaultValue              = string.Empty;
                infellowshipLoginAttribute.IsMultiValue              = false;
                infellowshipLoginAttribute.IsRequired                = false;
                infellowshipLoginAttribute.Order                     = 0;

                // don't add a category as this attribute is only used via the API
                lookupContext.Attributes.Add(infellowshipLoginAttribute);
                lookupContext.SaveChanges(DisableAuditing);
            }

            IndividualIdAttribute      = AttributeCache.Read(individualAttribute.Id);
            HouseholdIdAttribute       = AttributeCache.Read(householdAttribute.Id);
            InFellowshipLoginAttribute = AttributeCache.Read(infellowshipLoginAttribute.Id);
            SecondaryEmailAttribute    = AttributeCache.Read(secondaryEmailAttribute.Id);

            // Set AuthProviderEntityTypeId if Apollos/Infellowship provider exists
            var f1AuthProvider = "cc.newspring.F1.Security.Authentication.F1Migrator";
            var cache          = EntityTypeCache.Read(f1AuthProvider);

            AuthProviderEntityTypeId = cache == null ? (int?)null : cache.Id;

            var aliasIdList = new PersonAliasService(lookupContext).Queryable().AsNoTracking()
                              .Select(pa => new
            {
                PersonAliasId = pa.Id,
                PersonId      = pa.PersonId,
                IndividualId  = pa.ForeignId,
                FamilyRole    = pa.Person.ReviewReasonNote
            }).ToList();
            var householdIdList = attributeValueService.GetByAttributeId(householdAttribute.Id).AsNoTracking()
                                  .Select(av => new
            {
                PersonId    = (int)av.EntityId,
                HouseholdId = av.Value
            }).ToList();

            ImportedPeople = householdIdList.GroupJoin(aliasIdList,
                                                       household => household.PersonId,
                                                       aliases => aliases.PersonId,
                                                       (household, aliases) => new PersonKeys
            {
                PersonAliasId = aliases.Select(a => a.PersonAliasId).FirstOrDefault(),
                PersonId      = household.PersonId,
                IndividualId  = aliases.Select(a => a.IndividualId).FirstOrDefault(),
                HouseholdId   = household.HouseholdId.AsType <int?>(),
                FamilyRoleId  = aliases.Select(a => a.FamilyRole.ConvertToEnum <FamilyRole>(0)).FirstOrDefault()
            }
                                                       ).ToList();

            ImportedBatches = new FinancialBatchService(lookupContext).Queryable().AsNoTracking()
                              .Where(b => b.ForeignId != null)
                              .ToDictionary(t => (int)t.ForeignId, t => (int?)t.Id);
        }
コード例 #8
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        /// <param name="scanner">The scanner.</param>
        private void LoadGlobalObjects(DataScanner scanner)
        {
            var lookupContext         = new RockContext();
            var attributeValueService = new AttributeValueService(lookupContext);
            var attributeService      = new AttributeService(lookupContext);

            var visitInfoCategoryId = new CategoryService(lookupContext).GetByEntityTypeId(AttributeEntityTypeId)
                                      .Where(c => c.Name == "Visit Information").Select(c => c.Id).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var attributeKey     = "F1HouseholdId";
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).AsNoTracking().ToList();

            HouseholdIdAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals(attributeKey, StringComparison.InvariantCultureIgnoreCase));
            if (HouseholdIdAttribute == null)
            {
                HouseholdIdAttribute = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, string.Format("{0} imported {1}", attributeKey, ImportDateTime),
                                                          "Visit Information", "F1 Household Id", attributeKey, IntegerFieldTypeId
                                                          );
            }

            attributeKey          = "F1IndividualId";
            IndividualIdAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals(attributeKey, StringComparison.InvariantCultureIgnoreCase));
            if (IndividualIdAttribute == null)
            {
                IndividualIdAttribute = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, string.Format("{0} imported {1}", attributeKey, ImportDateTime),
                                                           "Visit Information", "F1 Individual Id", attributeKey, IntegerFieldTypeId
                                                           );
            }

            attributeKey            = "SecondaryEmail";
            SecondaryEmailAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals(attributeKey, StringComparison.InvariantCultureIgnoreCase));
            if (SecondaryEmailAttribute == null)
            {
                SecondaryEmailAttribute = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, string.Format("{0} imported {1}", attributeKey, ImportDateTime),
                                                             "Visit Information", "Secondary Email", attributeKey, TextFieldTypeId
                                                             );
            }

            attributeKey = "InFellowshipLogin";
            InFellowshipLoginAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals(attributeKey, StringComparison.InvariantCultureIgnoreCase));
            if (InFellowshipLoginAttribute == null)
            {
                InFellowshipLoginAttribute = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, string.Format("{0} imported {1}", attributeKey, ImportDateTime),
                                                                "Visit Information", "InFellowship Login", attributeKey, TextFieldTypeId
                                                                );
            }

            var aliasIdList = new PersonAliasService(lookupContext).Queryable().AsNoTracking()
                              .Select(pa => new
            {
                PersonAliasId = pa.Id,
                PersonId      = pa.PersonId,
                ForeignId     = pa.ForeignId,
                FamilyRole    = pa.Person.ReviewReasonNote
            }).ToList();
            var householdIdList = attributeValueService.GetByAttributeId(HouseholdIdAttribute.Id).AsNoTracking()
                                  .Select(av => new
            {
                PersonId    = (int)av.EntityId,
                HouseholdId = av.Value
            }).ToList();

            ImportedPeople = householdIdList.GroupJoin(aliasIdList,
                                                       household => household.PersonId,
                                                       aliases => aliases.PersonId,
                                                       (household, aliases) => new PersonKeys
            {
                PersonAliasId   = aliases.Select(a => a.PersonAliasId).FirstOrDefault(),
                PersonId        = household.PersonId,
                PersonForeignId = aliases.Select(a => a.ForeignId).FirstOrDefault(),
                GroupForeignId  = household.HouseholdId.AsType <int?>(),
                FamilyRoleId    = aliases.Select(a => a.FamilyRole.ConvertToEnum <FamilyRole>(0)).FirstOrDefault()
            }
                                                       ).ToList();

            ImportedGroupTypes = new GroupTypeService(lookupContext).Queryable().AsNoTracking()
                                 .Where(t => t.Id != FamilyGroupTypeId && t.ForeignKey != null)
                                 .ToList();

            ImportedGroups = new GroupService(lookupContext).Queryable().AsNoTracking()
                             .Where(g => g.GroupTypeId != FamilyGroupTypeId && g.ForeignKey != null)
                             .ToList();

            ImportedBatches = new FinancialBatchService(lookupContext).Queryable().AsNoTracking()
                              .Where(b => b.ForeignId.HasValue)
                              .ToDictionary(t => (int)t.ForeignId, t => (int?)t.Id);

            // get the portal users for lookups on notes
            var userIdList = scanner.ScanTable("Users")
                             .Select(s => new
            {
                UserId    = s["UserID"] as int?,
                ForeignId = s["LinkedIndividualID"] as int?
            }).ToList();

            PortalUsers = userIdList.Join(aliasIdList,
                                          users => users.ForeignId,
                                          aliases => aliases.ForeignId,
                                          (users, aliases) => new
            {
                UserId        = users.UserId,
                PersonAliasId = aliases.PersonAliasId
            }).ToDictionary(t => (int)t.UserId, t => t.PersonAliasId);
        }
コード例 #9
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();
            // Get the team that should be serving this week
            string weekTeam = "Team " + com.bricksandmortarstudio.TheCrossing.Utils.ServingWeek.GetTeamNumber();

            // Get the group members who should be serving
            var attributeService         = new AttributeService(rockContext);
            var groupMemberEntityType    = EntityTypeCache.Read(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid());
            var assignedTeamAttributeIds =
                attributeService.GetByEntityTypeId(
                    EntityTypeCache.Read(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id).Where(a => a.Key == "AssignedTeam").Select(a => a.Id);

            var assignedServicesAttributeIds =
                attributeService.GetByEntityTypeId(groupMemberEntityType.Id).Where(a => a.Key == "AssignedServices").Select(a => a.Id);

            var attributeValueService = new AttributeValueService(rockContext);
            var groupMemberIds        = new List <int>();

            foreach (int attributeId in assignedTeamAttributeIds)
            {
                var attributeValues = attributeValueService.GetByAttributeId(attributeId).AsQueryable().AsNoTracking().Where(av => av.Value.Contains(weekTeam));
                groupMemberIds.AddRange(attributeValues.Where(av => av.EntityId != null).Select(av => av.EntityId.Value));
            }

            // Find the group member information to present
            IEnumerable <GroupMember> query = new GroupMemberService(rockContext).GetListByIds(groupMemberIds);


            //Filtering to a specific group branch

            var groupService = new GroupService(rockContext);
            var group        = hfGroupGuid.Value.AsGuidOrNull() != null
                ? groupService.GetByGuid(hfGroupGuid.Value.AsGuid())
                : groupService.Get(gFilter.GetUserPreference("Group").AsInteger());

            if (group != null)
            {
                var validGroupIds = new List <int> {
                    group.Id
                };
                validGroupIds.AddRange(groupService.GetAllDescendents(group.Id).Select(g => g.Id));

                query = query.Where(gm => validGroupIds.Contains(gm.GroupId));
            }


            var allScheduledPeople = query.Select(gm =>
                                                  new GroupAndPerson
            {
                Name         = gm.Person.FullName,
                GroupName    = gm.Group.Name,
                ParentGroup  = gm.Group.ParentGroup,
                ServiceTimes = attributeValueService.Queryable().AsNoTracking().Where(a => a.EntityId == gm.Id && assignedServicesAttributeIds.Contains(a.AttributeId)).FirstOrDefault()
            });

            // Sort and bind
            var sortProperty = gList.SortProperty;

            if (sortProperty == null)
            {
                gList.DataSource = allScheduledPeople.OrderBy(gp => gp.GroupName).ToList();
            }
            else
            {
                gList.DataSource = allScheduledPeople.AsQueryable().Sort(sortProperty).ToList();
            }
            gList.DataBind();
        }
コード例 #10
0
        /// <summary>
        /// Loads Rock data that's used globally by the transform
        /// </summary>
        /// <param name="scanner">The scanner.</param>
        private void LoadGlobalObjects(DataScanner scanner)
        {
            var lookupContext         = new RockContext();
            var attributeValueService = new AttributeValueService(lookupContext);
            var attributeService      = new AttributeService(lookupContext);

            var visitInfoCategoryId = new CategoryService(lookupContext).GetByEntityTypeId(AttributeEntityTypeId)
                                      .Where(c => c.Name == "Visit Information").Select(c => c.Id).FirstOrDefault();

            // Look up and create attributes for F1 unique identifiers if they don't exist
            var attributeKey     = "F1HouseholdId";
            var personAttributes = attributeService.GetByEntityTypeId(PersonEntityTypeId).AsNoTracking().ToList();

            HouseholdIdAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals(attributeKey, StringComparison.OrdinalIgnoreCase));
            if (HouseholdIdAttribute == null)
            {
                HouseholdIdAttribute = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, string.Format("{0} imported {1}", attributeKey, ImportDateTime),
                                                          "Visit Information", "F1 Household Id", attributeKey, IntegerFieldTypeId
                                                          );
            }

            attributeKey          = "F1IndividualId";
            IndividualIdAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals(attributeKey, StringComparison.OrdinalIgnoreCase));
            if (IndividualIdAttribute == null)
            {
                IndividualIdAttribute = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, string.Format("{0} imported {1}", attributeKey, ImportDateTime),
                                                           "Visit Information", "F1 Individual Id", attributeKey, IntegerFieldTypeId
                                                           );
            }

            attributeKey            = "SecondaryEmail";
            SecondaryEmailAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals(attributeKey, StringComparison.OrdinalIgnoreCase));
            if (SecondaryEmailAttribute == null)
            {
                SecondaryEmailAttribute = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, string.Format("{0} imported {1}", attributeKey, ImportDateTime),
                                                             "Visit Information", "Secondary Email", attributeKey, TextFieldTypeId
                                                             );
            }

            attributeKey = "InFellowshipLogin";
            InFellowshipLoginAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals(attributeKey, StringComparison.OrdinalIgnoreCase));
            if (InFellowshipLoginAttribute == null)
            {
                InFellowshipLoginAttribute = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, string.Format("{0} imported {1}", attributeKey, ImportDateTime),
                                                                "Visit Information", "InFellowship Login", attributeKey, TextFieldTypeId
                                                                );
            }

            var aliasIdList = new PersonAliasService(lookupContext).Queryable().AsNoTracking()
                              .Select(pa => new
            {
                PersonAliasId = pa.Id,
                PersonId      = pa.PersonId,
                Gender        = pa.Person.Gender,
                ForeignId     = pa.ForeignId,
                FamilyRole    = pa.Person.ReviewReasonNote
            }).ToList();
            var householdIdList = attributeValueService.GetByAttributeId(HouseholdIdAttribute.Id).AsNoTracking()
                                  .Select(av => new
            {
                PersonId    = ( int )av.EntityId,
                HouseholdId = av.Value
            }).ToList();

            ImportedPeople = householdIdList.GroupJoin(aliasIdList,
                                                       household => household.PersonId,
                                                       aliases => aliases.PersonId,
                                                       (household, aliases) => new PersonKeys
            {
                PersonAliasId   = aliases.Select(a => a.PersonAliasId).FirstOrDefault(),
                PersonId        = household.PersonId,
                PersonForeignId = aliases.Select(a => a.ForeignId).FirstOrDefault(),
                GroupForeignId  = household.HouseholdId.AsType <int?>(),
                PersonGender    = aliases.Select(a => a.Gender).FirstOrDefault(),
                FamilyRoleId    = aliases.Select(a => a.FamilyRole.ConvertToEnum <FamilyRole>(0)).FirstOrDefault()
            }
                                                       ).ToList();

            ImportedGroupTypes = new GroupTypeService(lookupContext).Queryable().AsNoTracking()
                                 .Where(t => t.Id != FamilyGroupTypeId && t.ForeignKey != null)
                                 .ToList();

            ImportedGroups = new GroupService(lookupContext).Queryable().AsNoTracking()
                             .Where(g => g.GroupTypeId != FamilyGroupTypeId && g.ForeignKey != null)
                             .ToList();

            ImportedSchedules = new ScheduleService(lookupContext).Queryable().AsNoTracking()
                                .Where(s => s.ForeignKey != null)
                                .ToList();

            ImportedCheckinActivityGroups = new List <Group>();

            // this is a lookup hack for when clients don't want to import groups
            if (!ImportedGroups.Any() && !DataNodes.Where(n => n.Checked == true).Any(n => n.Name.Equals("ActivityMinistry")))
            {
                ImportedGroups.AddRange(
                    scanner.ScanTable("ActivityMinistry")
                    .Select(s => new Group
                {
                    ForeignId = s["Activity_ID"] as int?,
                    Name      = s["Activity_Name"] as string
                }).ToList()
                    );

                ImportedGroups.AddRange(
                    scanner.ScanTable("RLC")
                    .Select(s => new Group
                {
                    ForeignId = s["RLC_ID"] as int?,
                    Name      = s["Room_Desc"] as string
                }).ToList()
                    );
            }

            ImportedBatches = new FinancialBatchService(lookupContext).Queryable().AsNoTracking()
                              .Where(b => b.ForeignId.HasValue)
                              .ToDictionary(t => ( int )t.ForeignId, t => ( int? )t.Id);

            ServingTeamsParentGroup = lookupContext.Groups.AsNoTracking().AsQueryable().FirstOrDefault(g => g.Guid.ToString() == "31730962-4C7B-425B-BD73-4185331F37EF");

            // get the portal users for lookups on notes
            var userIdList = scanner.ScanTable("Users")
                             .Select(s => new
            {
                UserId    = s["UserID"] as int?,
                ForeignId = s["LinkedIndividualID"] as int?
            }).ToList();

            PortalUsers = userIdList.Join(aliasIdList,
                                          users => users.ForeignId,
                                          aliases => aliases.ForeignId,
                                          (users, aliases) => new
            {
                UserId        = users.UserId,
                PersonAliasId = aliases.PersonAliasId
            }).ToDictionary(t => ( int )t.UserId, t => t.PersonAliasId);
        }
コード例 #11
0
        /// <summary>
        /// Adds the attribute columns.
        /// </summary>
        private void AddDynamicControls()
        {
            // remove Family Campus columns
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <RockLiteralField>()
                     .ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // remove Group member attribute columns
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <AttributeField>().ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // remove Group member assignment columns
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <LinkButtonField>().ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // remove the edit field
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <EditField>().ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // Remove the delete field
            foreach (var column in pnlGroupMembers.Columns
                     .OfType <DeleteField>()
                     .ToList())
            {
                pnlGroupMembers.Columns.Remove(column);
            }

            // Set up group member attribute columns
            var rockContext           = new RockContext();
            var attributeValueService = new AttributeValueService(rockContext);

            foreach (var attribute in GetGroupAttributes())
            {
                // add the attribute data column
                var attributeColumn = pnlGroupMembers.Columns.OfType <AttributeField>().FirstOrDefault(a => a.AttributeId == attribute.Id);
                if (attributeColumn == null)
                {
                    var boundField = new AttributeField
                    {
                        DataField      = attribute.Id + attribute.Key,
                        AttributeId    = attribute.Id,
                        HeaderText     = attribute.Name,
                        SortExpression = string.Format("attribute:{0}", attribute.Id),
                    };

                    boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Center;

                    decimal needsFilled = 0;
                    if (attribute.FieldType != null)
                    {
                        var groupMemberIds  = _group.Members.Select(m => m.Id).ToList();
                        var attributeValues = attributeValueService.GetByAttributeId(attribute.Id)
                                              .Where(v => groupMemberIds.Contains((int)v.EntityId) && !(v.Value == null || v.Value.Trim() == string.Empty))
                                              .Select(v => v.Value).ToList();

                        // if the values are numeric, sum a number value
                        if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.INTEGER.AsGuid()) || attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.DECIMAL.AsGuid()))
                        {
                            needsFilled = attributeValues.Sum(v => v.AsDecimal());
                        }
                        else if (attribute.FieldType.Guid.Equals(Rock.SystemGuid.FieldType.MULTI_SELECT.AsGuid()))
                        {
                            // handles checkboxes and non-empty strings
                            needsFilled = attributeValues.Count(v => !string.IsNullOrWhiteSpace(v));
                        }
                        else
                        {
                            // handles single select and boolean
                            needsFilled = attributeValues.Count(v => v.AsBoolean());
                        }
                    }

                    if (needsFilled > 0)
                    {
                        pnlGroupMembers.ShowFooter = true;
                        boundField.FooterText      = needsFilled.ToString();
                    }

                    pnlGroupMembers.Columns.Add(boundField);
                }

                if (pnlGroupMembers.ShowFooter)
                {
                    pnlGroupMembers.Columns[1].FooterText = "Total";
                    pnlGroupMembers.Columns[1].FooterStyle.HorizontalAlign = HorizontalAlign.Left;
                }
            }

            // Add dynamic assignment columns for volunteer groups
            if (_resources != null && _group.GroupType.GroupTypePurposeValue != null && _group.GroupType.GroupTypePurposeValue.Value == "Serving Area")
            {
                foreach (var groupType in _resourceTypes.Where(gt => gt.GetAttributeValue("AllowVolunteerAssignment").AsBoolean(true)))
                {
                    if (_resources.ContainsKey(groupType.Name))
                    {
                        var resourceGroupGuid = _resources[groupType.Name];
                        if (resourceGroupGuid != null && !string.IsNullOrWhiteSpace(resourceGroupGuid.Value))
                        {
                            var parentGroup = new GroupService(rockContext).Get(resourceGroupGuid.Value.AsGuid());
                            if (parentGroup != null && parentGroup.GroupTypeId != _group.GroupTypeId)
                            {
                                var groupAssignment = new LinkButtonField();
                                groupAssignment.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                                groupAssignment.ExcelExportBehavior       = ExcelExportBehavior.NeverInclude;
                                groupAssignment.HeaderText           = parentGroup.Name;
                                groupAssignment.HeaderStyle.CssClass = "";
                                pnlGroupMembers.Columns.Add(groupAssignment);

                                var assignmentExport = new RockLiteralField();
                                assignmentExport.ID = string.Format("lAssignments_{0}", groupType.Id);
                                assignmentExport.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                                assignmentExport.ExcelExportBehavior       = ExcelExportBehavior.AlwaysInclude;
                                assignmentExport.HeaderStyle.CssClass      = "";
                                assignmentExport.HeaderText = parentGroup.Name;
                                assignmentExport.Visible    = false;
                                pnlGroupMembers.Columns.Add(assignmentExport);
                            }
                        }
                    }
                }
            }

            // Add edit column
            var editField = new EditField();

            pnlGroupMembers.Columns.Add(editField);
            editField.Click += pnlGroupMembers_EditClick;

            // Add delete column
            var deleteField = new DeleteField();

            pnlGroupMembers.Columns.Add(deleteField);
            deleteField.Click += pnlGroupMembers_DeleteClick;
        }
コード例 #12
0
        public void Execute(IJobExecutionContext context)
        {
            var rockContext     = new RockContext();
            var dataMap         = context.JobDetail.JobDataMap;
            var systemEmailGuid = dataMap.GetString("Email").AsGuidOrNull();
            var groupFieldGuid  = dataMap.GetString("RootGroup").AsGuidOrNull();

            string appRoot = GlobalAttributesCache.Read().GetValue("ExternalApplicationRoot");

            if (systemEmailGuid == null)
            {
                throw new Exception("A system email template needs to be set.");
            }
            var systemEmailTemplate = new SystemEmailService(rockContext).Get(systemEmailGuid.Value);

            if (systemEmailTemplate == null)
            {
                throw new Exception("The system email template setting is not a valid system email template.");
            }

            if (groupFieldGuid == null)
            {
                throw new Exception("A group must be specified");
            }

            var groupService  = new GroupService(rockContext);
            var rootGroup     = groupService.GetByGuid(groupFieldGuid.Value);
            var validGroupIds = new List <int> {
                rootGroup.Id
            };

            validGroupIds.AddRange(groupService.GetAllDescendents(rootGroup.Id).Select(g => g.Id));

            // Check to see if we should skip this week
            var definedTypeId = new DefinedTypeService(rockContext).Queryable().FirstOrDefault(dt => dt.Name == "Volunteer Reminder Exclusions")?.Id;

            if (definedTypeId == null)
            {
                context.Result = "Could not get Volunteer Reminder Exclusions defined type";
                return;
            }
            var datesToSkip = new DefinedValueService(rockContext).GetByDefinedTypeId(definedTypeId.Value);

            foreach (var dateToSkipValue in datesToSkip)
            {
                dateToSkipValue.LoadAttributes();
                var date = dateToSkipValue.GetAttributeValue("Date").AsDateTime();
                if (date != null && DatesAreInTheSameWeek(date.Value, RockDateTime.Today))
                {
                    context.Result = "This week should be skipped because of the exclusion " + date.Value.ToString("o");
                    return;
                }
            }


            string weekTeam         = "Team " + Utils.ServingWeek.GetTeamNumber();
            var    attributeService = new AttributeService(rockContext);
            var    attributeIds     =
                attributeService.GetByEntityTypeId(
                    EntityTypeCache.Read(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id).Where(a => a.Key == "AssignedTeam").Select(a => a.Id);
            var attributeValueService = new AttributeValueService(rockContext);
            var groupMemberIds        = new List <int>();

            foreach (int attributeId in attributeIds)
            {
                var attributeValues = attributeValueService.GetByAttributeId(attributeId).AsQueryable().AsNoTracking().Where(av => av.Value.Contains(weekTeam));
                groupMemberIds.AddRange(attributeValues.Where(av => av.EntityId != null).Select(av => av.EntityId.Value));
            }


            var groupMembers = new GroupMemberService(rockContext).GetListByIds(groupMemberIds).Where(gm => validGroupIds.Contains(gm.GroupId)).Distinct();
            int mailedCount  = 0;

            foreach (var groupMember in groupMembers)
            {
                var mergeFields = new Dictionary <string, object>
                {
                    { "GroupMember", groupMember },
                    { "Person", groupMember.Person },
                    { "Group", groupMember.Group }
                };

                var recipients = new List <string> {
                    groupMember.Person.Email
                };

                Email.Send(systemEmailTemplate.From.ResolveMergeFields(mergeFields), systemEmailTemplate.FromName.ResolveMergeFields(mergeFields), systemEmailTemplate.Subject.ResolveMergeFields(mergeFields), recipients, systemEmailTemplate.Body.ResolveMergeFields(mergeFields), appRoot, null, null);
                mailedCount++;
            }
            context.Result = string.Format("{0} reminders were sent ", mailedCount);
        }