private Group SaveNewPerson(Rock.Model.Person person, Group existingFamily, int?defaultCampus, RockContext rockContext)
        {
            if (existingFamily == null)
            {
                return(PersonService.SaveNewPerson(person, rockContext, (defaultCampus != null ? defaultCampus : ( int? )null), false));
            }
            else
            {
                person.FirstName  = person.FirstName.FixCase();
                person.NickName   = person.NickName.FixCase();
                person.MiddleName = person.MiddleName.FixCase();
                person.LastName   = person.LastName.FixCase();

                // Create/Save Known Relationship Group
                var knownRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS);
                if (knownRelationshipGroupType != null)
                {
                    var ownerRole = knownRelationshipGroupType.Roles
                                    .FirstOrDefault(r =>
                                                    r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()));
                    if (ownerRole != null)
                    {
                        var groupMember = new GroupMember();
                        groupMember.Person      = person;
                        groupMember.GroupRoleId = ownerRole.Id;

                        var group = new Group();
                        group.Name        = knownRelationshipGroupType.Name;
                        group.GroupTypeId = knownRelationshipGroupType.Id;
                        group.Members.Add(groupMember);

                        var groupService = new GroupService(rockContext);
                        groupService.Add(group);
                    }
                }

                // Create/Save Implied Relationship Group
                var impliedRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK);
                if (impliedRelationshipGroupType != null)
                {
                    var ownerRole = impliedRelationshipGroupType.Roles
                                    .FirstOrDefault(r =>
                                                    r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid()));
                    if (ownerRole != null)
                    {
                        var groupMember = new GroupMember();
                        groupMember.Person      = person;
                        groupMember.GroupRoleId = ownerRole.Id;

                        var group = new Group();
                        group.Name        = impliedRelationshipGroupType.Name;
                        group.GroupTypeId = impliedRelationshipGroupType.Id;
                        group.Members.Add(groupMember);

                        var groupService = new GroupService(rockContext);
                        groupService.Add(group);
                    }
                }
                var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);

                var adultRole = familyGroupType?.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()));

                var childRole = familyGroupType?.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()));

                var age = person.Age;

                var familyRole = age.HasValue && age < 18 ? childRole : adultRole;

                // Add to the existing family
                PersonService.AddPersonToFamily(person, true, existingFamily.Id, familyRole.Id, rockContext);
                return(existingFamily);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Handles the Click event of the btnSave 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 btnSave_Click(object sender, EventArgs e)
        {
            if (GetAttributeValue(AttributeKeys.DisplayTerms).AsBoolean() && !cbTOS.Checked)
            {
                nbTOS.Visible = true;
                return;
            }

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

            var person = GetPerson(personService);

            var personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));

            if (person.Id != 0)
            {
                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };


                if (person.PhotoId != imgPhoto.BinaryFileId)
                {
                    changeRequest.EvaluatePropertyChange(person, "PhotoId", imgPhoto.BinaryFileId);
                    if (person.Photo != null)
                    {
                        changeRequest.EvaluatePropertyChange(person.Photo, "IsTemporary", true, true);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
                changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
                changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
                var lastNameRecord = changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);

                //Store the person's old last name as a previous name
                if (lastNameRecord != null)
                {
                    changeRequest.AddEntity(new PersonPreviousName
                    {
                        LastName                = person.LastName,
                        PersonAliasId           = person.PrimaryAliasId ?? 0,
                        CreatedByPersonAliasId  = CurrentPersonAliasId,
                        ModifiedByPersonAliasId = CurrentPersonAliasId
                    },
                                            rockContext,
                                            true);
                }

                changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

                var birthMonth = person.BirthMonth;
                var birthDay   = person.BirthDay;
                var birthYear  = person.BirthYear;

                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                    changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                    }
                    else
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", ( int? )null);
                    }
                }

                if (ddlGradePicker.Visible)
                {
                    changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);
                }
                changeRequest.EvaluatePropertyChange(person, "Gender", rblGender.SelectedValue.ConvertToEnum <Gender>());

                var primaryFamilyMembers = person.GetFamilyMembers(true).Where(m => m.PersonId == person.Id).ToList();
                foreach (var member in primaryFamilyMembers)
                {
                    changeRequest.EvaluatePropertyChange(member, "GroupRoleId", rblRole.SelectedValue.AsInteger(), true);
                }

                var primaryFamily       = person.GetFamily(rockContext);
                var familyChangeRequest = new ChangeRequest
                {
                    EntityTypeId     = EntityTypeCache.Get(typeof(Group)).Id,
                    EntityId         = primaryFamily.Id,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };

                // update campus
                bool showCampus = GetAttributeValue("ShowCampusSelector").AsBoolean();
                if (showCampus)
                {
                    // Only update campus for adults
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    var adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
                    var adultRole = groupTypeRoleService.Get(adultGuid);
                    if (rblRole.SelectedValue.AsInteger() == adultRole.Id)
                    {
                        familyChangeRequest.EvaluatePropertyChange(primaryFamily, "CampusId", cpCampus.SelectedCampusId);
                    }
                }

                //Evaluate PhoneNumbers
                bool showPhoneNumbers = GetAttributeValue("ShowPhoneNumbers").AsBoolean();
                if (showPhoneNumbers)
                {
                    var phoneNumberTypeIds        = new List <int>();
                    var phoneNumbersScreen        = new List <PhoneNumber>();
                    var visiblePhoneNumberTypeIds = new List <int>();

                    var visiblePhoneNumberTypeGuids = GetAttributeValue("PhoneTypes").SplitDelimitedValues().AsGuidList();

                    foreach (var phoneTypeGuid in visiblePhoneNumberTypeGuids)
                    {
                        visiblePhoneNumberTypeIds.Add(DefinedValueCache.Get(phoneTypeGuid).Id);
                    }

                    bool smsSelected = false;
                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null)
                        {
                            int phoneNumberTypeId;
                            if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                            {
                                var    phoneNumberList = person.PhoneNumbers.Where(n => n.NumberTypeValueId == phoneNumberTypeId).ToList();
                                var    phoneNumber     = phoneNumberList.FirstOrDefault(pn => pn.Number == PhoneNumber.CleanNumber(pnbPhone.Number));
                                string oldPhoneNumber  = string.Empty;

                                if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                                {
                                    phoneNumber = new PhoneNumber
                                    {
                                        PersonId           = person.Id,
                                        NumberTypeValueId  = phoneNumberTypeId,
                                        CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                        IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                        Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                                    };
                                    var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                                    changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                                else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                                {
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                            }
                        }
                    }
                    //Remove old phone numbers or changed
                    var phoneNumbersToRemove = person.PhoneNumbers
                                               .Where(n => visiblePhoneNumberTypeIds.Contains(n.NumberTypeValueId ?? -1))
                                               .Where(n => !phoneNumbersScreen.Any(n2 => n2.Number == n.Number && n2.NumberTypeValueId == n.NumberTypeValueId)).ToList();

                    foreach (var number in phoneNumbersToRemove)
                    {
                        var phoneComment = string.Format("{0}: {1}.", number.NumberTypeValue.Value, number.NumberFormatted);
                        changeRequest.DeleteEntity(number, true, phoneComment);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text.Trim());
                changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
                changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());

                // if they used the ImageEditor, and cropped it, the non-cropped file is still in BinaryFile. So clean it up
                if (imgPhoto.CropBinaryFileId.HasValue)
                {
                    if (imgPhoto.CropBinaryFileId != person.PhotoId)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value);
                        if (binaryFile != null && binaryFile.IsTemporary)
                        {
                            string errorMessage;
                            if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                            {
                                binaryFileService.Delete(binaryFile);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }


                // save family information
                if (pnlAddress.Visible)
                {
                    var      currentLocation = person.GetHomeLocation();
                    Location location        = new Location
                    {
                        Street1    = acAddress.Street1,
                        Street2    = acAddress.Street2,
                        City       = acAddress.City,
                        State      = acAddress.State,
                        PostalCode = acAddress.PostalCode,
                    };
                    var globalAttributesCache = GlobalAttributesCache.Get();
                    location.Country = globalAttributesCache.OrganizationCountry;
                    location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

                    if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                        (currentLocation != null && currentLocation.Street1 != location.Street1))
                    {
                        LocationService locationService = new LocationService(rockContext);
                        locationService.Add(location);
                        rockContext.SaveChanges();

                        var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                        var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                        GroupLocation groupLocation = new GroupLocation
                        {
                            CreatedByPersonAliasId  = CurrentPersonAliasId,
                            ModifiedByPersonAliasId = CurrentPersonAliasId,
                            GroupId    = primaryFamily.Id,
                            LocationId = location.Id,
                            GroupLocationTypeValueId = homeLocationType.Id,
                            IsMailingLocation        = true,
                            IsMappedLocation         = true
                        };

                        var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                        var homelocations = primaryFamily.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                        foreach (var homelocation in homelocations)
                        {
                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "GroupLocationTypeValue",
                                previousLocationType,
                                true,
                                homelocation.Location.ToString());

                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "IsMailingLocation",
                                false,
                                true,
                                homelocation.Location.ToString());
                        }
                    }
                }

                // Handle both Child and Adult attributes together here
                var attributeGuids = GetAttributeValue(AttributeKeys.PersonAttributesAdult).SplitDelimitedValues().AsGuidList();
                attributeGuids.AddRange(GetAttributeValue(AttributeKeys.PersonAttributesChild).SplitDelimitedValues().AsGuidList());
                if (attributeGuids.Count > 0)
                {
                    person.LoadAttributes();
                    Helper.GetEditValues(phAttributes, person);
                    changeRequest.EvaluateAttributes(person);
                }

                List <string> errors;

                if (changeRequest.ChangeRecords.Any() ||
                    (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
                {
                    changeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(changeRequest);
                    rockContext.SaveChanges();

                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                if (familyChangeRequest.ChangeRecords.Any())
                {
                    familyChangeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(familyChangeRequest);
                    rockContext.SaveChanges();
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
            }
            else
            {
                var primaryFamily = CurrentPerson.GetFamily(rockContext);

                person.PhotoId = imgPhoto.BinaryFileId;

                if (imgPhoto.BinaryFileId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                    var binaryFile = binaryFileService.Get(imgPhoto.BinaryFileId.Value);
                    binaryFile.IsTemporary = false;
                }

                person.FirstName     = tbFirstName.Text;
                person.NickName      = tbNickName.Text;
                person.LastName      = tbLastName.Text;
                person.TitleValueId  = ddlTitle.SelectedValue.AsIntegerOrNull();
                person.SuffixValueId = ddlSuffix.SelectedValue.AsIntegerOrNull();
                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    person.BirthMonth = birthday.Value.Month;
                    person.BirthDay   = birthday.Value.Day;

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        person.BirthYear = birthday.Value.Year;
                    }
                    else
                    {
                        person.BirthYear = null;
                    }
                }

                person.Gender          = rblGender.SelectedValue.ConvertToEnum <Gender>();
                person.Email           = tbEmail.Text;
                person.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

                if (ddlGradePicker.Visible)
                {
                    person.GraduationYear = ypGraduation.SelectedYear;
                }


                GroupMember groupMember = new GroupMember
                {
                    PersonId    = person.Id,
                    GroupId     = primaryFamily.Id,
                    GroupRoleId = rblRole.SelectedValue.AsInteger()
                };

                PersonService.AddPersonToFamily(person, true, primaryFamily.Id, rblRole.SelectedValue.AsInteger(), rockContext);

                PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);

                foreach (RepeaterItem item in rContactInfo.Items)
                {
                    HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                    PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                    CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                    CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                    if (hfPhoneType != null &&
                        pnbPhone != null &&
                        cbSms != null &&
                        cbUnlisted != null &&
                        pnbPhone.Number.IsNotNullOrWhiteSpace())
                    {
                        int phoneNumberTypeId;
                        if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                        {
                            var phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            phoneNumberService.Add(phoneNumber);
                        }
                    }
                }
                rockContext.SaveChanges();

                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0,
                    RequestorComment = "Added as new person from My Account."
                };

                if (tbComments.Text.IsNotNullOrWhiteSpace())
                {
                    changeRequest.RequestorComment += "<br><br>Comment: " + tbComments.Text;
                }

                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();

                List <string> errors;
                changeRequest.CompleteChanges(rockContext, out errors);
            }

            NavigateToParentPage();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // get the Attribute.Guid for this workflow' AddToFamilyWiths Person Attribute so that we can lookup the value
            var    guidAddToFamilyPersonAttribute = GetAttributeValue(action, AttributeKey.AddToFamilyWith).AsGuid();
            Person addToFamilyWithPerson          = GetPersonFromWorkflowAttribute(rockContext, action, guidAddToFamilyPersonAttribute);

            if (addToFamilyWithPerson == null)
            {
                errorMessages.Add(string.Format("Add To Family With Person could not be found for selected value ('{0}')!", guidAddToFamilyPersonAttribute.ToString()));
            }

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var    guidPersonAttribute = GetAttributeValue(action, AttributeKey.Person).AsGuid();
            Person person = GetPersonFromWorkflowAttribute(rockContext, action, guidPersonAttribute);

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", person.ToString()));
            }

            bool removePersonFromCurrentFamily = GetRemovePersonFromCurrentFamilyValue(action);


            Guid familyRoleGuid = GetAttributeValue(action, AttributeKey.FamilyRole).AsGuid();
            var  familyRoles    = GroupTypeCache.Get(SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Roles;

            if (!familyRoles.Any(a => a.Guid == familyRoleGuid))
            {
                var workflowAttributeValue = action.GetWorkflowAttributeValue(familyRoleGuid);

                if (workflowAttributeValue != null)
                {
                    familyRoleGuid = workflowAttributeValue.AsGuid();
                }
            }

            if (!familyRoles.Any(a => a.Guid == familyRoleGuid))
            {
                errorMessages.Add(string.Format("Family Role could not be found for selected value ('{0}')!", familyRoleGuid.ToString()));
            }

            // Add Person to Group
            if (!errorMessages.Any())
            {
                // Determine which family to add the person to
                Group family     = addToFamilyWithPerson.GetFamily(rockContext);
                var   familyRole = familyRoles.First(a => a.Guid == familyRoleGuid);

                // Check if
                if (!family.Members
                    .Any(m =>
                         m.PersonId == person.Id))
                {
                    PersonService.AddPersonToFamily(person, false, family.Id, familyRole.Id, rockContext);
                    if (removePersonFromCurrentFamily)
                    {
                        PersonService.RemovePersonFromOtherFamilies(family.Id, person.Id, rockContext);
                    }
                }
                else
                {
                    action.AddLogEntry($"{person.FullName} was already a member of the family.", true);
                }
            }

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

            return(true);
        }
