public HttpResponseMessage GetEntityGuid(string code)
        {
            RockContext            rockContext            = new RockContext();
            PersonSearchKeyService personSearchKeyService = new PersonSearchKeyService(rockContext);
            var key = personSearchKeyService.Queryable().Where(k => k.SearchValue == code);

            if (!key.Any())
            {
                throw new Exception("Invalid Key");
            }

            var qr = GenerateQR(code);

            if (qr == null)
            {
                throw new Exception("Code Invalid");
            }
            MemoryStream stream = new MemoryStream();

            qr.Save(stream, ImageFormat.Png);
            var buffer   = stream.ToArray();
            var response = Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StreamContent(new MemoryStream(buffer));

            response.Content.Headers.ContentType   = new MediaTypeHeaderValue("image/png");
            response.Content.Headers.ContentLength = stream.Length;

            return(response);
        }
示例#2
0
        /// <summary>
        /// Delete a Person record, and all dependent records.
        /// </summary>
        /// <param name="dataContext"></param>
        /// <param name="personId"></param>
        /// <returns></returns>
        private bool DeletePerson(RockContext dataContext, int personId)
        {
            var personService = new PersonService(dataContext);

            var person = personService.Get(personId);

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

            // Delete Person Views
            var personViewedService = new PersonViewedService(dataContext);

            var personViewedQuery = personViewedService.Queryable()
                                    .Where(x => x.TargetPersonAlias.PersonId == person.Id || x.ViewerPersonAlias.PersonId == person.Id);

            personViewedService.DeleteRange(personViewedQuery);

            // Delete Communications
            var communicationService = new CommunicationService(dataContext);

            var communicationQuery = communicationService.Queryable()
                                     .Where(x => x.SenderPersonAlias.PersonId == person.Id);

            communicationService.DeleteRange(communicationQuery);

            // Delete Communication Recipients
            var recipientsService = new CommunicationRecipientService(dataContext);

            var recipientsQuery = recipientsService.Queryable()
                                  .Where(x => x.PersonAlias.PersonId == person.Id);

            recipientsService.DeleteRange(recipientsQuery);

            // Delete Interactions
            var interactionService = new InteractionService(dataContext);

            var interactionQuery = interactionService.Queryable()
                                   .Where(x => x.PersonAlias.PersonId == person.Id);

            interactionService.DeleteRange(interactionQuery);

            // Delete Person Aliases
            var personAliasService = new PersonAliasService(dataContext);

            personAliasService.DeleteRange(person.Aliases);

            // Delete Person Search Keys
            var personSearchKeyService = new PersonSearchKeyService(dataContext);

            var searchKeys = person.GetPersonSearchKeys(dataContext);

            personSearchKeyService.DeleteRange(searchKeys);

            // Delete Person
            personService.Delete(person);

            return(true);
        }
示例#3
0
        private static object GetSearchKey(Person person, RockContext rockContext)
        {
            var alternateIdSearchTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_ALTERNATE_ID.AsGuid()).Id;
            var searchKey = person.GetPersonSearchKeys(rockContext).Where(k => k.SearchTypeValueId == alternateIdSearchTypeValueId).FirstOrDefault();

            if (searchKey != null)
            {
                return(searchKey.SearchValue);
            }

            //Create Search Key if there is none.
            var             personSearchKeyService = new PersonSearchKeyService(rockContext);
            var             personService          = new PersonService(rockContext);
            var             personAlias            = personService.Get(person.Id).Aliases.First();
            PersonSearchKey personSearchKey        = new PersonSearchKey()
            {
                PersonAlias       = personAlias,
                SearchTypeValueId = alternateIdSearchTypeValueId,
                SearchValue       = PersonSearchKeyService.GenerateRandomAlternateId(true, rockContext)
            };

            personSearchKeyService.Add(personSearchKey);
            rockContext.SaveChanges();
            return(personSearchKey.SearchValue);
        }
示例#4
0
        /// <summary>
        /// If the JWT is valid, the person claimed by that token will be returned. This method uses the configured validation parameters from the
        /// JSON Web Token Configuration Defined Type.
        /// </summary>
        /// <param name="jwtString"></param>
        /// <returns></returns>
        public async static Task <Person> GetPerson(string jwtString)
        {
            if (jwtString.IsNullOrWhiteSpace())
            {
                return(null);
            }

            // Get the configs from the JSON Web Token Configuration defined values
            var configs = GetJwtConfigs();

            if (configs == null)
            {
                return(null);
            }

            // The configs are required to specify a person search key type. The subject of the JWT should match a search key value so that we know
            // which Person the sender of the token claims to be.
            var rockContext            = new RockContext();
            var personSearchKeyService = new PersonSearchKeyService(rockContext);
            var query = personSearchKeyService.Queryable().AsNoTracking();

            // Try each config in order, which are pre-ordered. The SearchTypeValueId is required (if null we couldn't match a person even if the
            // token validates)
            foreach (var config in configs.Where(c => c.SearchTypeValueId.HasValue))
            {
                // If the token is valid, this method will return it as an object that we can pull subject from. Even if the token is valid,
                // if the subject is not set, we cannot match it to a person search key
                var jwt = await ValidateToken(config, jwtString);

                if (jwt == null || jwt.Subject.IsNullOrWhiteSpace())
                {
                    continue;
                }

                // Get all the people (it is possible to get more than one) that have the matching search key
                var people = query
                             .Where(psk => psk.SearchTypeValueId == config.SearchTypeValueId.Value && psk.SearchValue == jwt.Subject)
                             .Select(psk => psk.PersonAlias.Person)
                             .ToList();

                // If there are more than one match, then the Rock admin needs to take action and fix the data as this could be a security hole and we
                // cannot tell which person is the bearer of the JWT
                if (people.Count > 1)
                {
                    ExceptionLogService.LogException($"{people.Count} people matched the JWT subject '{jwt.Subject}' for search value id '{config.SearchTypeValueId.Value}'");
                    continue;
                }

                // If there is a single match, then this method is done and there is no need to check more configurations
                if (people.Count == 1)
                {
                    return(people.Single());
                }
            }

            // None of the configurations was able to validate the token and find a matching person
            return(null);
        }
示例#5
0
        /// <summary>
        /// Adds any missing person alternate ids; limited to 150k records per run
        /// to avoid any possible memory issues. Processes about 150k records
        /// in 52 seconds.
        /// </summary>
        private static void AddMissingAlternateIds()
        {
            using (var personRockContext = new Rock.Data.RockContext())
            {
                var personService          = new PersonService(personRockContext);
                int alternateValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_ALTERNATE_ID.AsGuid()).Id;
                var personSearchKeyService = new PersonSearchKeyService(personRockContext);
                var alternateKeyQuery      = personSearchKeyService.Queryable().AsNoTracking().Where(a => a.SearchTypeValueId == alternateValueId);

                IQueryable <Person> personQuery = personService.Queryable(includeDeceased: true).AsNoTracking();

                // Make a list of items that we're going to bulk insert.
                var itemsToInsert = new List <PersonSearchKey>();

                // Get all existing keys so we can keep track and quickly check them while we're bulk adding new ones.
                var keys = new HashSet <string>(personSearchKeyService.Queryable().AsNoTracking()
                                                .Where(a => a.SearchTypeValueId == alternateValueId)
                                                .Select(a => a.SearchValue)
                                                .ToList());

                string alternateId = string.Empty;

                // Find everyone who does not yet have an alternateKey.
                foreach (var person in personQuery = personQuery
                                                     .Where(p => !alternateKeyQuery.Any(f => f.PersonAlias.PersonId == p.Id))
                                                     .Take(150000))
                {
                    // Regenerate key if it already exists.
                    do
                    {
                        alternateId = PersonSearchKeyService.GenerateRandomAlternateId();
                    } while (keys.Contains(alternateId));

                    keys.Add(alternateId);

                    itemsToInsert.Add(
                        new PersonSearchKey()
                    {
                        PersonAliasId     = person.PrimaryAliasId,
                        SearchTypeValueId = alternateValueId,
                        SearchValue       = alternateId
                    }
                        );
                }

                if (itemsToInsert.Count > 0)
                {
                    // Now add them in one bulk insert.
                    personRockContext.BulkInsert(itemsToInsert);
                }
            }
        }
示例#6
0
        /// <summary>
        /// Delete the test data
        /// </summary>
        private static void DeleteTestData()
        {
            using (var rockContext = new RockContext())
            {
                var stepService = new StepService(rockContext);
                var stepQuery   = stepService.Queryable().Where(s => s.ForeignKey == ForeignKey);
                stepService.DeleteRange(stepQuery);
                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var stepProgramService = new StepProgramService(rockContext);
                var stepProgramQuery   = stepProgramService.Queryable().Where(sp => sp.ForeignKey == ForeignKey);
                stepProgramService.DeleteRange(stepProgramQuery);
                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var personSearchKeyService = new PersonSearchKeyService(rockContext);
                var personSearchKeyQuery   = personSearchKeyService.Queryable()
                                             .Where(psk =>
                                                    psk.PersonAlias.Person.ForeignKey == ForeignKey ||
                                                    PersonGuids.Contains(psk.PersonAlias.Person.Guid));
                personSearchKeyService.DeleteRange(personSearchKeyQuery);
                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var personAliasService = new PersonAliasService(rockContext);
                var personAliasQuery   = personAliasService.Queryable()
                                         .Where(pa =>
                                                pa.Person.ForeignKey == ForeignKey ||
                                                PersonGuids.Contains(pa.Person.Guid));
                personAliasService.DeleteRange(personAliasQuery);
                rockContext.SaveChanges();
            }

            using (var rockContext = new RockContext())
            {
                var personService = new PersonService(rockContext);
                var personQuery   = personService.Queryable()
                                    .Where(p =>
                                           p.ForeignKey == ForeignKey ||
                                           PersonGuids.Contains(p.Guid));
                personService.DeleteRange(personQuery);
                rockContext.SaveChanges();
            }
        }
示例#7
0
        public HttpResponseMessage GetEntityGuid(string code)
        {
            if (code.StartsWith("MCR"))
            {
                var mobileCheckinRecord = MobileCheckinRecordCache.GetByAccessKey(code);
                if (mobileCheckinRecord == null)
                {
                    throw new Exception("Invalid Key");
                }
            }
            else
            {
                //Check to see if is a person's search key
                RockContext            rockContext            = new RockContext();
                PersonSearchKeyService personSearchKeyService = new PersonSearchKeyService(rockContext);
                var key = personSearchKeyService.Queryable().Where(k => k.SearchValue == code);
                if (!key.Any())
                {
                    throw new Exception("Invalid Key");
                }
            }

            var qr = GenerateQR(code);

            if (qr == null)
            {
                throw new Exception("Code Invalid");
            }
            MemoryStream stream = new MemoryStream();

            qr.Save(stream, ImageFormat.Png);
            var buffer   = stream.ToArray();
            var response = Request.CreateResponse(HttpStatusCode.OK);

            response.Content = new StreamContent(new MemoryStream(buffer));

            response.Content.Headers.ContentType   = new MediaTypeHeaderValue("image/png");
            response.Content.Headers.ContentLength = stream.Length;

            return(response);
        }
        /// <summary>
        /// Delete the test data
        /// </summary>
        private static void DeleteTestData()
        {
            var rockContext = new RockContext();

            var stepProgramService = new StepProgramService(rockContext);
            var stepProgramQuery   = stepProgramService.Queryable().Where(sp => sp.ForeignKey == ForeignKey);

            stepProgramService.DeleteRange(stepProgramQuery);
            rockContext.SaveChanges();

            var dataViewFilterService = new DataViewFilterService(rockContext);
            var dvfQuery = dataViewFilterService.Queryable().Where(dvf => dvf.DataView.ForeignKey == ForeignKey || dvf.ForeignKey == ForeignKey);

            dataViewFilterService.DeleteRange(dvfQuery);
            rockContext.SaveChanges();

            var dataViewService = new DataViewService(rockContext);
            var dvQuery         = dataViewService.Queryable().Where(dv => dv.ForeignKey == ForeignKey);

            dataViewService.DeleteRange(dvQuery);
            rockContext.SaveChanges();

            var personSearchKeyService = new PersonSearchKeyService(rockContext);
            var personSearchKeyQuery   = personSearchKeyService.Queryable().Where(psk => psk.PersonAlias.Person.ForeignKey == ForeignKey);

            personSearchKeyService.DeleteRange(personSearchKeyQuery);

            var personAliasService = new PersonAliasService(rockContext);
            var personAliasQuery   = personAliasService.Queryable().Where(pa => pa.Person.ForeignKey == ForeignKey || pa.ForeignKey == ForeignKey);

            personAliasService.DeleteRange(personAliasQuery);
            rockContext.SaveChanges();

            var personService = new PersonService(rockContext);
            var personQuery   = personService.Queryable().Where(p => p.ForeignKey == ForeignKey);

            personService.DeleteRange(personQuery);
            rockContext.SaveChanges();
        }