Ejemplo n.º 4
0
    private void processRegistration()
    {
        // Setup the Rock context
        var rockContext = new RockContext();

        List <Child>  children       = ((List <Child>)ViewState["Children"]);
        PersonService personService  = new PersonService(rockContext);
        var           matchingPeople = personService.GetByMatch(tbFirstname.Text, tbLastName.Text, dpBirthday.SelectedDate, ebEmail.Text, pnbPhone.Text, acAddress.Street1, acAddress.PostalCode);
        bool          match          = matchingPeople.Count() == 1;

        if (match && !string.IsNullOrWhiteSpace(tbFirstName2.Text))
        {
            var matchingPeople2 = personService.GetByMatch(tbFirstName2.Text, tbLastName2.Text, dpBirthday2.SelectedDate, ebEmail2.Text, pnbPhone2.Text, acAddress.Street1, acAddress.PostalCode);
            match = matchingPeople.Count() == 1;
        }

        // If we get exactly one match given the specificity of the search criteria this is probably a safe bet
        if (match)
        {
            bool updated = false;
            // See if the family member already exists
            foreach (Child child in children)
            {
                foreach (GroupMember gm in matchingPeople.FirstOrDefault().GetFamilyMembers())
                {
                    if (gm.Person.BirthDate == child.DateOfBirth && gm.Person.FirstName == child.FirstName)
                    {
                        child.SaveAttributes(gm.Person);
                        updated = true;
                        break;
                    }
                }
                if (!updated)
                {
                    // If we get here, it's time to create a new family member
                    var newChild = child.SaveAsPerson(matchingPeople.FirstOrDefault().GetFamily().Id, rockContext);
                }
            }
            rockContext.SaveChanges();

            var personWorkflowGuid = GetAttributeValue("PersonWorkflow");
            if (!string.IsNullOrWhiteSpace(personWorkflowGuid))
            {
                matchingPeople.FirstOrDefault().PrimaryAlias.LaunchWorkflow(new Guid(personWorkflowGuid), matchingPeople.FirstOrDefault().ToString() + " Pre-Registration", new Dictionary <string, string>()
                {
                    { "ExtraInformation", tbExtraInformation.Text }
                });
            }
        }
        else
        {
            DefinedValueCache homePhone = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME);

            // Create the adult
            Person adult = new Person();
            adult.FirstName               = tbFirstname.Text;
            adult.LastName                = tbLastName.Text;
            adult.BirthDay                = dpBirthday.SelectedDate.Value.Day;
            adult.BirthMonth              = dpBirthday.SelectedDate.Value.Month;
            adult.BirthYear               = dpBirthday.SelectedDate.Value.Year;
            adult.RecordTypeValueId       = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            adult.ConnectionStatusValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_WEB_PROSPECT.AsGuid()).Id;
            adult.RecordStatusValueId     = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
            adult.UpdatePhoneNumber(homePhone.Id, pnbPhone.CountryCode, pnbPhone.Number, false, false, rockContext);
            adult.Email = ebEmail.Text;

            Group family = PersonService.SaveNewPerson(adult, rockContext, cpCampus.SelectedCampusId);

            if (!string.IsNullOrWhiteSpace(tbFirstName2.Text))
            {
                Person adult2 = new Person();
                adult2.FirstName               = tbFirstName2.Text;
                adult2.LastName                = tbLastName2.Text;
                adult2.BirthDay                = dpBirthday2.SelectedDate.Value.Day;
                adult2.BirthMonth              = dpBirthday2.SelectedDate.Value.Month;
                adult2.BirthYear               = dpBirthday2.SelectedDate.Value.Year;
                adult2.RecordTypeValueId       = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                adult2.ConnectionStatusValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_WEB_PROSPECT.AsGuid()).Id;
                adult2.RecordStatusValueId     = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                adult2.UpdatePhoneNumber(homePhone.Id, pnbPhone2.CountryCode, pnbPhone2.Number, false, false, rockContext);
                adult2.Email = ebEmail2.Text;

                PersonService.AddPersonToFamily(adult2, true, family.Id, 3, rockContext);
            }

            // Now create all the children
            foreach (Child child in children)
            {
                child.SaveAsPerson(family.Id, rockContext);
            }

            rockContext.SaveChanges();
            var personWorkflowGuid = GetAttributeValue("PersonWorkflow");
            if (!string.IsNullOrWhiteSpace(personWorkflowGuid))
            {
                adult.PrimaryAlias.LaunchWorkflow(new Guid(GetAttributeValue("PersonWorkflow")), adult.ToString() + " Pre-Registration", new Dictionary <string, string>()
                {
                    { "ExtraInformation", tbExtraInformation.Text }
                });
            }
        }
    }
Ejemplo n.º 5
0
        public static Person CreatePersonFromMember(Member member, DefinedValueCache defaultConnectionValue)
        {
            Person person = null;

            RockContext     rockContext     = new RockContext();
            PersonService   personService   = new PersonService(rockContext);
            LocationService locationService = new LocationService(rockContext);

            var email = string.IsNullOrEmpty(member.email) ? String.Empty : member.email.Trim();

            if (email != String.Empty)
            {
                if (!email.IsValidEmail())
                {
                    email = String.Empty;
                }
            }

            var matches = personService.GetByMatch(
                member.firstName.Trim(),
                member.lastName.Trim(),
                member.birthDate,
                email, null,
                member.address1,
                member.zipCode);

            Location location = new Location()
            {
                Street1    = member.address1,
                Street2    = member.address2,
                City       = member.city,
                State      = member.state,
                PostalCode = member.zipCode,
                Country    = member.country ?? "US"
            };

            if (matches.Count() > 1)
            {
                // Find the oldest member record in the list
                person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault();

                if (person == null)
                {
                    // Find the oldest attendee record in the list
                    person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault();
                    if (person == null)
                    {
                        person = matches.OrderBy(p => p.Id).First();
                    }
                }
            }
            else if (matches.Count() == 1)
            {
                person = matches.First();
            }
            else
            {
                // Create the person
                person           = new Person();
                person.FirstName = member.firstName.Trim();
                person.LastName  = member.lastName.Trim();

                if (member.birthDate.HasValue)
                {
                    person.SetBirthDate(member.birthDate.Value);
                }

                if (email.IsNotNullOrWhiteSpace())
                {
                    person.Email = email;
                }

                person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                person.ConnectionStatusValueId = defaultConnectionValue.Id;
                person.RecordStatusValueId     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                person.IsSystem   = false;
                person.IsDeceased = false;
                var gender = member.gender;

                if (!String.IsNullOrEmpty(gender))
                {
                    gender.Trim();

                    if (gender == "Male" || gender == "male")
                    {
                        person.Gender = Gender.Male;
                    }
                    else if (gender == "Female" || gender == "female")
                    {
                        person.Gender = Gender.Female;
                    }
                    else
                    {
                        person.Gender = Gender.Unknown;
                    }
                }
                else
                {
                    person.Gender = Gender.Unknown;
                }

                locationService.Verify(location, true);
                bool existingFamily = false;

                var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);
                var adultRole       = familyGroupType.Roles
                                      .FirstOrDefault(r =>
                                                      r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()));

                var childRole = familyGroupType.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()));

                //Look for the family by groupId
                var familyFromAttribute = LeagueAppsHelper.GetFamilyByApiId(member.groupId);
                if (familyFromAttribute != null)
                {
                    var familyRole = person.Age.HasValue && person.Age < 18 ? childRole : adultRole;
                    PersonService.AddPersonToFamily(person, true, familyFromAttribute.Id, familyRole.Id, rockContext);
                    existingFamily = true;
                }


                if (!existingFamily && !string.IsNullOrWhiteSpace(member.address1))
                {
                    // See if we can find an existing family using the location where everyone is a web prospect
                    var matchingLocations = locationService.Queryable().Where(l => l.Street1 == location.Street1 && l.PostalCode == location.PostalCode);
                    var matchingFamilies  = matchingLocations.Where(l => l.GroupLocations.Any(gl => gl.Group.GroupTypeId == familyGroupType.Id)).SelectMany(l => l.GroupLocations).Select(gl => gl.Group);
                    var matchingFamily    = matchingFamilies.Where(f => f.Members.All(m => m.Person.ConnectionStatusValueId == defaultConnectionValue.Id) && f.Name == member.lastName + " Family");
                    if (matchingFamily.Count() == 1)
                    {
                        var familyRole = person.Age.HasValue && person.Age < 18 ? childRole : adultRole;
                        PersonService.AddPersonToFamily(person, true, matchingFamily.FirstOrDefault().Id, familyRole.Id, rockContext);
                        existingFamily = true;
                    }
                }

                if (!existingFamily)
                {
                    Group         family        = PersonService.SaveNewPerson(person, rockContext);
                    GroupLocation groupLocation = new GroupLocation();
                    groupLocation.GroupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                    groupLocation.Location         = location;
                    groupLocation.IsMappedLocation = true;
                    family.CampusId = CampusCache.All().FirstOrDefault().Id;
                    family.GroupLocations.Add(groupLocation);
                    family.LoadAttributes();
                    family.SetAttributeValue(Constants.LeagueAppsFamilyId, member.groupId);
                    family.SaveAttributeValues();
                }

                rockContext.SaveChanges();
            }


            var groupLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME);

            // Check to see if the address/location should be updated.
            if (member.dateJoined > person.GetFamilies().SelectMany(f => f.GroupLocations).Where(gl => gl.GroupLocationTypeValueId == groupLocationType.Id).Max(gl => gl.CreatedDateTime ?? gl.Location.CreatedDateTime))
            {
                if (!location.StandardizedDateTime.HasValue)
                {
                    locationService.Verify(location, true);
                }
                var allLocations = person.GetFamilies().SelectMany(f => f.GroupLocations);
                if (location.Street1 != null && location.StandardizedDateTime != null && !allLocations.Any(hl => hl.Location.Street1 == location.Street1) && !location.Street1.Contains("PO Box") && !location.Street1.Contains("PMB"))
                {
                    locationService.Add(location);
                    rockContext.SaveChanges();


                    // Get all existing addresses of the specified type
                    var groupLocations = person.GetFamily().GroupLocations.Where(l => l.GroupLocationTypeValueId == groupLocationType.Id).ToList();

                    // Create a new address of the specified type, saving all existing addresses of that type as Previous Addresses
                    // Use the Is Mailing and Is Mapped values from any of the existing addresses of that type have those values set to true
                    GroupService.AddNewGroupAddress(rockContext, person.GetFamily(),
                                                    groupLocationType.Guid.ToString(), location.Id, true,
                                                    "LeagueApps Import Data Job",
                                                    groupLocations.Any(x => x.IsMailingLocation),
                                                    groupLocations.Any(x => x.IsMappedLocation));
                }
            }

            // Update the person's LeagueApps User ID attribute
            person.LoadAttributes();
            var attributevaluelist = person.GetAttributeValue(Constants.LeagueAppsUserId).SplitDelimitedValues().ToList();

            if (!attributevaluelist.Contains(member.userId.ToString()))
            {
                attributevaluelist.Add(member.userId.ToString());
                person.SetAttributeValue(Constants.LeagueAppsUserId, string.Join("|", attributevaluelist) + "|");
                person.SaveAttributeValues();
            }

            return(person);
        }