示例#9
0
        /// <summary>
        /// Saves the family and persons to the database
        /// </summary>
        /// <param name="kioskCampusId">The kiosk campus identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public SaveResult SaveFamilyAndPersonsToDatabase(int?kioskCampusId, RockContext rockContext)
        {
            SaveResult saveResult = new SaveResult();

            FamilyRegistrationState editFamilyState = this;
            var personService             = new PersonService(rockContext);
            var groupService              = new GroupService(rockContext);
            var recordTypePersonId        = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            var maritalStatusMarried      = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid());
            var maritalStatusSingle       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_SINGLE.AsGuid());
            var numberTypeValueMobile     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
            int groupTypeRoleAdultId      = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
            int groupTypeRoleChildId      = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
            int?groupTypeRoleCanCheckInId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid())
                                            ?.Roles.FirstOrDefault(r => r.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN.AsGuid())?.Id;

            bool?groupTypeDefaultSmsEnabled = GroupTypeCache.GetFamilyGroupType().GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED).AsBooleanOrNull();

            Group primaryFamily = null;

            if (editFamilyState.GroupId.HasValue)
            {
                primaryFamily = groupService.Get(editFamilyState.GroupId.Value);
            }

            // see if we can find matches for new people that were added, and also set the primary family if this is a new family, but a matching family was found
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.PersonId.HasValue && !a.IsDeleted))
            {
                var personQuery    = new PersonService.PersonMatchQuery(familyPersonState.FirstName, familyPersonState.LastName, familyPersonState.Email, familyPersonState.MobilePhoneNumber, familyPersonState.Gender, familyPersonState.BirthDate, familyPersonState.SuffixValueId);
                var matchingPerson = personService.FindPerson(personQuery, true);
                if (matchingPerson != null)
                {
                    // newly added person, but a match was found, so set the PersonId, GroupId, and ConnectionStatusValueID to the matching person instead of creating a new person
                    familyPersonState.PersonId                 = matchingPerson.Id;
                    familyPersonState.GroupId                  = matchingPerson.GetFamily(rockContext)?.Id;
                    familyPersonState.RecordStatusValueId      = matchingPerson.RecordStatusValueId;
                    familyPersonState.ConnectionStatusValueId  = matchingPerson.ConnectionStatusValueId;
                    familyPersonState.ConvertedToMatchedPerson = true;
                    if (primaryFamily == null && familyPersonState.IsAdult)
                    {
                        // if this is a new family, but we found a matching adult person, use that person's family as the family
                        primaryFamily = matchingPerson.GetFamily(rockContext);
                    }
                }
            }

            // loop thru all people and add/update as needed
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted))
            {
                Person person;
                if (!familyPersonState.PersonId.HasValue)
                {
                    person = new Person();
                    personService.Add(person);
                    saveResult.NewPersonList.Add(person);
                    person.RecordTypeValueId = recordTypePersonId;
                    person.FirstName         = familyPersonState.FirstName;
                }
                else
                {
                    person = personService.Get(familyPersonState.PersonId.Value);
                }

                // NOTE, Gender, MaritalStatusValueId, NickName, LastName are required fields so, always updated them to match the UI (even if a matched person was found)
                person.Gender = familyPersonState.Gender;
                person.MaritalStatusValueId = familyPersonState.IsMarried ? maritalStatusMarried.Id : maritalStatusSingle.Id;
                person.NickName             = familyPersonState.FirstName;
                person.LastName             = familyPersonState.LastName;

                // if the familyPersonState was converted to a Matched Person, don't overwrite existing values with blank values
                var saveEmptyValues = !familyPersonState.ConvertedToMatchedPerson;

                if (familyPersonState.SuffixValueId.HasValue || saveEmptyValues)
                {
                    person.SuffixValueId = familyPersonState.SuffixValueId;
                }

                if (familyPersonState.BirthDate.HasValue || saveEmptyValues)
                {
                    person.SetBirthDate(familyPersonState.BirthDate);
                }

                if (familyPersonState.DeceasedDate.HasValue || saveEmptyValues)
                {
                    person.DeceasedDate = familyPersonState.DeceasedDate;
                }

                if (familyPersonState.Email.IsNotNullOrWhiteSpace() || saveEmptyValues)
                {
                    person.Email = familyPersonState.Email;
                }

                if (familyPersonState.GradeOffset.HasValue || saveEmptyValues)
                {
                    person.GradeOffset = familyPersonState.GradeOffset;
                }

                // if a matching person was found, the familyPersonState's RecordStatusValueId and ConnectinoStatusValueId was already updated to match the matched person
                person.RecordStatusValueId     = familyPersonState.RecordStatusValueId;
                person.ConnectionStatusValueId = familyPersonState.ConnectionStatusValueId;

                rockContext.SaveChanges();

                bool isNewPerson = !familyPersonState.PersonId.HasValue;
                if (!familyPersonState.PersonId.HasValue)
                {
                    // if we added a new person, we know now the personId after SaveChanges, so set it
                    familyPersonState.PersonId = person.Id;
                }

                if (familyPersonState.AlternateID.IsNotNullOrWhiteSpace())
                {
                    PersonSearchKey        personAlternateValueIdSearchKey;
                    PersonSearchKeyService personSearchKeyService = new PersonSearchKeyService(rockContext);
                    if (isNewPerson)
                    {
                        // if we added a new person, a default AlternateId was probably added in the service layer. If a specific Alternate ID was specified, make sure that their SearchKey is updated
                        personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId).FirstOrDefault();
                    }
                    else
                    {
                        // see if the key already exists. If if it doesn't already exist, let a new one get created
                        personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId && a.SearchValue == familyPersonState.AlternateID).FirstOrDefault();
                    }

                    if (personAlternateValueIdSearchKey == null)
                    {
                        personAlternateValueIdSearchKey = new PersonSearchKey();
                        personAlternateValueIdSearchKey.PersonAliasId     = person.PrimaryAliasId;
                        personAlternateValueIdSearchKey.SearchTypeValueId = _personSearchAlternateValueId;
                        personSearchKeyService.Add(personAlternateValueIdSearchKey);
                    }

                    if (personAlternateValueIdSearchKey.SearchValue != familyPersonState.AlternateID)
                    {
                        personAlternateValueIdSearchKey.SearchValue = familyPersonState.AlternateID;
                        rockContext.SaveChanges();
                    }
                }

                person.LoadAttributes();
                foreach (var attributeValue in familyPersonState.PersonAttributeValuesState)
                {
                    // only set attribute values that are editable so we don't accidently delete any attribute values
                    if (familyPersonState.EditableAttributes.Contains(attributeValue.Value.AttributeId))
                    {
                        if (attributeValue.Value.Value.IsNotNullOrWhiteSpace() || saveEmptyValues)
                        {
                            person.SetAttributeValue(attributeValue.Key, attributeValue.Value.Value);
                        }
                    }
                }

                person.SaveAttributeValues(rockContext);

                if (familyPersonState.MobilePhoneNumber.IsNotNullOrWhiteSpace() || saveEmptyValues)
                {
                    person.UpdatePhoneNumber(numberTypeValueMobile.Id, familyPersonState.MobilePhoneCountryCode, familyPersonState.MobilePhoneNumber, familyPersonState.MobilePhoneSmsEnabled ?? groupTypeDefaultSmsEnabled, false, rockContext);
                }

                rockContext.SaveChanges();
            }

            if (primaryFamily == null)
            {
                // new family and no family found by looking up matching adults, so create a new family
                primaryFamily = new Group();
                var familyLastName = editFamilyState.FamilyPersonListState.OrderBy(a => a.IsAdult).Where(a => !a.IsDeleted).Select(a => a.LastName).FirstOrDefault();
                primaryFamily.Name        = familyLastName + " Family";
                primaryFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

                // Set the Campus to the Campus of this Kiosk
                primaryFamily.CampusId = kioskCampusId;

                groupService.Add(primaryFamily);
                saveResult.NewFamilyList.Add(primaryFamily);
                rockContext.SaveChanges();
            }

            if (!editFamilyState.GroupId.HasValue)
            {
                editFamilyState.GroupId = primaryFamily.Id;
            }

            primaryFamily.LoadAttributes();
            foreach (var familyAttribute in editFamilyState.FamilyAttributeValuesState)
            {
                // only set attribute values that are editable so we don't accidently delete any attribute values
                if (editFamilyState.EditableFamilyAttributes.Contains(familyAttribute.Value.AttributeId))
                {
                    primaryFamily.SetAttributeValue(familyAttribute.Key, familyAttribute.Value.Value);
                }
            }

            primaryFamily.SaveAttributeValues(rockContext);

            var groupMemberService = new GroupMemberService(rockContext);

            // loop thru all people that are part of the same family (in the UI) and ensure they are all in the same primary family (in the database)
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily))
            {
                var currentFamilyMember = primaryFamily.Members.FirstOrDefault(m => m.PersonId == familyPersonState.PersonId.Value);

                if (currentFamilyMember == null)
                {
                    currentFamilyMember = new GroupMember
                    {
                        GroupId           = primaryFamily.Id,
                        PersonId          = familyPersonState.PersonId.Value,
                        GroupMemberStatus = GroupMemberStatus.Active
                    };

                    if (familyPersonState.IsAdult)
                    {
                        currentFamilyMember.GroupRoleId = groupTypeRoleAdultId;
                    }
                    else
                    {
                        currentFamilyMember.GroupRoleId = groupTypeRoleChildId;
                    }

                    groupMemberService.Add(currentFamilyMember);

                    rockContext.SaveChanges();
                }
            }

            // make a dictionary of new related families (by lastname) so we can combine any new related children into a family with the same last name
            Dictionary <string, Group> newRelatedFamilies = new Dictionary <string, Group>(StringComparer.OrdinalIgnoreCase);

            // loop thru all people that are NOT part of the same family
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily == false))
            {
                if (!familyPersonState.GroupId.HasValue)
                {
                    // related person not in a family yet
                    Group relatedFamily = newRelatedFamilies.GetValueOrNull(familyPersonState.LastName);
                    if (relatedFamily == null)
                    {
                        relatedFamily             = new Group();
                        relatedFamily.Name        = familyPersonState.LastName + " Family";
                        relatedFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

                        // Set the Campus to the Campus of this Kiosk
                        relatedFamily.CampusId = kioskCampusId;

                        newRelatedFamilies.Add(familyPersonState.LastName, relatedFamily);
                        groupService.Add(relatedFamily);
                        saveResult.NewFamilyList.Add(relatedFamily);
                    }

                    rockContext.SaveChanges();

                    familyPersonState.GroupId = relatedFamily.Id;

                    var familyMember = new GroupMember
                    {
                        GroupId           = relatedFamily.Id,
                        PersonId          = familyPersonState.PersonId.Value,
                        GroupMemberStatus = GroupMemberStatus.Active
                    };

                    if (familyPersonState.IsAdult)
                    {
                        familyMember.GroupRoleId = groupTypeRoleAdultId;
                    }
                    else
                    {
                        familyMember.GroupRoleId = groupTypeRoleChildId;
                    }

                    groupMemberService.Add(familyMember);
                }

                // ensure there are known relationships between each adult in the primary family to this person that isn't in the primary family
                foreach (var primaryFamilyAdult in editFamilyState.FamilyPersonListState.Where(a => a.IsAdult && a.InPrimaryFamily))
                {
                    groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, familyPersonState.ChildRelationshipToAdult);

                    // if this is something other than the CanCheckIn relationship, but is a relationship that should ensure a CanCheckIn relationship, create a CanCheckinRelationship
                    if (groupTypeRoleCanCheckInId.HasValue && familyPersonState.CanCheckIn && groupTypeRoleCanCheckInId != familyPersonState.ChildRelationshipToAdult)
                    {
                        groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, groupTypeRoleCanCheckInId.Value);
                    }
                }
            }

            return(saveResult);
        }
        private void BindGrid()
        {
            var birthDateCol = gPeople.ColumnsOfType <DateField>().First(c => c.DataField == "BirthDate");
            var ageCol       = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Age");
            var genderCol    = gPeople.ColumnsOfType <RockBoundField>().First(c => c.DataField == "Gender");

            var envelopeNumberField = gPeople.ColumnsOfType <RockLiteralField>().First(c => c.ID == "lEnvelopeNumber");
            var spouseCol           = gPeople.ColumnsOfType <RockTemplateField>().First(c => c.HeaderText == "Spouse");

            var personGivingEnvelopeAttribute = AttributeCache.Get(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER.AsGuid());

            if (personGivingEnvelopeAttribute != null)
            {
                envelopeNumberField.Visible = GlobalAttributesCache.Get().EnableGivingEnvelopeNumber&& this.GetAttributeValue("ShowEnvelopeNumber").AsBoolean();
            }
            else
            {
                envelopeNumberField.Visible = false;
            }

            birthDateCol.Visible = GetAttributeValue("ShowBirthdate").AsBoolean();
            ageCol.Visible       = GetAttributeValue("ShowAge").AsBoolean();
            genderCol.Visible    = GetAttributeValue("ShowGender").AsBoolean();
            spouseCol.Visible    = _showSpouse;

            string type = PageParameter("SearchType");
            string term = PageParameter("SearchTerm");

            if (!string.IsNullOrWhiteSpace(type) && !string.IsNullOrWhiteSpace(term))
            {
                term = term.Trim();
                type = type.Trim();
                var rockContext = new RockContext();

                var personService          = new PersonService(rockContext);
                IQueryable <Person> people = null;

                switch (type.ToLower())
                {
                case ("name"):
                {
                    bool allowFirstNameOnly = false;
                    if (!bool.TryParse(PageParameter("allowFirstNameOnly"), out allowFirstNameOnly))
                    {
                        allowFirstNameOnly = false;
                    }
                    people = personService.GetByFullName(term, allowFirstNameOnly, true);
                    break;
                }

                case ("phone"):
                {
                    var phoneService = new PhoneNumberService(rockContext);
                    var personIds    = phoneService.GetPersonIdsByNumber(term);
                    people = personService.Queryable().Where(p => personIds.Contains(p.Id));
                    break;
                }

                case ("address"):
                {
                    var groupMemberService = new GroupMemberService(rockContext);
                    var personIds2         = groupMemberService.GetPersonIdsByHomeAddress(term);
                    people = personService.Queryable().Where(p => personIds2.Contains(p.Id));
                    break;
                }

                case ("email"):
                {
                    var searchKeyQry = new PersonSearchKeyService(rockContext).Queryable();
                    people = personService.Queryable()
                             .Where(p => (term != "" && p.Email == term) ||
                                    searchKeyQry.Any(a => a.PersonAlias.PersonId == p.Id && a.SearchValue == term));
                    break;
                }

                case ("birthdate"):
                {
                    DateTime?birthDate = Request.QueryString["birthdate"].AsDateTime();
                    int?     personId  = Request.QueryString["person-id"].AsIntegerOrNull();
                    if (birthDate == null)
                    {
                        birthDate = term.AsDateTime();
                    }

                    if (personId.HasValue)
                    {
                        people = personService.Queryable().Where(a => a.Id == personId.Value);
                    }
                    else
                    {
                        people = personService.Queryable().Where(p => p.BirthDate.HasValue && birthDate.HasValue && p.BirthDate == birthDate.Value);
                    }

                    break;
                }
                }

                IEnumerable <int> personIdList = people.Select(p => p.Id);

                // just leave the personIdList as a Queryable if it is over 10000 so that we don't throw a SQL exception due to the big list of ids
                if (people.Count() < 10000)
                {
                    personIdList = personIdList.ToList();
                }

                people = personService.Queryable(true).Where(p => personIdList.Contains(p.Id));

                SortProperty sortProperty = gPeople.SortProperty;
                if (sortProperty != null)
                {
                    people = people.Sort(sortProperty);
                }
                else
                {
                    people = people.OrderBy(p => p.LastName).ThenBy(p => p.FirstName);
                }

                var familyGroupType   = GroupTypeCache.GetFamilyGroupType();
                int familyGroupTypeId = familyGroupType != null ? familyGroupType.Id : 0;

                var groupLocationTypeHome = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
                int homeAddressTypeId     = groupLocationTypeHome != null ? groupLocationTypeHome.Id : 0;

                var personList = people.Select(p => new PersonSearchResult
                {
                    Id         = p.Id,
                    FirstName  = p.FirstName,
                    NickName   = p.NickName,
                    LastName   = p.LastName,
                    BirthDate  = p.BirthDate,
                    BirthYear  = p.BirthYear,
                    BirthMonth = p.BirthMonth,
                    BirthDay   = p.BirthDay,
                    ConnectionStatusValueId = p.ConnectionStatusValueId,
                    RecordStatusValueId     = p.RecordStatusValueId,
                    RecordTypeValueId       = p.RecordTypeValueId,
                    AgeClassification       = p.AgeClassification,
                    SuffixValueId           = p.SuffixValueId,
                    IsDeceased = p.IsDeceased,
                    Email      = p.Email,
                    Gender     = p.Gender,
                    PhotoId    = p.PhotoId,
                    CampusIds  = p.Members
                                 .Where(m =>
                                        m.Group.GroupTypeId == familyGroupTypeId &&
                                        m.Group.CampusId.HasValue)
                                 .Select(m => m.Group.CampusId.Value)
                                 .ToList(),
                    HomeAddresses = p.Members
                                    .Where(m => m.Group.GroupTypeId == familyGroupTypeId)
                                    .SelectMany(m => m.Group.GroupLocations)
                                    .Where(gl => gl.GroupLocationTypeValueId == homeAddressTypeId)
                                    .Select(gl => gl.Location),
                    PhoneNumbers = p.PhoneNumbers
                                   .Where(n => n.NumberTypeValueId.HasValue)
                                   .Select(n => new PersonSearchResultPhone
                    {
                        NumberTypeValueId = n.NumberTypeValueId.Value,
                        Number            = n.NumberFormatted,
                        PhoneTypeName     = n.NumberTypeValue.Value
                    })
                                   .ToList(),
                    TopSignalColor        = p.TopSignalColor,
                    TopSignalIconCssClass = p.TopSignalIconCssClass
                }).ToList();

                if (personList.Count == 1)
                {
                    Response.Redirect(string.Format("~/Person/{0}", personList[0].Id), false);
                    Context.ApplicationInstance.CompleteRequest();
                }
                else
                {
                    if (type.ToLower() == "name")
                    {
                        var similarNames = personService.GetSimilarNames(term,
                                                                         personList.Select(p => p.Id).ToList(), true);
                        if (similarNames.Any())
                        {
                            var hyperlinks = new List <string>();
                            foreach (string name in similarNames.Distinct())
                            {
                                var pageRef = CurrentPageReference;
                                pageRef.Parameters["SearchTerm"] = name;
                                hyperlinks.Add(string.Format("<a href='{0}'>{1}</a>", pageRef.BuildUrl(), name));
                            }
                            string altNames = string.Join(", ", hyperlinks);
                            nbNotice.Text    = string.Format("Other Possible Matches: {0}", altNames);
                            nbNotice.Visible = true;
                        }
                    }

                    _inactiveStatus = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);
                    var personIds = personList.Select(a => a.Id).ToList();

                    if (envelopeNumberField != null && envelopeNumberField.Visible)
                    {
                        _envelopeNumbers = new AttributeValueService(rockContext).Queryable()
                                           .Where(a => a.AttributeId == personGivingEnvelopeAttribute.Id)
                                           .Where(a => personIds.Contains(a.EntityId.Value))
                                           .Select(a => new
                        {
                            PersonId = a.EntityId.Value,
                            Value    = a.Value
                        }).ToList().ToDictionary(k => k.PersonId, v => v.Value);
                    }

                    gPeople.EntityTypeId = EntityTypeCache.GetId <Person>();

                    gPeople.DataSource = personList;
                    gPeople.DataBind();
                }
            }
        }