Ejemplo n.º 6
0
        /// <summary>Process all leagues (programs) from LeagueApps.</summary>
        /// <param name="message">The message that is returned depending on the result.</param>
        /// <param name="state">The state of the process.</param>
        /// <returns><see cref="WorkerResultStatus"/></returns>
        public void Execute(IJobExecutionContext context)
        {
            RockContext           dbContext             = new RockContext();
            GroupService          groupService          = new GroupService(dbContext);
            AttributeService      attributeService      = new AttributeService(dbContext);
            AttributeValueService attributeValueService = new AttributeValueService(dbContext);
            GroupTypeRoleService  groupTypeRoleService  = new GroupTypeRoleService(dbContext);
            DefinedValueService   definedValueService   = new DefinedValueService(dbContext);
            DefinedTypeService    definedTypeService    = new DefinedTypeService(dbContext);
            BinaryFileService     binaryFileService     = new BinaryFileService(dbContext);

            // Get the datamap for loading attributes
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            String warnings  = string.Empty;
            var    processed = 0;

            try
            {
                String            siteid           = Encryption.DecryptString(dataMap.GetString("LeagueAppsSiteId"));
                String            clientid         = Encryption.DecryptString(dataMap.GetString("LeagueAppsClientId"));
                DefinedValueCache connectionStatus = DefinedValueCache.Get(dataMap.GetString("DefaultConnectionStatus").AsGuid(), dbContext);
                var p12File = binaryFileService.Get(dataMap.GetString("LeagueAppsServiceAccountFile").AsGuid());

                Group                group = groupService.Get(dataMap.GetString("ParentGroup").AsGuid());
                GroupTypeCache       grandparentGroupType = GroupTypeCache.Get(dataMap.Get("YearGroupType").ToString().AsGuid(), dbContext);
                GroupTypeCache       parentGroupType      = GroupTypeCache.Get(dataMap.Get("CategoryGroupType").ToString().AsGuid(), dbContext);
                GroupTypeCache       groupType            = GroupTypeCache.Get(dataMap.Get("LeagueGroupType").ToString().AsGuid(), dbContext);
                DefinedTypeCache     sports               = DefinedTypeCache.Get(dataMap.Get("SportsType").ToString().AsGuid(), dbContext);
                DefinedTypeCache     seasons              = DefinedTypeCache.Get(dataMap.Get("SeasonsType").ToString().AsGuid(), dbContext);
                DefinedTypeCache     genders              = DefinedTypeCache.Get(dataMap.Get("GendersType").ToString().AsGuid(), dbContext);
                Rock.Model.Attribute personattribute      = attributeService.Get(dataMap.GetString("LeagueAppsUserId").AsGuid());
                Rock.Model.Attribute groupmemberattribute = attributeService.Get(dataMap.GetString("LeagueGroupTeam").AsGuid());
                var entitytype = EntityTypeCache.Get(typeof(Group)).Id;

                var client = new RestClient("https://public.leagueapps.io");

                // Get all programs from LeagueApps
                var request = new RestRequest("/v1/sites/{siteid}/programs/current", Method.GET);
                request.AddUrlSegment("siteid", siteid);
                request.AddHeader("la-api-key", clientid);
                var response = client.Get(request);

                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    throw new Exception("LeagueApps API Response: " + response.StatusDescription + " Content Length: " + response.ContentLength);
                }

                if (response.Content != null)
                {
                    var export   = response.Content.ToString();
                    var programs = JsonConvert.DeserializeObject <List <Contracts.Programs> >(export);
                    var groups   = groupService.Queryable().Where(g => g.GroupTypeId == groupType.Id).ToList();

                    foreach (Contracts.Programs program in programs)
                    {
                        // Process the program
                        Group league    = null;
                        Group league2   = null;
                        Group league3   = null;
                        var   startdate = program.startTime;
                        var   mode      = program.mode.ToLower();
                        mode = mode.First().ToString().ToUpper() + mode.Substring(1);
                        var grandparentgroup = string.Format("{0}", startdate.Year);
                        if (program.programId > 0)
                        {
                            league = groupService.Queryable().Where(l => l.Name == grandparentgroup && l.ParentGroupId == group.Id).FirstOrDefault();
                            if (league != null)
                            {
                                league2 = groupService.Queryable().Where(l => l.Name == mode && l.ParentGroupId == league.Id).FirstOrDefault();
                                if (league2 != null)
                                {
                                    league3 = groupService.Queryable().Where(l => l.ForeignId == program.programId && l.GroupTypeId == groupType.Id && l.ParentGroupId == league2.Id).FirstOrDefault();
                                }
                            }
                        }
                        Guid guid  = Guid.NewGuid();
                        Guid guid2 = Guid.NewGuid();
                        Guid guid3 = Guid.NewGuid();

                        if (league == null)
                        {
                            // Create league grandparent Group
                            Group leagueGPG = new Group();
                            leagueGPG.Name           = grandparentgroup;
                            leagueGPG.GroupTypeId    = grandparentGroupType.Id;
                            leagueGPG.ParentGroupId  = group.Id;
                            leagueGPG.IsSystem       = false;
                            leagueGPG.IsActive       = true;
                            leagueGPG.IsSecurityRole = false;
                            leagueGPG.Order          = 0;
                            leagueGPG.Guid           = guid;
                            groupService.Add(leagueGPG);

                            // Now save the league grandparent group
                            dbContext.SaveChanges();
                            league = leagueGPG;
                        }

                        if (league2 == null)
                        {
                            // Create league parent Group
                            Group leaguePG = new Group();
                            leaguePG.Name           = mode;
                            leaguePG.GroupTypeId    = parentGroupType.Id;
                            leaguePG.ParentGroupId  = league.Id;
                            leaguePG.IsSystem       = false;
                            leaguePG.IsActive       = true;
                            leaguePG.IsSecurityRole = false;
                            leaguePG.Order          = 0;
                            leaguePG.Guid           = guid2;
                            groupService.Add(leaguePG);

                            // Now save the league parent group
                            dbContext.SaveChanges();
                            league2 = leaguePG;
                        }

                        if (league3 == null)
                        {
                            // Create the league
                            Group leagueG = new Group();
                            leagueG.Name           = program.name;
                            leagueG.GroupTypeId    = groupType.Id;
                            leagueG.ParentGroupId  = league2.Id;
                            leagueG.IsSystem       = false;
                            leagueG.IsActive       = true;
                            leagueG.IsSecurityRole = false;
                            leagueG.Order          = 0;
                            leagueG.Description    = HTMLConvertor.Convert(program.description);
                            leagueG.ForeignId      = program.programId;
                            groupService.Add(leagueG);

                            // Now save the league
                            dbContext.SaveChanges();
                            league3 = leagueG;
                        }
                        else
                        {
                            groups.Remove(league3);
                        }
                        league3.LoadAttributes();
                        var sport       = definedValueService.Queryable().Where(d => d.Value == program.sport && d.DefinedTypeId == sports.Id).FirstOrDefault();
                        var season      = definedValueService.Queryable().Where(d => d.Value == program.season && d.DefinedTypeId == seasons.Id).FirstOrDefault();
                        var groupgender = definedValueService.Queryable().Where(d => d.Value == program.gender && d.DefinedTypeId == genders.Id).FirstOrDefault();

                        if (!sport.IsNull())
                        {
                            league3.SetAttributeValue("Sport", sport.Guid);
                        }

                        if (!season.IsNull())
                        {
                            league3.SetAttributeValue("Season", season.Guid);
                        }
                        league3.SetAttributeValue("ExperienceLevel", program.experienceLevel);

                        if (!groupgender.IsNull())
                        {
                            league3.SetAttributeValue("Gender", groupgender.Guid);
                        }

                        if (startdate != DateTime.MinValue)
                        {
                            league3.SetAttributeValue("StartTime", startdate);
                        }

                        if (program.publicRegistrationTime != DateTime.MinValue)
                        {
                            league3.SetAttributeValue("PublicRegistrationTime", program.publicRegistrationTime);
                        }

                        if (program.ageLimitEffectiveDate != DateTime.MinValue)
                        {
                            league3.SetAttributeValue("AgeLimitDate", program.ageLimitEffectiveDate.Date.ToString("d"));
                        }
                        league3.SetAttributeValue("ProgramURL", program.programUrlHtml);
                        league3.SetAttributeValue("RegisterURL", program.registerUrlHtml);
                        league3.SetAttributeValue("ScheduleURL", program.scheduleUrlHtml);
                        league3.SetAttributeValue("StandingsURL", program.standingsUrlHtml);
                        league3.SetAttributeValue("ProgramLogo", program.programLogo150);
                        league3.SaveAttributeValues();
                        dbContext.SaveChanges();
                        APIClient.RunAsync(p12File, clientid, true, "/v2/sites/" + siteid + "/export/registrations-2?last-updated=0&last-id=0&program-id=" + program.programId).GetAwaiter().GetResult();
                        var applicants = APIClient.names;

                        context.UpdateLastStatusMessage("Processing league " + (processed + 1) + " of " + programs.Count + ": " + program.startTime.Year + " > " + program.mode + " > " + program.name + " (" + applicants.Count + " members).");

                        foreach (Contracts.Registrations applicant in applicants)
                        {
                            // Use a fresh RockContext on every person/groupmember to keep things moving quickly
                            using (var rockContext = new RockContext())
                            {
                                PersonService      personService      = new PersonService(rockContext);
                                GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                                LocationService    locationService    = new LocationService(rockContext);

                                Person person = null;

                                // 1. Try to load the person using the LeagueApps UserId
                                var attributevalue = applicant.userId.ToString();
                                var personIds      = attributeValueService.Queryable().Where(av => av.AttributeId == personattribute.Id &&
                                                                                             (av.Value == attributevalue ||
                                                                                              av.Value.Contains("|" + attributevalue + "|") ||
                                                                                              av.Value.StartsWith(attributevalue + "|"))).Select(av => av.EntityId);
                                if (personIds.Count() == 1)
                                {
                                    person = personService.Get(personIds.FirstOrDefault().Value);
                                }

                                // 2. If we don't have a person match then
                                //    just use the standard person match/create logic
                                if (person == null)
                                {
                                    APIClient.RunAsync(p12File, clientid, false, "/v2/sites/" + siteid + "/members/" + applicant.userId).GetAwaiter().GetResult();
                                    var member     = APIClient.user;
                                    var street1    = member.address1;
                                    var postalCode = member.zipCode;

                                    var email = string.IsNullOrEmpty(member.email) ? String.Empty : member.email.Trim();

                                    if (email != String.Empty)
                                    {
                                        if (!email.IsValidEmail())
                                        {
                                            email = String.Empty;
                                        }
                                    }

                                    List <Person> matches = personService.GetByMatch(member.firstName.Trim(), member.lastName.Trim(), member.birthDate, email, null, street1, postalCode).ToList();

                                    Location location = new Location()
                                    {
                                        Street1    = member.address1,
                                        Street2    = member.address2,
                                        City       = member.city,
                                        State      = member.state,
                                        PostalCode = member.zipCode,
                                        Country    = member.country ?? "US"
                                    };

                                    if (matches.Count > 1)
                                    {
                                        // Find the oldest member record in the list
                                        person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault();

                                        if (person == null)
                                        {
                                            // Find the oldest attendee record in the list
                                            person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault();
                                            if (person == null)
                                            {
                                                person = matches.OrderBy(p => p.Id).First();
                                            }
                                        }
                                    }
                                    else if (matches.Count == 1)
                                    {
                                        person = matches.First();
                                    }
                                    else
                                    {
                                        // Create the person
                                        Guid guid4 = Guid.NewGuid();
                                        person           = new Person();
                                        person.FirstName = member.firstName.Trim();
                                        person.LastName  = member.lastName.Trim();
                                        person.SetBirthDate(member.birthDate.Value);

                                        if (email != String.Empty)
                                        {
                                            person.Email = email;
                                        }
                                        person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                                        person.ConnectionStatusValueId = connectionStatus.Id;
                                        person.RecordStatusValueId     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                                        person.IsSystem   = false;
                                        person.IsDeceased = false;
                                        person.Guid       = guid4;
                                        var gender = member.gender;

                                        if (!String.IsNullOrEmpty(gender))
                                        {
                                            gender.Trim();

                                            if (gender == "Male" || gender == "male")
                                            {
                                                person.Gender = Gender.Male;
                                            }
                                            else if (gender == "Female" || gender == "female")
                                            {
                                                person.Gender = Gender.Female;
                                            }
                                            else
                                            {
                                                person.Gender = Gender.Unknown;
                                            }
                                        }
                                        else
                                        {
                                            person.Gender = Gender.Unknown;
                                        }


                                        var groupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;

                                        locationService.Verify(location, true);
                                        bool existingFamily = false;
                                        if (!string.IsNullOrWhiteSpace(member.address1))
                                        {
                                            var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);

                                            // See if we can find an existing family using the location where everyone is a web prospect
                                            var matchingLocations = locationService.Queryable().Where(l => l.Street1 == location.Street1 && l.PostalCode == location.PostalCode);
                                            var matchingFamilies  = matchingLocations.Where(l => l.GroupLocations.Any(gl => gl.Group.GroupTypeId == familyGroupType.Id)).SelectMany(l => l.GroupLocations).Select(gl => gl.Group);
                                            var matchingFamily    = matchingFamilies.Where(f => f.Members.All(m => m.Person.ConnectionStatusValueId == connectionStatus.Id) && f.Name == member.lastName + " Family");
                                            if (matchingFamily.Count() == 1)
                                            {
                                                var adultRole = familyGroupType.Roles
                                                                .FirstOrDefault(r =>
                                                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()));

                                                var childRole = familyGroupType.Roles
                                                                .FirstOrDefault(r =>
                                                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()));

                                                var age = person.Age;

                                                var familyRole = age.HasValue && age < 18 ? childRole : adultRole;
                                                PersonService.AddPersonToFamily(person, true, matchingFamily.FirstOrDefault().Id, familyRole.Id, rockContext);
                                                existingFamily = true;
                                            }
                                        }

                                        if (!existingFamily)
                                        {
                                            Group         family        = PersonService.SaveNewPerson(person, rockContext);
                                            GroupLocation groupLocation = new GroupLocation();
                                            groupLocation.GroupLocationTypeValueId = groupLocationTypeValueId;
                                            groupLocation.Location         = location;
                                            groupLocation.IsMappedLocation = true;
                                            family.CampusId = CampusCache.All().FirstOrDefault().Id;
                                            family.GroupLocations.Add(groupLocation);
                                        }

                                        rockContext.SaveChanges();
                                    }

                                    var groupLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME);

                                    // Check to see if the address/location should be updated.
                                    if (member.dateJoined > person.GetFamilies().SelectMany(f => f.GroupLocations).Where(gl => gl.GroupLocationTypeValueId == groupLocationType.Id).Max(gl => gl.CreatedDateTime ?? gl.Location.CreatedDateTime))
                                    {
                                        if (!location.StandardizedDateTime.HasValue)
                                        {
                                            locationService.Verify(location, true);
                                        }
                                        var allLocations = person.GetFamilies().SelectMany(f => f.GroupLocations);
                                        if (location.Street1 != null && location.StandardizedDateTime != null && !allLocations.Any(hl => hl.Location.Street1 == location.Street1) && !location.Street1.Contains("PO Box") && !location.Street1.Contains("PMB"))
                                        {
                                            locationService.Add(location);
                                            rockContext.SaveChanges();


                                            // Get all existing addresses of the specified type
                                            var groupLocations = person.PrimaryFamily.GroupLocations.Where(l => l.GroupLocationTypeValueId == groupLocationType.Id).ToList();

                                            // Create a new address of the specified type, saving all existing addresses of that type as Previous Addresses
                                            // Use the Is Mailing and Is Mapped values from any of the existing addresses of that type have those values set to true
                                            GroupService.AddNewGroupAddress(rockContext, person.PrimaryFamily,
                                                                            groupLocationType.Guid.ToString(), location.Id, true,
                                                                            "LeagueApps Import Data Job",
                                                                            groupLocations.Any(x => x.IsMailingLocation),
                                                                            groupLocations.Any(x => x.IsMappedLocation));
                                        }
                                    }

                                    // Update the person's LeagueApps User ID attribute
                                    person.LoadAttributes();
                                    var attributevaluelist = person.GetAttributeValue(personattribute.Key).SplitDelimitedValues().ToList();
                                    if (!attributevaluelist.Contains(applicant.userId.ToString()))
                                    {
                                        attributevaluelist.Add(applicant.userId.ToString());
                                        person.SetAttributeValue(personattribute.Key, string.Join("|", attributevaluelist) + "|");
                                        person.SaveAttributeValues(rockContext);
                                    }
                                }

                                // Check to see if the group member already exists
                                GroupMember groupmember = league3.Members.Where(m => m.PersonId == person.Id).FirstOrDefault();

                                if (groupmember == null)
                                {
                                    Guid guid5 = Guid.NewGuid();
                                    groupmember          = new GroupMember();
                                    groupmember.PersonId = person.Id;
                                    groupmember.GroupId  = league3.Id;
                                    groupmember.IsSystem = false;
                                    groupmember.Guid     = guid5;

                                    if (!String.IsNullOrEmpty(applicant.role))
                                    {
                                        var role = applicant.role.Split('(')[0].Trim();

                                        if (role == "FREEAGENT" || role == "PLAYER")
                                        {
                                            role = "Member";
                                        }
                                        else if (role == "CAPTAIN")
                                        {
                                            role = "Captain";
                                        }
                                        else if (role == "HEAD COACH" || role == "Head Coach")
                                        {
                                            role = "Head Coach";
                                        }
                                        else if (role == "ASST. COACH" || role == "Asst. Coach")
                                        {
                                            role = "Asst. Coach";
                                        }
                                        else
                                        {
                                            role = "Member";
                                        }
                                        var grouprole = groupTypeRoleService.Queryable().Where(r => r.GroupTypeId == groupType.Id && r.Name == role).FirstOrDefault().Id;
                                        groupmember.GroupRoleId = grouprole;
                                    }
                                    else
                                    {
                                        groupmember.GroupRoleId = groupType.DefaultGroupRoleId.Value;
                                    }
                                    groupmember.GroupMemberStatus = GroupMemberStatus.Active;
                                    groupMemberService.Add(groupmember);
                                    rockContext.SaveChanges();
                                }

                                // Make sure we update the team if necessary
                                groupmember.LoadAttributes();
                                groupmember.SetAttributeValue(groupmemberattribute.Key, applicant.team);
                                groupmember.SaveAttributeValues(rockContext);
                            }
                        }
                        processed++;
                    }

                    foreach (Group sportsleague in groups)
                    {
                        sportsleague.IsActive = false;
                        dbContext.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("LeagueApps Job Failed", ex);
            }
            finally
            {
                dbContext.SaveChanges();
            }

            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " leagues.";
        }