示例#11
0
        /// <summary>
        /// Finds or Creates the Rock person asynchronously.
        /// </summary>
        /// <param name="lookupContext">The lookup context.</param>
        /// <param name="donation">The donation.</param>
        /// <param name="connectionStatusId">The connection status identifier.</param>
        /// <param name="updatePrimaryEmail">Whether or not this method should update the primary email address on the person.</param>
        /// <returns></returns>
        public static Task <int?> FindPersonAsync(RockContext lookupContext, Donation donation, int connectionStatusId, bool updatePrimaryEmail)
        {
            // specifically using Task.Run instead of Task.Factory.StartNew( longRunning)
            // see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html
            return(Task.Run(() =>
            {
                // look for a single existing person by person fields
                int?primaryAliasId = null;
                var reachSearchKey = string.Format("{0}_{1}", donation.supporter_id, "reach");
                var person = new PersonService(lookupContext).FindPerson(donation.first_name, donation.last_name, donation.email, updatePrimaryEmail, true);
                if (person == null)
                {
                    // check by the search key
                    var existingSearchKey = new PersonSearchKeyService(lookupContext).Queryable().FirstOrDefault(k => k.SearchValue.Equals(reachSearchKey, StringComparison.InvariantCultureIgnoreCase));
                    if (existingSearchKey != null)
                    {
                        primaryAliasId = existingSearchKey.PersonAlias.Person.PrimaryAliasId;
                    }
                    else
                    {
                        // create the person since they don't exist
                        using (var rockContext = new RockContext())
                        {
                            person = new Person
                            {
                                Guid = Guid.NewGuid(),
                                Gender = Gender.Unknown,
                                FirstName = donation.first_name,
                                LastName = donation.last_name,
                                Email = donation.email,
                                IsEmailActive = true,
                                EmailPreference = EmailPreference.EmailAllowed,
                                RecordStatusValueId = recordStatusPendingId,
                                RecordTypeValueId = recordTypePersonId,
                                ConnectionStatusValueId = connectionStatusId,
                                ForeignId = donation.supporter_id
                            };

                            // save so the person alias is attributed for the search key
                            PersonService.SaveNewPerson(person, rockContext);

                            // add the person phone number
                            if (donation.phone.IsNotNullOrWhiteSpace())
                            {
                                person.PhoneNumbers.Add(new PhoneNumber
                                {
                                    Number = donation.phone,
                                    NumberTypeValueId = homePhoneValueId,
                                    Guid = Guid.NewGuid(),
                                    CreatedDateTime = donation.date,
                                    ModifiedDateTime = donation.updated_at
                                });
                            }

                            // add the person address
                            if (donation.address1.IsNotNullOrWhiteSpace())
                            {
                                var familyGroup = person.GetFamily(rockContext);
                                var countryValue = donation.country;
                                var countryDV = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid())
                                                .GetDefinedValueFromValue(countryValue);
                                if (countryDV == null)
                                {
                                    var countriesDT = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid());
                                    countryDV = countriesDT.DefinedValues.FirstOrDefault(dv => dv.Description.Contains(countryValue));
                                    if (countryDV != null && countryDV.Value.IsNotNullOrWhiteSpace())
                                    {
                                        countryValue = countryDV.Value;
                                    }
                                }

                                var location = new LocationService(rockContext).Get(donation.address1, donation.address2, donation.city, donation.state, donation.postal, countryValue);
                                if (familyGroup != null && location != null)
                                {
                                    familyGroup.GroupLocations.Add(new GroupLocation
                                    {
                                        GroupLocationTypeValueId = homeLocationValueId,
                                        LocationId = location.Id,
                                        IsMailingLocation = true,
                                        IsMappedLocation = true
                                    });
                                }
                            }

                            // add the search key
                            new PersonSearchKeyService(rockContext).Add(new PersonSearchKey
                            {
                                SearchTypeValueId = searchKeyValueId,
                                SearchValue = reachSearchKey,
                                PersonAliasId = person.PrimaryAliasId
                            });
                            rockContext.SaveChanges();

                            primaryAliasId = person.PrimaryAliasId;
                        }
                    }
                }
                else
                {
                    primaryAliasId = person.PrimaryAliasId;
                }

                return primaryAliasId;
            }));
        }
        private bool UpdateSearchValueRecords(IJobExecutionContext context, int howManyToConvert, int commandTimeout)
        {
            bool anyRemaining = true;

            int howManyLeft = howManyToConvert;

            var attribute       = AttributeCache.Get("8F528431-A438-4488-8DC3-CA42E66C1B37".AsGuid());
            var searchTypeValue = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_ALTERNATE_ID.AsGuid());

            if (attribute != null && searchTypeValue != null)
            {
                while (howManyLeft > 0)
                {
                    using (var rockContext = new RockContext())
                    {
                        var groupMemberService     = new GroupMemberService(rockContext);
                        var attributeValueService  = new AttributeValueService(rockContext);
                        var personSearchKeyService = new PersonSearchKeyService(rockContext);

                        int take = howManyLeft < 100 ? howManyLeft : 100;

                        var attributeValueRecords = attributeValueService
                                                    .Queryable()
                                                    .Where(v =>
                                                           v.AttributeId == attribute.Id &&
                                                           v.EntityId.HasValue)
                                                    .OrderBy(v => v.Id)
                                                    .Take(take)
                                                    .ToList();

                        anyRemaining = attributeValueRecords.Count >= take;
                        howManyLeft  = anyRemaining ? howManyLeft - take : 0;

                        foreach (var attributevalueRecord in attributeValueRecords)
                        {
                            var hoh = groupMemberService
                                      .Queryable()
                                      .Where(m => m.GroupId == attributevalueRecord.EntityId.Value)
                                      .HeadOfHousehold();

                            if (hoh != null && hoh.PrimaryAlias != null)
                            {
                                var keys = attributevalueRecord.Value.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (var key in keys)
                                {
                                    var searchValue = new PersonSearchKey
                                    {
                                        PersonAliasId     = hoh.PrimaryAlias.Id,
                                        SearchTypeValueId = searchTypeValue.Id,
                                        SearchValue       = key
                                    };
                                    personSearchKeyService.Add(searchValue);
                                }
                            }

                            attributeValueService.Delete(attributevalueRecord);

                            rockContext.SaveChanges();
                        }

                        int numberMigrated  = howManyToConvert - howManyLeft;
                        var percentComplete = howManyToConvert > 0 ? (numberMigrated * 100.0) / howManyToConvert : 100.0;
                        var statusMessage   = $@"Progress: {numberMigrated} of {howManyToConvert} ({Math.Round( percentComplete, 1 )}%) Family Check-in Identifiers migrated to person search key values";
                        context.UpdateLastStatusMessage(statusMessage);

                        rockContext.SaveChanges(disablePrePostProcessing: true);
                    }
                }
            }

            return(anyRemaining);
        }
示例#13
0
 /// <summary>
 /// Handles the Click event of the lbGenerate 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 lbGenerate_Click(object sender, EventArgs e)
 {
     AlternateId = PersonSearchKeyService.GenerateRandomAlternateId(true);
 }
示例#14
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null && checkInState.CheckIn.SearchType != null)
            {
                checkInState.CheckIn.Families = new List <CheckInFamily>();

                if (!string.IsNullOrWhiteSpace(checkInState.CheckIn.SearchValue))
                {
                    var personService = new PersonService(rockContext);
                    var memberService = new GroupMemberService(rockContext);
                    var groupService  = new GroupService(rockContext);

                    int personRecordTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    int familyGroupTypeId  = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;
                    var dvInactive         = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid());

                    IQueryable <int> familyIdQry = null;

                    if (checkInState.CheckIn.SearchType.Guid.Equals(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER.AsGuid()))
                    {
                        string numericPhone = checkInState.CheckIn.SearchValue.AsNumeric();

                        var phoneQry = new PhoneNumberService(rockContext).Queryable().AsNoTracking();
                        if (checkInState.CheckInType == null || checkInState.CheckInType.PhoneSearchType == PhoneSearchType.EndsWith)
                        {
                            char[] charArray = numericPhone.ToCharArray();
                            Array.Reverse(charArray);
                            phoneQry = phoneQry.Where(o =>
                                                      o.NumberReversed.StartsWith(new string( charArray )));
                        }
                        else
                        {
                            phoneQry = phoneQry.Where(o =>
                                                      o.Number.Contains(numericPhone));
                        }

                        var tmpQry = phoneQry.Join(personService.Queryable().AsNoTracking(),
                                                   o => new { PersonId = o.PersonId, IsDeceased = false, RecordTypeValueId = personRecordTypeId },
                                                   p => new { PersonId = p.Id, IsDeceased = p.IsDeceased, RecordTypeValueId = p.RecordTypeValueId.Value },
                                                   (pn, p) => new { Person = p, PhoneNumber = pn })
                                     .Join(memberService.Queryable().AsNoTracking(),
                                           pn => pn.Person.Id,
                                           m => m.PersonId,
                                           (o, m) => new { PersonNumber = o.PhoneNumber, GroupMember = m });

                        familyIdQry = groupService.Queryable().Where(g => tmpQry.Any(o => o.GroupMember.GroupId == g.Id) && g.GroupTypeId == familyGroupTypeId)
                                      .Select(g => g.Id)
                                      .Distinct();
                    }
                    else
                    {
                        var familyMemberQry = memberService
                                              .Queryable().AsNoTracking()
                                              .Where(m =>
                                                     m.Group.GroupTypeId == familyGroupTypeId &&
                                                     m.Person.RecordTypeValueId == personRecordTypeId);

                        if (checkInState.CheckIn.SearchType.Guid.Equals(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_NAME.AsGuid()))
                        {
                            var personIds = personService.GetByFullName(checkInState.CheckIn.SearchValue, false).AsNoTracking().Select(p => p.Id);
                            familyMemberQry = familyMemberQry.Where(f => personIds.Contains(f.PersonId));
                        }
                        else if (checkInState.CheckIn.SearchType.Guid.Equals(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_SCANNED_ID.AsGuid()))
                        {
                            var personIds = new List <int>();

                            var dv = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_ALTERNATE_ID.AsGuid());
                            if (dv != null)
                            {
                                var searchValueService = new PersonSearchKeyService(rockContext);
                                var personAliases      = searchValueService.Queryable().AsNoTracking()
                                                         .Where(v =>
                                                                v.SearchTypeValueId == dv.Id &&
                                                                v.SearchValue == checkInState.CheckIn.SearchValue)
                                                         .Select(v => v.PersonAlias);

                                if (personAliases.Any())
                                {
                                    checkInState.CheckIn.CheckedInByPersonAliasId = personAliases.First().Id;
                                    personIds = personAliases.Select(a => a.PersonId).ToList();
                                }
                            }

                            if (personIds.Any())
                            {
                                familyMemberQry = familyMemberQry.Where(f => personIds.Contains(f.PersonId));
                            }
                            else
                            {
                                // if there were no matches, try to find a family check-in identifier. V8 has a "run once" job that moves the family identifiers
                                // to person search values, but in case the job has not yet completed, will still do the check for family ids.
                                var entityIds = new List <int>();

                                var attributeValueService = new AttributeValueService(rockContext);
                                var attr = AttributeCache.Get("8F528431-A438-4488-8DC3-CA42E66C1B37".AsGuid());
                                if (attr != null)
                                {
                                    entityIds = new AttributeValueService(rockContext)
                                                .Queryable().AsNoTracking()
                                                .Where(v =>
                                                       v.AttributeId == attr.Id &&
                                                       v.EntityId.HasValue &&
                                                       ("|" + v.Value + "|").Contains("|" + checkInState.CheckIn.SearchValue + "|"))
                                                .Select(v => v.EntityId.Value)
                                                .ToList();
                                }

                                familyMemberQry = familyMemberQry.Where(f => entityIds.Contains(f.GroupId));
                            }
                        }
                        else if (checkInState.CheckIn.SearchType.Guid.Equals(SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_FAMILY_ID.AsGuid()))
                        {
                            List <int> searchFamilyIds = checkInState.CheckIn.SearchValue.SplitDelimitedValues().AsIntegerList();
                            familyMemberQry = familyMemberQry.Where(f => searchFamilyIds.Contains(f.GroupId));
                        }
                        else
                        {
                            errorMessages.Add("Invalid Search Type");
                            return(false);
                        }

                        familyIdQry = familyMemberQry
                                      .Select(m => m.GroupId)
                                      .Distinct();
                    }

                    int maxResults = checkInState.CheckInType != null ? checkInState.CheckInType.MaxSearchResults : 100;
                    if (maxResults > 0)
                    {
                        familyIdQry = familyIdQry.Take(maxResults);
                    }

                    var familyIds = familyIdQry.ToList();

                    // Load the family members
                    var familyMembers = memberService
                                        .Queryable("Group,GroupRole,Person").AsNoTracking()
                                        .Where(m => familyIds.Contains(m.GroupId))
                                        .ToList();

                    // Add each family
                    foreach (int familyId in familyIds)
                    {
                        // Get each of the members for this family
                        var familyMemberQry = familyMembers
                                              .Where(m =>
                                                     m.GroupId == familyId &&
                                                     m.Person.NickName != null);

                        if (checkInState.CheckInType != null && checkInState.CheckInType.PreventInactivePeople && dvInactive != null)
                        {
                            familyMemberQry = familyMemberQry
                                              .Where(m =>
                                                     m.Person.RecordStatusValueId != dvInactive.Id);
                        }

                        var thisFamilyMembers = familyMemberQry.ToList();

                        if (thisFamilyMembers.Any())
                        {
                            var group = thisFamilyMembers
                                        .Select(m => m.Group)
                                        .FirstOrDefault();

                            var firstNames = thisFamilyMembers
                                             .OrderBy(m => m.GroupRole.Order)
                                             .ThenBy(m => m.Person.BirthYear)
                                             .ThenBy(m => m.Person.BirthMonth)
                                             .ThenBy(m => m.Person.BirthDay)
                                             .ThenBy(m => m.Person.Gender)
                                             .Select(m => m.Person.NickName)
                                             .ToList();

                            var family = new CheckInFamily();
                            family.Group      = group.Clone(false);
                            family.Caption    = group.ToString();
                            family.SubCaption = firstNames.AsDelimited(", ");
                            checkInState.CheckIn.Families.Add(family);
                        }
                    }
                }

                return(true);
            }

            errorMessages.Add("Invalid Check-in State");
            return(false);
        }