Ejemplo n.º 7
0
    private void processRegistration()
    {
        // Setup the Rock context
        var           rockContext          = new RockContext();
        var           groupLocationService = new GroupLocationService(rockContext);
        Group         family         = null;
        List <Child>  children       = ((List <Child>)ViewState["Children"]);
        PersonService personService  = new PersonService(rockContext);
        var           matchingPeople = personService.GetByMatch(tbFirstname.Text, tbLastName.Text, dpBirthday.SelectedDate, ebEmail.Text, pnbPhone.Text, acAddress.Street1, acAddress.PostalCode);
        bool          match          = matchingPeople.Count() == 1;

        if (match && !string.IsNullOrWhiteSpace(tbFirstName2.Text))
        {
            var matchingPeople2 = personService.GetByMatch(tbFirstName2.Text, tbLastName2.Text, dpBirthday2.SelectedDate, ebEmail2.Text, pnbPhone2.Text, acAddress.Street1, acAddress.PostalCode);
            match = matchingPeople.Count() == 1;
        }

        // If we get exactly one match given the specificity of the search criteria this is probably a safe bet
        if (match)
        {
            bool updated = false;
            // See if the family member already exists
            foreach (Child child in children)
            {
                foreach (GroupMember gm in matchingPeople.FirstOrDefault().GetFamilyMembers())
                {
                    if (gm.Person.BirthDate == child.DateOfBirth && gm.Person.FirstName == child.FirstName)
                    {
                        child.SaveAttributes(gm.Person);
                        updated = true;
                        break;
                    }
                }
                if (!updated)
                {
                    // If we get here, it's time to create a new family member
                    var newChild = child.SaveAsPerson(matchingPeople.FirstOrDefault().GetFamily().Id, rockContext);
                    family = newChild.GetFamily();
                }
            }
            rockContext.SaveChanges();

            var personWorkflowGuid = GetAttributeValue("PersonWorkflow");
            if (!string.IsNullOrWhiteSpace(personWorkflowGuid))
            {
                matchingPeople.FirstOrDefault().PrimaryAlias.LaunchWorkflow(new Guid(personWorkflowGuid), matchingPeople.FirstOrDefault().ToString() + " Pre-Registration", new Dictionary <string, string>()
                {
                    { "ExtraInformation", tbExtraInformation.Text }
                });
            }
        }
        else
        {
            DefinedValueCache mobilePhone = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);

            // Create the adult
            Person adult = new Person();
            adult.FirstName = tbFirstname.Text;
            adult.LastName  = tbLastName.Text;
            if (dpBirthday.SelectedDate != null)
            {
                adult.BirthDay   = dpBirthday.SelectedDate.Value.Day;
                adult.BirthMonth = dpBirthday.SelectedDate.Value.Month;
                adult.BirthYear  = dpBirthday.SelectedDate.Value.Year;
            }
            adult.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            adult.ConnectionStatusValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_WEB_PROSPECT.AsGuid()).Id;
            adult.RecordStatusValueId     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
            adult.UpdatePhoneNumber(mobilePhone.Id, pnbPhone.CountryCode, pnbPhone.Number, false, false, rockContext);
            adult.Email = ebEmail.Text;

            family = PersonService.SaveNewPerson(adult, rockContext, cpCampus.SelectedCampusId);

            if (!string.IsNullOrWhiteSpace(tbFirstName2.Text))
            {
                Person adult2 = new Person();
                adult2.FirstName = tbFirstName2.Text;
                adult2.LastName  = tbLastName2.Text;
                if (dpBirthday2.SelectedDate != null)
                {
                    adult2.BirthDay   = dpBirthday2.SelectedDate.Value.Day;
                    adult2.BirthMonth = dpBirthday2.SelectedDate.Value.Month;
                    adult2.BirthYear  = dpBirthday2.SelectedDate.Value.Year;
                }
                adult2.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                adult2.ConnectionStatusValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_WEB_PROSPECT.AsGuid()).Id;
                adult2.RecordStatusValueId     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;
                adult2.UpdatePhoneNumber(mobilePhone.Id, pnbPhone2.CountryCode, pnbPhone2.Number, false, false, rockContext);
                adult2.Email = ebEmail2.Text;

                PersonService.AddPersonToFamily(adult2, true, family.Id, 3, rockContext);
            }

            // Now create all the children
            foreach (Child child in children)
            {
                child.SaveAsPerson(family.Id, rockContext);
            }



            //rockContext.SaveChanges();
            var personWorkflowGuid = GetAttributeValue("PersonWorkflow");
            if (!string.IsNullOrWhiteSpace(personWorkflowGuid))
            {
                adult.PrimaryAlias.LaunchWorkflow(new Guid(GetAttributeValue("PersonWorkflow")), adult.ToString() + " Pre-Registration", new Dictionary <string, string>()
                {
                    { "ExtraInformation", tbExtraInformation.Text }
                });
            }
        }
        // Save the family address
        var homeLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

        if (homeLocationType != null)
        {
            // Find a location record for the address that was entered
            var loc = new Location();
            acAddress.GetValues(loc);
            if (acAddress.Street1.IsNotNullOrWhiteSpace() && loc.City.IsNotNullOrWhiteSpace())
            {
                loc = new LocationService(rockContext).Get(
                    loc.Street1, loc.Street2, loc.City, loc.State, loc.PostalCode, loc.Country, family, true);
            }
            else
            {
                loc = null;
            }


            if (!groupLocationService.Queryable()
                .Where(gl =>
                       gl.GroupId == family.Id &&
                       gl.GroupLocationTypeValueId == homeLocationType.Id &&
                       gl.LocationId == loc.Id)
                .Any())
            {
                var groupType        = GroupTypeCache.Get(family.GroupTypeId);
                var prevLocationType = groupType.LocationTypeValues.FirstOrDefault(l => l.Guid.Equals(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid()));
                if (prevLocationType != null)
                {
                    foreach (var prevLoc in groupLocationService.Queryable("Location,GroupLocationTypeValue")
                             .Where(gl =>
                                    gl.GroupId == family.Id &&
                                    gl.GroupLocationTypeValueId == homeLocationType.Id))
                    {
                        prevLoc.GroupLocationTypeValueId = prevLocationType.Id;
                        prevLoc.IsMailingLocation        = false;
                        prevLoc.IsMappedLocation         = false;
                    }
                }


                string addressChangeField = homeLocationType.Value;

                var groupLocation = groupLocationService.Queryable()
                                    .Where(gl =>
                                           gl.GroupId == family.Id &&
                                           gl.LocationId == loc.Id)
                                    .FirstOrDefault();
                if (groupLocation == null)
                {
                    groupLocation                   = new GroupLocation();
                    groupLocation.Location          = loc;
                    groupLocation.IsMailingLocation = true;
                    groupLocation.IsMappedLocation  = true;
                    groupLocation.LocationId        = loc.Id;
                    groupLocation.GroupId           = family.Id;
                    groupLocationService.Add(groupLocation);
                }
                groupLocation.GroupLocationTypeValueId = homeLocationType.Id;
            }

            rockContext.SaveChanges();
        }
    }