示例#15
0
        private static void CreatePersonWithPrimaryAndPreviousEmails()
        {
            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);

            var person = personService.Get(PersonGuid.PersonWithPrimaryAndPreviousEmailsGuid);

            if (person != null)
            {
                new PersonAliasService(rockContext).DeleteRange(person.Aliases);
                new PersonSearchKeyService(rockContext).DeleteRange(person.GetPersonSearchKeys(rockContext).ToList());
                personService.Delete(person);
                rockContext.SaveChanges();
            }

            person = new Person()
            {
                RecordTypeValueId = DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()),
                FirstName         = "I Have A",
                LastName          = "CommonLastName",
                Guid  = PersonGuid.PersonWithPrimaryAndPreviousEmailsGuid,
                Email = Email.PrimaryEmail
            };

            Group newPersonFamily = PersonService.SaveNewPerson(person, rockContext);

            person = personService.Get(PersonGuid.PersonWithPrimaryAndPreviousEmailsGuid);

            var primaryAliasId = person.PrimaryAliasId;

            var personSearchKeyService = new PersonSearchKeyService(rockContext);
            var searchTypeValue        = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_SEARCH_KEYS_EMAIL.AsGuid());

            PersonSearchKey personSearchKeyPreviousEmail1 = new PersonSearchKey()
            {
                PersonAliasId     = primaryAliasId,
                SearchTypeValueId = searchTypeValue.Id,
                SearchValue       = Email.PreviousEmail1
            };

            personSearchKeyService.Add(personSearchKeyPreviousEmail1);

            PersonSearchKey personSearchKeyPreviousEmail2 = new PersonSearchKey()
            {
                PersonAliasId     = primaryAliasId,
                SearchTypeValueId = searchTypeValue.Id,
                SearchValue       = Email.PreviousEmail2
            };

            personSearchKeyService.Add(personSearchKeyPreviousEmail2);

            PersonSearchKey personSearchKeyPreviousEmail3 = new PersonSearchKey()
            {
                PersonAliasId     = primaryAliasId,
                SearchTypeValueId = searchTypeValue.Id,
                SearchValue       = Email.PreviousEmail3
            };

            personSearchKeyService.Add(personSearchKeyPreviousEmail3);
            rockContext.SaveChanges();
        }
示例#16
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            var    personService = new PersonService(rockContext);
            Person business      = null;

            if (int.Parse(hfBusinessId.Value) != 0)
            {
                business = personService.Get(int.Parse(hfBusinessId.Value));
            }

            if (business == null)
            {
                business = new Person();
                personService.Add(business);
                tbBusinessName.Text = tbBusinessName.Text.FixCase();
            }

            // Business Name
            business.LastName = tbBusinessName.Text;

            // Phone Number
            var businessPhoneTypeId = new DefinedValueService(rockContext).GetByGuid(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK)).Id;

            var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId);

            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
            {
                if (phoneNumber == null)
                {
                    phoneNumber = new PhoneNumber {
                        NumberTypeValueId = businessPhoneTypeId
                    };
                    business.PhoneNumbers.Add(phoneNumber);
                }
                phoneNumber.CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                phoneNumber.Number             = PhoneNumber.CleanNumber(pnbPhone.Number);
                phoneNumber.IsMessagingEnabled = cbSms.Checked;
                phoneNumber.IsUnlisted         = cbUnlisted.Checked;
            }
            else
            {
                if (phoneNumber != null)
                {
                    business.PhoneNumbers.Remove(phoneNumber);
                    new PhoneNumberService(rockContext).Delete(phoneNumber);
                }
            }

            // Record Type - this is always "business". it will never change.
            business.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid()).Id;

            // Record Status
            business.RecordStatusValueId = dvpRecordStatus.SelectedValueAsInt();;

            // Record Status Reason
            int?newRecordStatusReasonId = null;

            if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id)
            {
                newRecordStatusReasonId = dvpReason.SelectedValueAsInt();
            }
            business.RecordStatusReasonValueId = newRecordStatusReasonId;

            // Email
            business.IsEmailActive   = true;
            business.Email           = tbEmail.Text.Trim();
            business.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

            avcEditAttributes.GetEditValues(business);

            if (!business.IsValid)
            {
                // Controls will render the error messages
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();

                // Add/Update Family Group
                var familyGroupType = GroupTypeCache.GetFamilyGroupType();
                int adultRoleId     = familyGroupType.Roles
                                      .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()))
                                      .Select(r => r.Id)
                                      .FirstOrDefault();
                var adultFamilyMember = UpdateGroupMember(business.Id, familyGroupType, business.LastName + " Business", ddlCampus.SelectedValueAsInt(), adultRoleId, rockContext);
                business.GivingGroup  = adultFamilyMember.Group;

                // Add/Update Known Relationship Group Type
                var knownRelationshipGroupType   = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                int knownRelationshipOwnerRoleId = knownRelationshipGroupType.Roles
                                                   .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                                   .Select(r => r.Id)
                                                   .FirstOrDefault();
                var knownRelationshipOwner = UpdateGroupMember(business.Id, knownRelationshipGroupType, "Known Relationship", null, knownRelationshipOwnerRoleId, rockContext);

                // Add/Update Implied Relationship Group Type
                var impliedRelationshipGroupType   = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK.AsGuid());
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                                                     .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid()))
                                                     .Select(r => r.Id)
                                                     .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext);

                rockContext.SaveChanges();

                // Location
                int workLocationTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK).Id;

                var groupLocationService = new GroupLocationService(rockContext);
                var workLocation         = groupLocationService.Queryable("Location")
                                           .Where(gl =>
                                                  gl.GroupId == adultFamilyMember.Group.Id &&
                                                  gl.GroupLocationTypeValueId == workLocationTypeId)
                                           .FirstOrDefault();

                if (string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    if (workLocation != null)
                    {
                        if (cbSaveFormerAddressAsPreviousAddress.Checked)
                        {
                            GroupLocationHistorical.CreateCurrentRowFromGroupLocation(workLocation, RockDateTime.Now);
                        }

                        groupLocationService.Delete(workLocation);
                    }
                }
                else
                {
                    var newLocation = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                    if (workLocation == null)
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    else
                    {
                        // Save this to history if the box is checked and the new info is different than the current one.
                        if (cbSaveFormerAddressAsPreviousAddress.Checked && newLocation.Id != workLocation.Location.Id)
                        {
                            new GroupLocationHistoricalService(rockContext).Add(GroupLocationHistorical.CreateCurrentRowFromGroupLocation(workLocation, RockDateTime.Now));
                        }
                    }

                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;
                }

                rockContext.SaveChanges();

                hfBusinessId.Value = business.Id.ToString();
            });

            /* Ethan Drotning 2022-01-11
             * Need save the PersonSearchKeys outside of the transaction since the DB might not have READ_COMMITTED_SNAPSHOT enabled.
             */

            // PersonSearchKey
            var personSearchKeyService = new PersonSearchKeyService(rockContext);
            var validSearchTypes       = GetValidSearchKeyTypes();
            var databaseSearchKeys     = personSearchKeyService.Queryable().Where(a => a.PersonAlias.PersonId == business.Id && validSearchTypes.Contains(a.SearchTypeValue.Guid)).ToList();

            foreach (var deletedSearchKey in databaseSearchKeys.Where(a => !PersonSearchKeysState.Any(p => p.Guid == a.Guid)))
            {
                personSearchKeyService.Delete(deletedSearchKey);
            }

            foreach (var personSearchKey in PersonSearchKeysState.Where(a => !databaseSearchKeys.Any(d => d.Guid == a.Guid)))
            {
                personSearchKey.PersonAliasId = business.PrimaryAliasId.Value;
                personSearchKeyService.Add(personSearchKey);
            }

            rockContext.SaveChanges();

            business.SaveAttributeValues();

            var queryParams = new Dictionary <string, string>
            {
                { "BusinessId", hfBusinessId.Value }
            };

            NavigateToCurrentPage(queryParams);
        }