Ejemplo n.º 8
0
        public override MobileBlockResponse HandleRequest(string request, Dictionary <string, string> body)
        {
            if (request == "cancel")
            {
                var cancelResponse = new FormResponse
                {
                    Success    = true,
                    ActionType = "3",
                };

                return(new MobileBlockResponse()
                {
                    Request = "cancel",
                    Response = JsonConvert.SerializeObject(cancelResponse),
                    TTL = 0
                });
            }

            RockContext rockContext = new RockContext();
            var         parameter   = body["parameter"];

            Person person = null;

            if (parameter == "0")
            {
                person = new Person();
            }
            else
            {
                PersonAliasService personAliasService = new PersonAliasService(rockContext);
                var personAlias = personAliasService.Get(parameter.AsGuid());
                if (personAlias == null)
                {
                    return(base.HandleRequest(request, body));
                }
                person = personAlias.Person;
            }

            if (person.Id != 0 && !CanEdit(person))
            {
                return(base.HandleRequest(request, body));
            }

            if (body.ContainsKey("firstName"))
            {
                person.FirstName = body["firstName"];
            }

            if (!string.IsNullOrWhiteSpace(body["nickName"]))
            {
                person.NickName = body["nickName"];
            }
            person.LastName        = body["lastName"];
            person.TitleValueId    = body["title"].AsIntegerOrNull();
            person.SuffixValueId   = body["suffix"].AsIntegerOrNull();
            person.Gender          = ( Gender )body["gender"].AsInteger();
            person.Email           = body["email"];
            person.EmailPreference = ( EmailPreference )body["emailPreference"].AsInteger();
            person.SetBirthDate(body["birthdate"].AsDateTime());

            if (parameter == "0")
            {
                GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                var groupTypeRoleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;

                {
                    if (person.Age < 18)
                    {
                        groupTypeRoleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
                    }
                }
                PersonService.AddPersonToFamily(person, true, CurrentPerson.PrimaryFamilyId ?? 0, groupTypeRoleId, rockContext);
            }
            rockContext.SaveChanges();

            person.UpdatePhoneNumber(DefinedValueCache.Get(
                                         Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id,
                                     PhoneNumber.DefaultCountryCode(),
                                     body["mobilePhone"],
                                     true,
                                     false,
                                     rockContext
                                     );

            person.UpdatePhoneNumber(DefinedValueCache.Get(
                                         Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Id,
                                     PhoneNumber.DefaultCountryCode(),
                                     body["homePhone"],
                                     false,
                                     false,
                                     rockContext
                                     );

            person.UpdatePhoneNumber(DefinedValueCache.Get(
                                         Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK.AsGuid()).Id,
                                     PhoneNumber.DefaultCountryCode(),
                                     body["workPhone"],
                                     false,
                                     false,
                                     rockContext
                                     );

            var response = new FormResponse
            {
                Success    = true,
                ActionType = "3"
            };

            var nextPage = PageCache.Get(GetAttributeValue("NextPage"));

            if (nextPage != null)
            {
                response.ActionType = "2"; // replace page
                response.Resource   = nextPage.Id.ToString();

                DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                long     ms    = ( long )(DateTime.UtcNow - epoch).TotalMilliseconds;
                response.Parameter = ms.ToString();//Cache buster
            }


            return(new MobileBlockResponse()
            {
                Request = "save",
                Response = JsonConvert.SerializeObject(response),
                TTL = 0
            });
        }