Ejemplo n.º 1
0
        /// <summary>
        /// Adds the new home location.
        /// </summary>
        /// <param name="ncoaHistory">The NCOA history.</param>
        /// <param name="locationService">The location service.</param>
        /// <param name="groupLocationService">The group location service.</param>
        /// <param name="homeValueId">The home value identifier.</param>
        /// <param name="changes">The changes.</param>
        /// <param name="isMailingLocation">Is the location a mailing location.</param>
        /// <param name="isMappedLocation">Is the location a mapped location.</param>
        /// <returns></returns>
        private bool AddNewHomeLocation(NcoaHistory ncoaHistory, LocationService locationService, GroupLocationService groupLocationService, int?homeValueId, History.HistoryChangeList changes, bool isMailingLocation, bool isMappedLocation)
        {
            if (homeValueId.HasValue)
            {
                var location = locationService.Get(
                    ncoaHistory.UpdatedStreet1,
                    ncoaHistory.UpdatedStreet2,
                    ncoaHistory.UpdatedCity,
                    ncoaHistory.UpdatedState,
                    ncoaHistory.UpdatedPostalCode,
                    ncoaHistory.UpdatedCountry);

                var groupLocation = new GroupLocation();
                groupLocation.Location                 = location;
                groupLocation.IsMailingLocation        = isMailingLocation;
                groupLocation.IsMappedLocation         = isMappedLocation;
                groupLocation.GroupId                  = ncoaHistory.FamilyId;
                groupLocation.GroupLocationTypeValueId = homeValueId.Value;
                groupLocation.IsMailingLocation        = true;
                groupLocationService.Add(groupLocation);

                changes.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Property, "Location").SetNewValue(groupLocation.Location.ToString()).SourceOfChange = "NCOA Request";

                return(true);
            }

            return(false);
        }
Ejemplo n.º 2
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>();

            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)
                    {
                        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;
                    }
                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;
                }

                rockContext.SaveChanges();

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

            var queryParams = new Dictionary <string, string>();

            queryParams.Add("BusinessId", hfBusinessId.Value);
            NavigateToCurrentPage(queryParams);
        }
Ejemplo n.º 3
0
        public object UpdateProfile(MobilePerson profile)
        {
            var user = UserLoginService.GetCurrentUser(false);

            if (user == null)
            {
                return(ActionStatusCode(System.Net.HttpStatusCode.Unauthorized));
            }

            var personId    = user.PersonId.Value;
            var rockContext = new Data.RockContext();

            var personService      = new PersonService(rockContext);
            var phoneNumberService = new PhoneNumberService(rockContext);
            var person             = personService.Get(personId);

            person.NickName  = person.NickName == person.FirstName ? profile.FirstName : person.NickName;
            person.FirstName = profile.FirstName;
            person.LastName  = profile.LastName;

            var gender = (Model.Gender)profile.Gender;

            if (GenderVisibility != VisibilityTriState.Hidden)
            {
                person.Gender = gender;
            }

            if (GetAttributeValue(AttributeKeys.BirthDateShow).AsBoolean())
            {
                person.SetBirthDate(profile.BirthDate?.Date);
            }

            if (GetAttributeValue(AttributeKeys.CampusShow).AsBoolean())
            {
                person.PrimaryFamily.CampusId = profile.CampusGuid.HasValue ? CampusCache.Get(profile.CampusGuid.Value)?.Id : null;
            }

            if (GetAttributeValue(AttributeKeys.EmailShow).AsBoolean())
            {
                person.Email = profile.Email;
            }

            if (GetAttributeValue(AttributeKeys.MobilePhoneShow).AsBoolean())
            {
                int phoneNumberTypeId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;

                var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                if (phoneNumber == null)
                {
                    phoneNumber = new PhoneNumber {
                        NumberTypeValueId = phoneNumberTypeId
                    };
                    person.PhoneNumbers.Add(phoneNumber);
                }

                // TODO: What to do with country code?
                phoneNumber.CountryCode = PhoneNumber.CleanNumber("+1");
                phoneNumber.Number      = PhoneNumber.CleanNumber(profile.MobilePhone);

                if (string.IsNullOrWhiteSpace(phoneNumber.Number))
                {
                    person.PhoneNumbers.Remove(phoneNumber);
                    phoneNumberService.Delete(phoneNumber);
                }
            }

            if (GetAttributeValue(AttributeKeys.AddressShow).AsBoolean())
            {
                var addressTypeGuid = SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid();

                var groupLocationService = new GroupLocationService(rockContext);

                var dvHomeAddressType = DefinedValueCache.Get(addressTypeGuid);
                var familyAddress     = groupLocationService.Queryable().Where(l => l.GroupId == person.PrimaryFamily.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id).FirstOrDefault();

                if (familyAddress != null && string.IsNullOrWhiteSpace(profile.HomeAddress.Street1))
                {
                    // delete the current address
                    groupLocationService.Delete(familyAddress);
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(profile.HomeAddress.Street1))
                    {
                        if (familyAddress == null)
                        {
                            familyAddress = new GroupLocation();
                            groupLocationService.Add(familyAddress);
                            familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                            familyAddress.GroupId           = person.PrimaryFamily.Id;
                            familyAddress.IsMailingLocation = true;
                            familyAddress.IsMappedLocation  = true;
                        }
                        else if (familyAddress.Location.Street1 != profile.HomeAddress.Street1)
                        {
                            // user clicked move so create a previous address
                            var previousAddress = new GroupLocation();
                            groupLocationService.Add(previousAddress);

                            var previousAddressValue = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                            if (previousAddressValue != null)
                            {
                                previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                previousAddress.GroupId = person.PrimaryFamily.Id;

                                Location previousAddressLocation = new Location
                                {
                                    Street1    = familyAddress.Location.Street1,
                                    Street2    = familyAddress.Location.Street2,
                                    City       = familyAddress.Location.City,
                                    State      = familyAddress.Location.State,
                                    PostalCode = familyAddress.Location.PostalCode,
                                    Country    = familyAddress.Location.Country
                                };

                                previousAddress.Location = previousAddressLocation;
                            }
                        }

                        // TODO: ???
                        // familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                        // familyAddress.IsMappedLocation = cbIsPhysicalAddress.Checked;
                        familyAddress.Location = new LocationService(rockContext).Get(
                            profile.HomeAddress.Street1,
                            string.Empty,
                            profile.HomeAddress.City,
                            profile.HomeAddress.State,
                            profile.HomeAddress.PostalCode,
                            profile.HomeAddress.Country,
                            person.PrimaryFamily,
                            true);

                        // since there can only be one mapped location, set the other locations to not mapped
                        if (familyAddress.IsMappedLocation)
                        {
                            var groupLocations = groupLocationService.Queryable()
                                                 .Where(l => l.GroupId == person.PrimaryFamily.Id && l.Id != familyAddress.Id).ToList();

                            foreach (var groupLocation in groupLocations)
                            {
                                groupLocation.IsMappedLocation = false;
                            }
                        }

                        rockContext.SaveChanges();
                    }
                }
            }

            rockContext.SaveChanges();

            var mobilePerson = MobileHelper.GetMobilePerson(person, MobileHelper.GetCurrentApplicationSite());

            mobilePerson.AuthToken = MobileHelper.GetAuthenticationToken(user.UserName);

            return(ActionOk(mobilePerson));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates the person.
        /// </summary>
        /// <returns></returns>
        private Person CreatePerson()
        {
            var rockContext = new RockContext();

            DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read(GetAttributeValue("ConnectionStatus").AsGuid());
            DefinedValueCache dvcRecordStatus     = DefinedValueCache.Read(GetAttributeValue("RecordStatus").AsGuid());

            Person person = new Person();

            person.FirstName         = tbFirstName.Text;
            person.LastName          = tbLastName.Text;
            person.Email             = tbEmail.Text;
            person.IsEmailActive     = true;
            person.EmailPreference   = EmailPreference.EmailAllowed;
            person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            if (dvcConnectionStatus != null)
            {
                person.ConnectionStatusValueId = dvcConnectionStatus.Id;
            }

            if (dvcRecordStatus != null)
            {
                person.RecordStatusValueId = dvcRecordStatus.Id;
            }

            switch (ddlGender.SelectedValue)
            {
            case "M":
                person.Gender = Gender.Male;
                break;

            case "F":
                person.Gender = Gender.Female;
                break;

            default:
                person.Gender = Gender.Unknown;
                break;
            }

            var birthday = bdaypBirthDay.SelectedDate;

            if (birthday.HasValue)
            {
                person.BirthMonth = birthday.Value.Month;
                person.BirthDay   = birthday.Value.Day;
                if (birthday.Value.Year != DateTime.MinValue.Year)
                {
                    person.BirthYear = birthday.Value.Year;
                }
            }

            bool smsSelected = false;

            foreach (RepeaterItem item in rPhoneNumbers.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 (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var phoneNumber = new PhoneNumber {
                            NumberTypeValueId = phoneNumberTypeId
                        };
                        person.PhoneNumbers.Add(phoneNumber);
                        phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                        phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                        // Only allow one number to have SMS selected
                        if (smsSelected)
                        {
                            phoneNumber.IsMessagingEnabled = false;
                        }
                        else
                        {
                            phoneNumber.IsMessagingEnabled = cbSms.Checked;
                            smsSelected = cbSms.Checked;
                        }

                        phoneNumber.IsUnlisted = cbUnlisted.Checked;
                    }
                }
            }

            PersonService.SaveNewPerson(person, rockContext, null, false);

            // save address
            if (pnlAddress.Visible)
            {
                if (acAddress.IsValid && !string.IsNullOrWhiteSpace(acAddress.Street1) && !string.IsNullOrWhiteSpace(acAddress.City) && !string.IsNullOrWhiteSpace(acAddress.PostalCode))
                {
                    Guid locationTypeGuid = GetAttributeValue("LocationType").AsGuid();
                    if (locationTypeGuid != Guid.Empty)
                    {
                        Guid                 familyGroupTypeGuid  = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                        GroupService         groupService         = new GroupService(rockContext);
                        GroupLocationService groupLocationService = new GroupLocationService(rockContext);
                        var family = groupService.Queryable().Where(g => g.GroupType.Guid == familyGroupTypeGuid && g.Members.Any(m => m.PersonId == person.Id)).FirstOrDefault();

                        var groupLocation = new GroupLocation();
                        groupLocation.GroupId = family.Id;
                        groupLocationService.Add(groupLocation);

                        var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                        groupLocation.Location = location;

                        groupLocation.GroupLocationTypeValueId = DefinedValueCache.Read(locationTypeGuid).Id;
                        groupLocation.IsMailingLocation        = true;
                        groupLocation.IsMappedLocation         = true;

                        rockContext.SaveChanges();
                    }
                }
            }

            return(person);
        }
Ejemplo n.º 5
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 person
            Person person = null;

            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid?  guidPersonAttribute  = personAttributeValue.AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType")
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        Guid personAliasGuid = attributePersonValue.AsGuid();
                        if (!personAliasGuid.IsEmpty())
                        {
                            person = new PersonAliasService(rockContext).Queryable()
                                     .Where(a => a.Guid.Equals(personAliasGuid))
                                     .Select(a => a.Person)
                                     .FirstOrDefault();
                            if (person == null)
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return(false);
                            }
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'.");
                return(false);
            }

            // determine the location type to edit
            DefinedValueCache locationType = null;
            var locationTypeAttributeValue = action.GetWorklowAttributeValue(GetAttributeValue(action, "LocationTypeAttribute").AsGuid());

            if (locationTypeAttributeValue != null)
            {
                locationType = DefinedValueCache.Read(locationTypeAttributeValue.AsGuid());
            }
            if (locationType == null)
            {
                locationType = DefinedValueCache.Read(GetAttributeValue(action, "LocationType").AsGuid());
            }
            if (locationType == null)
            {
                errorMessages.Add("The location type to be updated was not selected.");
                return(false);
            }

            // get the new phone number value
            Location location      = null;
            string   locationValue = GetAttributeValue(action, "Location");
            Guid?    locationGuid  = locationValue.AsGuidOrNull();

            if (!locationGuid.HasValue || locationGuid.Value.IsEmpty())
            {
                string locationAttributeValue     = GetAttributeValue(action, "LocationAttribute");
                Guid?  locationAttributeValueGuid = locationAttributeValue.AsGuidOrNull();
                if (locationAttributeValueGuid.HasValue)
                {
                    locationGuid = action.GetWorklowAttributeValue(locationAttributeValueGuid.Value).AsGuidOrNull();
                }
            }

            if (locationGuid.HasValue)
            {
                location = new LocationService(rockContext).Get(locationGuid.Value);
            }

            if (location == null)
            {
                errorMessages.Add("The location value could not be determined.");
                return(false);
            }

            // gets value indicating if location is a mailing location
            string mailingValue     = GetAttributeValue(action, "IsMailing");
            Guid?  mailingValueGuid = mailingValue.AsGuidOrNull();

            if (mailingValueGuid.HasValue)
            {
                mailingValue = action.GetWorklowAttributeValue(mailingValueGuid.Value);
            }
            else
            {
                mailingValue = mailingValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?mailing = mailingValue.AsBooleanOrNull();

            // gets value indicating if location is a mapped location
            string mappedValue     = GetAttributeValue(action, "IsMapped");
            Guid?  mappedValueGuid = mappedValue.AsGuidOrNull();

            if (mappedValueGuid.HasValue)
            {
                mappedValue = action.GetWorklowAttributeValue(mappedValueGuid.Value);
            }
            else
            {
                mappedValue = mappedValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?mapped = mappedValue.AsBooleanOrNull();

            var groupLocationService = new GroupLocationService(rockContext);

            foreach (var family in person.GetFamilies(rockContext).ToList())
            {
                var    groupLocation = family.GroupLocations.FirstOrDefault(l => l.GroupLocationTypeValueId == locationType.Id);
                string oldValue      = string.Empty;
                if (groupLocation == null)
                {
                    groupLocation         = new GroupLocation();
                    groupLocation.GroupId = family.Id;
                    groupLocation.GroupLocationTypeValueId = locationType.Id;
                    groupLocationService.Add(groupLocation);
                }
                else
                {
                    oldValue = groupLocation.Location.ToString();
                }

                var groupChanges = new List <string>();

                History.EvaluateChange(
                    groupChanges,
                    locationType.Value + " Location",
                    oldValue,
                    location.ToString());

                groupLocation.Location = location;

                if (mailing.HasValue)
                {
                    History.EvaluateChange(
                        groupChanges,
                        locationType.Value + " Is Mailing",
                        groupLocation.IsMailingLocation.ToString(),
                        mailing.Value.ToString());
                    groupLocation.IsMailingLocation = mailing.Value;
                }

                if (mapped.HasValue)
                {
                    History.EvaluateChange(
                        groupChanges,
                        locationType.Value + " Is Map Location",
                        groupLocation.IsMappedLocation.ToString(),
                        mapped.Value.ToString());
                    groupLocation.IsMappedLocation = mapped.Value;
                }

                if (groupChanges.Any())
                {
                    groupChanges.Add(string.Format("<em>(Updated by the '{0}' workflow)</em>", action.ActionType.ActivityType.WorkflowType.Name));
                    foreach (var fm in family.Members)
                    {
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof(Person),
                            Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            fm.PersonId,
                            groupChanges,
                            family.Name,
                            typeof(Group),
                            family.Id,
                            false);
                    }
                }

                rockContext.SaveChanges();

                action.AddLogEntry(string.Format("Updated the {0} location for {1} (family: {2}) to {3}", locationType.Value, person.FullName, family.Name, location.ToString()));
            }

            return(true);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Handles the Click event of the btnGive 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 btnGive_Click(object sender, EventArgs e)
        {
            Person person = FindPerson();

            using (new UnitOfWorkScope())
            {
                RockTransactionScope.WrapTransaction(() =>
                {
                    var groupLocationService = new GroupLocationService();
                    var groupMemberService   = new GroupMemberService();
                    var phoneService         = new PhoneNumberService();
                    var locationService      = new LocationService();
                    var groupService         = new GroupService();
                    GroupLocation groupLocation;
                    Location homeAddress;
                    Group familyGroup;

                    var homeLocationType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_HOME);
                    var addressList      = locationService.Queryable().Where(l => l.Street1 == txtStreet.Text &&
                                                                             l.City == txtCity.Text && l.State == ddlState.SelectedValue && l.Zip == txtZip.Text &&
                                                                             l.LocationTypeValueId == homeLocationType.Id).ToList();

                    if (!addressList.Any())
                    {
                        homeAddress = new Location();
                        locationService.Add(homeAddress, person.Id);
                    }
                    else
                    {
                        homeAddress = addressList.FirstOrDefault();
                    }

                    homeAddress.Street1             = txtStreet.Text ?? homeAddress.Street1;
                    homeAddress.City                = txtCity.Text ?? homeAddress.City;
                    homeAddress.State               = ddlState.SelectedValue ?? homeAddress.State;
                    homeAddress.Zip                 = txtZip.Text ?? homeAddress.Zip;
                    homeAddress.IsActive            = true;
                    homeAddress.IsLocation          = true;
                    homeAddress.Country             = "US";
                    homeAddress.LocationTypeValueId = homeLocationType.Id;
                    locationService.Save(homeAddress, person.Id);

                    GroupType familyGroupType = new GroupTypeService().Get(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY));
                    var familyGroupList       = groupMemberService.Queryable().Where(g => g.PersonId == person.Id &&
                                                                                     g.Group.GroupType.Guid == familyGroupType.Guid).Select(g => g.Group).ToList();

                    if (!familyGroupList.Any())
                    {
                        familyGroup                = new Group();
                        familyGroup.IsActive       = true;
                        familyGroup.IsSystem       = false;
                        familyGroup.IsSecurityRole = false;
                        familyGroup.Name           = "The " + txtLastName.Text + " Family";
                        familyGroup.GroupTypeId    = familyGroupType.Id;
                        groupService.Add(familyGroup, person.Id);
                        groupService.Save(familyGroup, person.Id);

                        var familyMember         = new GroupMember();
                        familyMember.IsSystem    = false;
                        familyMember.GroupId     = familyGroup.Id;
                        familyMember.PersonId    = person.Id;
                        familyMember.GroupRoleId = new GroupRoleService().Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id;
                        groupMemberService.Add(familyMember, person.Id);
                        groupMemberService.Save(familyMember, person.Id);
                    }
                    else
                    {
                        familyGroup = familyGroupList.FirstOrDefault();
                    }

                    var groupLocationList = groupLocationService.Queryable().Where(g => g.GroupLocationTypeValueId == familyGroupType.Id &&
                                                                                   g.GroupId == familyGroup.Id).ToList();

                    if (!groupLocationList.Any())
                    {
                        groupLocation            = new GroupLocation();
                        groupLocation.GroupId    = familyGroup.Id;
                        groupLocation.LocationId = homeAddress.Id;
                        groupLocation.IsMailing  = true;
                        groupLocation.IsLocation = true;
                        groupLocation.GroupLocationTypeValueId = homeLocationType.Id;
                        groupLocationService.Add(groupLocation, person.Id);
                        groupLocationService.Save(groupLocation, person.Id);
                    }
                    else
                    {
                        groupLocation = groupLocationList.FirstOrDefault();
                    }

                    groupLocation.LocationId = homeAddress.Id;
                    groupLocationService.Save(groupLocation, person.Id);

                    var homePhoneType   = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME);
                    string phoneNumeric = txtPhone.Text.AsNumeric();
                    if (!phoneService.Queryable().Where(n => n.PersonId == person.Id &&
                                                        n.NumberTypeValueId == homePhoneType.Id && n.Number == phoneNumeric).Any())
                    {
                        var homePhone                = new PhoneNumber();
                        homePhone.Number             = phoneNumeric;
                        homePhone.PersonId           = person.Id;
                        homePhone.IsSystem           = false;
                        homePhone.IsMessagingEnabled = false;
                        homePhone.IsUnlisted         = false;
                        homePhone.NumberTypeValueId  = homePhoneType.Id;
                        phoneService.Add(homePhone, person.Id);
                        phoneService.Save(homePhone, person.Id);
                    }
                });
            }

            var      amountList   = (Dictionary <FinancialAccount, Decimal>)Session["CachedAmounts"];
            var      profileId    = (int)Session["CachedProfileId"];
            Location giftLocation = new Location();

            var configValues = (Dictionary <string, object>)Session["CachedMergeFields"];

            configValues.Add("Date", DateTimeOffset.Now.ToString("MM/dd/yyyy hh:mm tt"));

            var receiptTemplate = GetAttributeValue("ReceiptMessage");

            lReceipt.Text = receiptTemplate.ResolveMergeFields(configValues);
            var    summaryTemplate = GetAttributeValue("SummaryMessage");
            string summaryMessage  = summaryTemplate.ResolveMergeFields(configValues);

            var creditProcessorId = GetAttributeValue("CreditCardProvider");
            var achProcessorId    = GetAttributeValue("Checking/ACHProvider");
            var gatewayService    = new FinancialGatewayService();
            FinancialGateway gateway;

            if (!string.IsNullOrEmpty(txtCreditCard.Text) && !string.IsNullOrWhiteSpace(creditProcessorId))
            {
                int creditId = Convert.ToInt32(creditProcessorId);
                gateway = new FinancialGatewayService().Get(creditId);
            }
            else if (!string.IsNullOrEmpty(txtAccountNumber.Text) && !string.IsNullOrWhiteSpace(achProcessorId))
            {
                int achId = Convert.ToInt32(achProcessorId);
                gateway = new FinancialGatewayService().Get(achId);
            }
            else
            {
                gateway = gatewayService.Queryable().FirstOrDefault();
            }

            // #TODO test card through gateway

            if (btnFrequency.SelectedIndex > -1 && btnFrequency.SelectedValueAsInt() != DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.TRANSACTION_FREQUENCY_TYPE_ONE_TIME).Id)
            {
                using (new UnitOfWorkScope())
                {
                    RockTransactionScope.WrapTransaction(() =>
                    {
                        var scheduledTransactionDetailService = new FinancialScheduledTransactionDetailService();
                        var scheduledTransactionService       = new FinancialScheduledTransactionService();
                        FinancialScheduledTransaction scheduledTransaction;
                        var detailList = amountList.ToList();

                        if (profileId > 0)
                        {
                            scheduledTransaction = scheduledTransactionService.Get(profileId);
                        }
                        else
                        {
                            scheduledTransaction = new FinancialScheduledTransaction();
                            scheduledTransactionService.Add(scheduledTransaction, person.Id);
                        }

                        DateTime startDate = (DateTime)dtpStartDate.SelectedDate;
                        if (startDate != null)
                        {
                            scheduledTransaction.StartDate = startDate;
                        }

                        scheduledTransaction.TransactionFrequencyValueId = (int)btnFrequency.SelectedValueAsInt();
                        scheduledTransaction.AuthorizedPersonId          = person.Id;
                        scheduledTransaction.IsActive = true;

                        if (!string.IsNullOrEmpty(txtCreditCard.Text))
                        {
                            scheduledTransaction.CardReminderDate = mypExpiration.SelectedDate;
                        }

                        if (chkLimitGifts.Checked && !string.IsNullOrWhiteSpace(txtLimitNumber.Text))
                        {
                            scheduledTransaction.NumberOfPayments = Convert.ToInt32(txtLimitNumber.Text);
                        }

                        foreach (var detail in amountList.ToList())
                        {
                            var scheduledTransactionDetail       = new FinancialScheduledTransactionDetail();
                            scheduledTransactionDetail.AccountId = detail.Key.Id;
                            scheduledTransactionDetail.Amount    = detail.Value;
                            scheduledTransactionDetail.ScheduledTransactionId = scheduledTransaction.Id;
                            scheduledTransactionDetailService.Add(scheduledTransactionDetail, person.Id);
                            scheduledTransactionDetailService.Save(scheduledTransactionDetail, person.Id);
                        }

                        // implement gateway charge()

                        scheduledTransactionService.Save(scheduledTransaction, person.Id);
                    });
                }
            }
            else
            {
                using (new UnitOfWorkScope())
                {
                    RockTransactionScope.WrapTransaction(() =>
                    {
                        var transactionService = new FinancialTransactionService();
                        var tdService          = new FinancialTransactionDetailService();
                        var transaction        = new FinancialTransaction();
                        var detailList         = amountList.ToList();

                        transaction.Summary = summaryMessage;
                        transaction.Amount  = detailList.Sum(d => d.Value);
                        transaction.TransactionTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION).Id;
                        transaction.TransactionDateTime    = DateTimeOffset.Now.DateTime;
                        transaction.AuthorizedPersonId     = person.Id;
                        transactionService.Add(transaction, person.Id);

                        foreach (var detail in detailList)
                        {
                            var td           = new FinancialTransactionDetail();
                            td.TransactionId = transaction.Id;
                            td.AccountId     = detail.Key.Id;
                            td.Amount        = detail.Value;
                            td.TransactionId = transaction.Id;
                            tdService.Add(td, person.Id);
                            tdService.Save(td, person.Id);
                        }

                        // #TODO implement gateway.charge()

                        transactionService.Save(transaction, person.Id);
                    });
                }
            }

            Session["CachedMergeFields"] = configValues;
            pnlConfirm.Visible           = false;
            pnlComplete.Visible          = true;
            pnlContribution.Update();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Gets the name of the OAuth user.
        /// </summary>
        /// <param name="oauthUser">The OAuth user.</param>
        /// <param name="accessToken">The access token.</param>
        /// <returns></returns>
        public static string GetOAuthUser(Guid connectionStatusGuid, OAuthUser oauthUser, string accessToken = "")
        {
            // accessToken is required
            if (accessToken.IsNullOrWhiteSpace())
            {
                return(null);
            }

            string username = string.Empty;
            string oauthId  = oauthUser.id;

            string    userName = "******" + oauthId;
            UserLogin user     = null;

            using (var rockContext = new RockContext())
            {
                // Query for an existing user
                var userLoginService = new UserLoginService(rockContext);
                user = userLoginService.GetByUserName(userName);

                // If no user was found, see if we can find a match in the person table
                if (user == null)
                {
                    // Get name/email from OAuth login
                    string lastName  = oauthUser.last_name.ToString();
                    string firstName = oauthUser.first_name.ToString();
                    string email     = string.Empty;
                    try
                    { email = oauthUser.email.ToString(); }
                    catch { }

                    Person person = null;

                    // If person had an email, get the first person with the same name and email address.
                    if (!string.IsNullOrWhiteSpace(email))
                    {
                        var personService = new PersonService(rockContext);
                        person = personService.FindPerson(firstName, lastName, email, true);
                    }

                    var personRecordTypeId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                    var personStatusPendingId    = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING.AsGuid()).Id;
                    var personConnectionStatusId = DefinedValueCache.Get(connectionStatusGuid).Id;
                    var phoneNumberTypeId        = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Id;

                    rockContext.WrapTransaction(() =>
                    {
                        if (person == null)
                        {
                            person                         = new Person();
                            person.IsSystem                = false;
                            person.RecordTypeValueId       = personRecordTypeId;
                            person.RecordStatusValueId     = personStatusPendingId;
                            person.ConnectionStatusValueId = personConnectionStatusId;
                            person.FirstName               = firstName;
                            person.LastName                = lastName;
                            person.Email                   = email;
                            person.IsEmailActive           = true;
                            person.EmailPreference         = EmailPreference.EmailAllowed;
                            person.Gender                  = Gender.Unknown;

                            var phoneNumber = new PhoneNumber {
                                NumberTypeValueId = phoneNumberTypeId
                            };
                            person.PhoneNumbers.Add(phoneNumber);
                            phoneNumber.Number = PhoneNumber.CleanNumber(oauthUser.contact.phone.AsNumeric());

                            var birthday = oauthUser.contact.birthday.Split((new char[] { '-' }));
                            if (birthday.Length == 3)
                            {
                                person.BirthYear  = birthday[0].AsIntegerOrNull();
                                person.BirthMonth = birthday[1].AsIntegerOrNull();
                                person.BirthDay   = birthday[2].AsIntegerOrNull();
                            }

                            var gender = oauthUser.contact.gender_id.AsIntegerOrNull();
                            if (gender != null)
                            {
                                person.Gender = ( Gender )gender;
                            }

                            if (person != null)
                            {
                                PersonService.SaveNewPerson(person, rockContext, null, false);
                            }

                            // save address
                            var personLocation = new LocationService(rockContext)
                                                 .Get(oauthUser.address.street1, oauthUser.address.street2,
                                                      oauthUser.address.city, oauthUser.address.state, oauthUser.address.zip, oauthUser.address.country);
                            if (personLocation != null)
                            {
                                Guid locationTypeGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid();
                                if (locationTypeGuid != Guid.Empty)
                                {
                                    Guid familyGroupTypeGuid  = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid();
                                    GroupService groupService = new GroupService(rockContext);
                                    GroupLocationService groupLocationService = new GroupLocationService(rockContext);
                                    var family = groupService.Queryable().Where(g => g.GroupType.Guid == familyGroupTypeGuid && g.Members.Any(m => m.PersonId == person.Id)).FirstOrDefault();

                                    var groupLocation     = new GroupLocation();
                                    groupLocation.GroupId = family.Id;
                                    groupLocationService.Add(groupLocation);

                                    groupLocation.Location = personLocation;

                                    groupLocation.GroupLocationTypeValueId = DefinedValueCache.Get(locationTypeGuid).Id;
                                    groupLocation.IsMailingLocation        = true;
                                    groupLocation.IsMappedLocation         = true;

                                    rockContext.SaveChanges();
                                }
                            }
                        }

                        if (person != null)
                        {
                            int typeId = EntityTypeCache.Get(typeof(DoorkeeperOAuth)).Id;
                            user       = UserLoginService.Create(rockContext, person, AuthenticationServiceType.External, typeId, userName, "KFSRocksRock", true);
                        }
                    });
                }
                if (user != null)
                {
                    username = user.UserName;

                    if (user.PersonId.HasValue)
                    {
                        var converter = new ExpandoObjectConverter();

                        var personService = new PersonService(rockContext);
                        var person        = personService.Get(user.PersonId.Value);
                    }
                }

                return(username);
            }
        }
Ejemplo n.º 8
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)
        {
            // confirmation was disabled by btnSave on client-side.  So if returning without a redirect,
            // it should be enabled.  If returning with a redirect, the control won't be updated to reflect
            // confirmation being enabled, so it's ok to enable it here
            confirmExit.Enabled = true;

            if (Page.IsValid)
            {
                confirmExit.Enabled = true;

                using (new UnitOfWorkScope())
                {
                    var familyService       = new GroupService();
                    var familyMemberService = new GroupMemberService();
                    var personService       = new PersonService();

                    // SAVE FAMILY
                    _family          = familyService.Get(_family.Id);
                    _family.Name     = tbFamilyName.Text;
                    _family.CampusId = cpCampus.SelectedValueAsInt();

                    var familyGroupTypeId = _family.GroupTypeId;

                    familyService.Save(_family, CurrentPersonId);

                    // SAVE FAMILY MEMBERS
                    int?recordStatusValueID = ddlRecordStatus.SelectedValueAsInt();
                    int?reasonValueId       = ddlReason.SelectedValueAsInt();
                    var newFamilies         = new List <Group>();

                    foreach (var familyMember in FamilyMembers)
                    {
                        var role = familyRoles.Where(r => r.Guid.Equals(familyMember.RoleGuid)).FirstOrDefault();
                        if (role == null)
                        {
                            role = familyRoles.FirstOrDefault();
                        }

                        // People added to family (new or from other family)
                        if (!familyMember.ExistingFamilyMember)
                        {
                            var groupMember = new GroupMember();

                            if (familyMember.Id == -1)
                            {
                                // added new person
                                groupMember.Person           = new Person();
                                groupMember.Person.GivenName = familyMember.FirstName;
                                groupMember.Person.LastName  = familyMember.LastName;
                                groupMember.Person.Gender    = familyMember.Gender;
                                groupMember.Person.BirthDate = familyMember.BirthDate;
                            }
                            else
                            {
                                // added from other family
                                groupMember.Person = personService.Get(familyMember.Id);
                            }

                            groupMember.Person.RecordStatusValueId       = recordStatusValueID;
                            groupMember.Person.RecordStatusReasonValueId = reasonValueId;

                            groupMember.GroupId = _family.Id;
                            if (role != null)
                            {
                                groupMember.GroupRoleId = role.Id;
                            }

                            if (groupMember.Person != null)
                            {
                                familyMemberService.Add(groupMember, CurrentPersonId);
                                familyMemberService.Save(groupMember, CurrentPersonId);
                            }
                        }
                        else
                        {
                            // existing family members
                            var groupMember = familyMemberService.Queryable().Where(m =>
                                                                                    m.PersonId == familyMember.Id &&
                                                                                    m.Group.GroupTypeId == familyGroupTypeId &&
                                                                                    m.GroupId == _family.Id).FirstOrDefault();
                            if (groupMember != null)
                            {
                                if (familyMember.Removed)
                                {
                                    // Family member was removed and should be created in their own new family
                                    var newFamily = new Group();
                                    newFamily.Name        = familyMember.LastName + " Family";
                                    newFamily.GroupTypeId = familyGroupTypeId;
                                    newFamily.CampusId    = _family.CampusId;
                                    familyService.Add(newFamily, CurrentPersonId);
                                    familyService.Save(newFamily, CurrentPersonId);

                                    groupMember.Group = newFamily;
                                    familyMemberService.Save(groupMember, CurrentPersonId);

                                    newFamilies.Add(newFamily);
                                }
                                else
                                {
                                    // Existing member was not remvoved
                                    if (role != null)
                                    {
                                        groupMember.GroupRoleId = role.Id;
                                        groupMember.Person.RecordStatusValueId       = recordStatusValueID;
                                        groupMember.Person.RecordStatusReasonValueId = reasonValueId;
                                        familyMemberService.Save(groupMember, CurrentPersonId);
                                    }
                                }
                            }
                        }

                        // Remove anyone that was moved from another family
                        if (familyMember.RemoveFromOtherFamilies)
                        {
                            var otherFamilies = familyMemberService.Queryable()
                                                .Where(m =>
                                                       m.PersonId == familyMember.Id &&
                                                       m.Group.GroupTypeId == familyGroupTypeId &&
                                                       m.GroupId != _family.Id)
                                                .ToList();

                            foreach (var otherFamilyMember in otherFamilies)
                            {
                                var fm = familyMemberService.Get(otherFamilyMember.Id);
                                familyMemberService.Delete(fm, CurrentPersonId);
                                familyMemberService.Save(fm, CurrentPersonId);

                                var f = familyService.Queryable()
                                        .Where(g =>
                                               g.Id == otherFamilyMember.GroupId &&
                                               !g.Members.Any())
                                        .FirstOrDefault();

                                if (f != null)
                                {
                                    familyService.Delete(f, CurrentPersonId);
                                    familyService.Save(f, CurrentPersonId);
                                }
                            }
                        }
                    }

                    // SAVE LOCATIONS
                    var groupLocationService = new GroupLocationService();

                    // delete any group locations that were removed
                    var remainingLocationIds = FamilyAddresses.Where(a => a.Id > 0).Select(a => a.Id).ToList();
                    foreach (var removedLocation in groupLocationService.Queryable()
                             .Where(l => l.GroupId == _family.Id &&
                                    !remainingLocationIds.Contains(l.Id)))
                    {
                        groupLocationService.Delete(removedLocation, CurrentPersonId);
                        groupLocationService.Save(removedLocation, CurrentPersonId);
                    }

                    foreach (var familyAddress in FamilyAddresses)
                    {
                        Location updatedAddress = null;
                        if (familyAddress.LocationIsDirty)
                        {
                            updatedAddress = new LocationService().Get(
                                familyAddress.Street1, familyAddress.Street2, familyAddress.City,
                                familyAddress.State, familyAddress.Zip);
                        }

                        GroupLocation groupLocation = null;
                        if (familyAddress.Id > 0)
                        {
                            groupLocation = groupLocationService.Get(familyAddress.Id);
                        }
                        if (groupLocation == null)
                        {
                            groupLocation         = new GroupLocation();
                            groupLocation.GroupId = _family.Id;
                            groupLocationService.Add(groupLocation, CurrentPersonId);
                        }

                        groupLocation.GroupLocationTypeValueId = familyAddress.LocationTypeId;
                        groupLocation.IsMailing  = familyAddress.IsMailing;
                        groupLocation.IsLocation = familyAddress.IsLocation;
                        if (updatedAddress != null)
                        {
                            groupLocation.Location = updatedAddress;
                        }

                        groupLocationService.Save(groupLocation, CurrentPersonId);


                        // Add the same locations to any new families created by removing an existing family member
                        if (newFamilies.Any())
                        {
                            //reload grouplocation for access to child properties
                            groupLocation = groupLocationService.Get(groupLocation.Id);
                            foreach (var newFamily in newFamilies)
                            {
                                var newFamilyLocation = new GroupLocation();
                                newFamilyLocation.GroupId    = newFamily.Id;
                                newFamilyLocation.LocationId = groupLocation.LocationId;
                                newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId;
                                newFamilyLocation.IsMailing  = groupLocation.IsMailing;
                                newFamilyLocation.IsLocation = groupLocation.IsLocation;
                                groupLocationService.Add(newFamilyLocation, CurrentPersonId);
                                groupLocationService.Save(newFamilyLocation, CurrentPersonId);
                            }
                        }
                    }

                    _family = familyService.Get(_family.Id);
                    if (_family.Members.Any(m => m.PersonId == Person.Id))
                    {
                        Response.Redirect(string.Format("~/Person/{0}", Person.Id), false);
                    }
                    else
                    {
                        var fm = _family.Members
                                 .Where(m =>
                                        m.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)) &&
                                        m.Person.Gender == Gender.Male)
                                 .OrderByDescending(m => m.Person.Age)
                                 .FirstOrDefault();
                        if (fm == null)
                        {
                            fm = _family.Members
                                 .Where(m =>
                                        m.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)))
                                 .OrderByDescending(m => m.Person.Age)
                                 .FirstOrDefault();
                        }
                        if (fm == null)
                        {
                            fm = _family.Members
                                 .OrderByDescending(m => m.Person.Age)
                                 .FirstOrDefault();
                        }
                        if (fm != null)
                        {
                            Response.Redirect(string.Format("~/Person/{0}", fm.PersonId), false);
                        }
                        else
                        {
                            Response.Redirect("~", false);
                        }
                    }
                }
            }
        }
Ejemplo n.º 9
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)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);

                var changes = new List <string>();

                var person = personService.Get(CurrentPersonId ?? 0);
                if (person != null)
                {
                    int?orphanedPhotoId = null;
                    if (person.PhotoId != imgPhoto.BinaryFileId)
                    {
                        orphanedPhotoId = person.PhotoId;
                        person.PhotoId  = imgPhoto.BinaryFileId;

                        if (orphanedPhotoId.HasValue)
                        {
                            if (person.PhotoId.HasValue)
                            {
                                changes.Add("Modified the photo.");
                            }
                            else
                            {
                                changes.Add("Deleted the photo.");
                            }
                        }
                        else if (person.PhotoId.HasValue)
                        {
                            changes.Add("Added a photo.");
                        }
                    }

                    int?newTitleId = ddlTitle.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(newTitleId));
                    person.TitleValueId = newTitleId;

                    History.EvaluateChange(changes, "First Name", person.FirstName, tbFirstName.Text);
                    person.FirstName = tbFirstName.Text;

                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text);
                    person.NickName = tbNickName.Text;

                    History.EvaluateChange(changes, "Last Name", person.LastName, tbLastName.Text);
                    person.LastName = tbLastName.Text;

                    int?newSuffixId = ddlSuffix.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(newSuffixId));
                    person.SuffixValueId = newSuffixId;

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

                    var birthday = bpBirthDay.SelectedDate;
                    if (birthday.HasValue)
                    {
                        // If setting a future birthdate, subtract a century until birthdate 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;
                        }
                    }
                    else
                    {
                        person.SetBirthDate(null);
                    }

                    History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth);
                    History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay);
                    History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear);

                    var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                    History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                    person.Gender = newGender;

                    var phoneNumberTypeIds = new List <int>();

                    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)
                        {
                            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                            {
                                int phoneNumberTypeId;
                                if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                                {
                                    var phoneNumber       = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                                    string oldPhoneNumber = string.Empty;
                                    if (phoneNumber == null)
                                    {
                                        phoneNumber = new PhoneNumber {
                                            NumberTypeValueId = phoneNumberTypeId
                                        };
                                        person.PhoneNumbers.Add(phoneNumber);
                                    }
                                    else
                                    {
                                        oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                    }

                                    phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                                    phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                                    // Only allow one number to have SMS selected
                                    if (smsSelected)
                                    {
                                        phoneNumber.IsMessagingEnabled = false;
                                    }
                                    else
                                    {
                                        phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                        smsSelected = cbSms.Checked;
                                    }

                                    phoneNumber.IsUnlisted = cbUnlisted.Checked;
                                    phoneNumberTypeIds.Add(phoneNumberTypeId);

                                    History.EvaluateChange(
                                        changes,
                                        string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumberTypeId)),
                                        oldPhoneNumber,
                                        phoneNumber.NumberFormattedWithCountryCode);
                                }
                            }
                        }
                    }

                    // Remove any blank numbers
                    var phoneNumberService = new PhoneNumberService(rockContext);
                    foreach (var phoneNumber in person.PhoneNumbers
                             .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value))
                             .ToList())
                    {
                        History.EvaluateChange(
                            changes,
                            string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)),
                            phoneNumber.ToString(),
                            string.Empty);

                        person.PhoneNumbers.Remove(phoneNumber);
                        phoneNumberService.Delete(phoneNumber);
                    }

                    History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text);
                    person.Email = tbEmail.Text.Trim();

                    var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();
                    History.EvaluateChange(changes, "Email Preference", person.EmailPreference, newEmailPreference);
                    person.EmailPreference = newEmailPreference;

                    if (person.IsValid)
                    {
                        if (rockContext.SaveChanges() > 0)
                        {
                            if (changes.Any())
                            {
                                HistoryService.SaveChanges(
                                    rockContext,
                                    typeof(Person),
                                    Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                    person.Id,
                                    changes);
                            }

                            if (orphanedPhotoId.HasValue)
                            {
                                BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                                var binaryFile = binaryFileService.Get(orphanedPhotoId.Value);
                                if (binaryFile != null)
                                {
                                    // marked the old images as IsTemporary so they will get cleaned up later
                                    binaryFile.IsTemporary = true;
                                    rockContext.SaveChanges();
                                }
                            }

                            // if they used the ImageEditor, and cropped it, the uncropped 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 address
                        if (pnlAddress.Visible)
                        {
                            Guid?familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();
                            if (familyGroupTypeGuid.HasValue)
                            {
                                var familyGroup = new GroupService(rockContext).Queryable()
                                                  .Where(f => f.GroupType.Guid == familyGroupTypeGuid.Value &&
                                                         f.Members.Any(m => m.PersonId == person.Id))
                                                  .FirstOrDefault();
                                if (familyGroup != null)
                                {
                                    Guid?addressTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                                    if (addressTypeGuid.HasValue)
                                    {
                                        var groupLocationService = new GroupLocationService(rockContext);

                                        var dvHomeAddressType = DefinedValueCache.Read(addressTypeGuid.Value);
                                        var familyAddress     = groupLocationService.Queryable().Where(l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == dvHomeAddressType.Id).FirstOrDefault();
                                        if (familyAddress != null && string.IsNullOrWhiteSpace(acAddress.Street1))
                                        {
                                            // delete the current address
                                            History.EvaluateChange(changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty);
                                            groupLocationService.Delete(familyAddress);
                                            rockContext.SaveChanges();
                                        }
                                        else
                                        {
                                            if (!string.IsNullOrWhiteSpace(acAddress.Street1))
                                            {
                                                if (familyAddress == null)
                                                {
                                                    familyAddress = new GroupLocation();
                                                    groupLocationService.Add(familyAddress);
                                                    familyAddress.GroupLocationTypeValueId = dvHomeAddressType.Id;
                                                    familyAddress.GroupId           = familyGroup.Id;
                                                    familyAddress.IsMailingLocation = true;
                                                    familyAddress.IsMappedLocation  = true;
                                                }
                                                else if (hfStreet1.Value != string.Empty)
                                                {
                                                    // user clicked move so create a previous address
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add(previousAddress);

                                                    var previousAddressValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                                                    if (previousAddressValue != null)
                                                    {
                                                        previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                        previousAddress.GroupId = familyGroup.Id;

                                                        Location previousAddressLocation   = new Location();
                                                        previousAddressLocation.Street1    = hfStreet1.Value;
                                                        previousAddressLocation.Street2    = hfStreet2.Value;
                                                        previousAddressLocation.City       = hfCity.Value;
                                                        previousAddressLocation.State      = hfState.Value;
                                                        previousAddressLocation.PostalCode = hfPostalCode.Value;
                                                        previousAddressLocation.Country    = hfCountry.Value;

                                                        previousAddress.Location = previousAddressLocation;
                                                    }
                                                }

                                                familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                                                familyAddress.IsMappedLocation  = cbIsPhysicalAddress.Checked;

                                                var updatedHomeAddress = new Location();
                                                acAddress.GetValues(updatedHomeAddress);

                                                History.EvaluateChange(changes, dvHomeAddressType.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString());

                                                familyAddress.Location = updatedHomeAddress;
                                                rockContext.SaveChanges();
                                            }
                                        }

                                        HistoryService.SaveChanges(
                                            rockContext,
                                            typeof(Person),
                                            Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                            person.Id,
                                            changes);
                                    }
                                }
                            }
                        }

                        NavigateToParentPage();
                    }
                }
            });
        }
Ejemplo n.º 10
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();

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);
                var changes       = new List <string>();
                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);
                }

                // Business Name
                History.EvaluateChange(changes, "Last Name", business.LastName, tbBusinessName.Text);
                business.LastName = tbBusinessName.Text;

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

                string oldPhoneNumber = string.Empty;
                string newPhoneNumber = string.Empty;

                var phoneNumber = business.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == businessPhoneTypeId);
                if (phoneNumber != null)
                {
                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }

                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;

                    newPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                }
                else
                {
                    if (phoneNumber != null)
                    {
                        business.PhoneNumbers.Remove(phoneNumber);
                        new PhoneNumberService(rockContext).Delete(phoneNumber);
                    }
                }

                History.EvaluateChange(
                    changes,
                    string.Format("{0} Phone", DefinedValueCache.GetName(businessPhoneTypeId)),
                    oldPhoneNumber,
                    newPhoneNumber);

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

                // Record Status
                int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt();
                History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(business.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId));
                business.RecordStatusValueId = newRecordStatusId;

                // Record Status Reason
                int?newRecordStatusReasonId = null;
                if (business.RecordStatusValueId.HasValue && business.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id)
                {
                    newRecordStatusReasonId = ddlReason.SelectedValueAsInt();
                }

                History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(business.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId));
                business.RecordStatusReasonValueId = newRecordStatusReasonId;

                // Email
                business.IsEmailActive = true;
                History.EvaluateChange(changes, "Email", business.Email, tbEmail.Text);
                business.Email = tbEmail.Text.Trim();

                var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();
                History.EvaluateChange(changes, "EmailPreference", business.EmailPreference, newEmailPreference);
                business.EmailPreference = newEmailPreference;

                if (business.IsValid)
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                business.Id,
                                changes);
                        }
                    }
                }

                // 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.Read(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.Read(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS.AsGuid());
                int impliedRelationshipOwnerRoleId = impliedRelationshipGroupType.Roles
                                                     .Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid()))
                                                     .Select(r => r.Id)
                                                     .FirstOrDefault();
                var impliedRelationshipOwner = UpdateGroupMember(business.Id, impliedRelationshipGroupType, "Implied Relationship", null, impliedRelationshipOwnerRoleId, rockContext);

                rockContext.SaveChanges();

                // Location
                int workLocationTypeId = DefinedValueCache.Read(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)
                    {
                        groupLocationService.Delete(workLocation);
                        History.EvaluateChange(changes, "Address", workLocation.Location.ToString(), string.Empty);
                    }
                }
                else
                {
                    var oldValue = string.Empty;

                    var newLocation = new LocationService(rockContext).Get(
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);

                    if (workLocation != null)
                    {
                        oldValue = workLocation.Location.ToString();
                    }
                    else
                    {
                        workLocation = new GroupLocation();
                        groupLocationService.Add(workLocation);
                        workLocation.GroupId = adultFamilyMember.Group.Id;
                        workLocation.GroupLocationTypeValueId = workLocationTypeId;
                    }
                    workLocation.Location          = newLocation;
                    workLocation.IsMailingLocation = true;

                    History.EvaluateChange(changes, "Address", oldValue, newLocation.ToString());
                }

                rockContext.SaveChanges();

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

            ShowSummary(hfBusinessId.Value.AsInteger());
        }
Ejemplo n.º 11
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 person
            Person person = null;

            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid?  guidPersonAttribute  = personAttributeValue.AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType")
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        Guid personAliasGuid = attributePersonValue.AsGuid();
                        if (!personAliasGuid.IsEmpty())
                        {
                            person = new PersonAliasService(rockContext).Queryable()
                                     .Where(a => a.Guid.Equals(personAliasGuid))
                                     .Select(a => a.Person)
                                     .FirstOrDefault();
                            if (person == null)
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return(false);
                            }
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'.");
                return(false);
            }

            // determine the location type to edit
            DefinedValueCache locationType = null;
            var locationTypeAttributeValue = action.GetWorklowAttributeValue(GetAttributeValue(action, "LocationTypeAttribute").AsGuid());

            if (locationTypeAttributeValue != null)
            {
                locationType = DefinedValueCache.Get(locationTypeAttributeValue.AsGuid());
            }
            if (locationType == null)
            {
                locationType = DefinedValueCache.Get(GetAttributeValue(action, "LocationType").AsGuid());
            }
            if (locationType == null)
            {
                errorMessages.Add("The location type to be updated was not selected.");
                return(false);
            }

            // get the new phone number value
            Location location      = null;
            string   locationValue = GetAttributeValue(action, "Location");
            Guid?    locationGuid  = locationValue.AsGuidOrNull();

            if (!locationGuid.HasValue || locationGuid.Value.IsEmpty())
            {
                string locationAttributeValue     = GetAttributeValue(action, "LocationAttribute");
                Guid?  locationAttributeValueGuid = locationAttributeValue.AsGuidOrNull();
                if (locationAttributeValueGuid.HasValue)
                {
                    locationGuid = action.GetWorklowAttributeValue(locationAttributeValueGuid.Value).AsGuidOrNull();
                }
            }

            if (locationGuid.HasValue)
            {
                location = new LocationService(rockContext).Get(locationGuid.Value);
            }

            if (location == null)
            {
                errorMessages.Add("The location value could not be determined.");
                return(false);
            }

            // gets value indicating if location is a mailing location
            string mailingValue     = GetAttributeValue(action, "IsMailing");
            Guid?  mailingValueGuid = mailingValue.AsGuidOrNull();

            if (mailingValueGuid.HasValue)
            {
                mailingValue = action.GetWorklowAttributeValue(mailingValueGuid.Value);
            }
            else
            {
                mailingValue = mailingValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?mailing = mailingValue.AsBooleanOrNull();

            // gets value indicating if location is a mapped location
            string mappedValue     = GetAttributeValue(action, "IsMapped");
            Guid?  mappedValueGuid = mappedValue.AsGuidOrNull();

            if (mappedValueGuid.HasValue)
            {
                mappedValue = action.GetWorklowAttributeValue(mappedValueGuid.Value);
            }
            else
            {
                mappedValue = mappedValue.ResolveMergeFields(GetMergeFields(action));
            }
            bool?mapped = mappedValue.AsBooleanOrNull();

            var savePreviousAddress = GetAttributeValue(action, "SavePreviousAddress").AsBoolean();

            var locationService = new LocationService(rockContext);

            locationService.Verify(location, false);

            var groupLocationService = new GroupLocationService(rockContext);

            foreach (var family in person.GetFamilies(rockContext).ToList())
            {
                bool locationUpdated = false;

                if (savePreviousAddress)
                {
                    // Get all existing addresses of the specified type
                    var groupLocations = family.GroupLocations.Where(l => l.GroupLocationTypeValueId == locationType.Id).ToList();

                    // Create a new address of the specified type, saving all existing addresses of that type as Previous Addresses
                    // Use the specified Is Mailing and Is Mapped values from the action's parameters if they are set,
                    // otherwise set them to true if any of the existing addresses of that type have those values set to true
                    GroupService.AddNewGroupAddress(rockContext, family, locationType.Guid.ToString(), location.Id, true,
                                                    $"the {action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow",
                                                    mailing ?? groupLocations.Any(x => x.IsMailingLocation),
                                                    mapped ?? groupLocations.Any(x => x.IsMappedLocation));
                }
                else
                {
                    var    groupLocation = family.GroupLocations.FirstOrDefault(l => l.GroupLocationTypeValueId == locationType.Id);
                    string oldValue      = string.Empty;
                    if (groupLocation == null)
                    {
                        groupLocation         = new GroupLocation();
                        groupLocation.GroupId = family.Id;
                        groupLocation.GroupLocationTypeValueId = locationType.Id;
                        groupLocationService.Add(groupLocation);
                    }
                    else
                    {
                        oldValue = groupLocation.Location.ToString();
                    }

                    locationUpdated = oldValue != location.ToString();

                    groupLocation.Location = location;

                    if (mailing.HasValue)
                    {
                        if (((oldValue == string.Empty) ? null : groupLocation.IsMailingLocation.ToString()) != mailing.Value.ToString())
                        {
                            locationUpdated = true;
                        }
                        groupLocation.IsMailingLocation = mailing.Value;
                    }

                    if (mapped.HasValue)
                    {
                        if (((oldValue == string.Empty) ? null : groupLocation.IsMappedLocation.ToString()) != mapped.Value.ToString())
                        {
                            locationUpdated = true;
                        }
                        groupLocation.IsMappedLocation = mapped.Value;
                    }
                }

                if (locationUpdated)
                {
                    var groupChanges = new History.HistoryChangeList();
                    groupChanges.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, "Location").SourceOfChange = $"{action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow";

                    foreach (var fm in family.Members)
                    {
                        HistoryService.SaveChanges(
                            rockContext,
                            typeof(Person),
                            Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            fm.PersonId,
                            groupChanges,
                            family.Name,
                            typeof(Group),
                            family.Id,
                            false,
                            null,
                            rockContext.SourceOfChange);
                    }
                }

                rockContext.SaveChanges();

                action.AddLogEntry(string.Format("Updated the {0} location for {1} (family: {2}) to {3}", locationType.Value, person.FullName, family.Name, location.ToString()));
            }

            return(true);
        }
Ejemplo n.º 12
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.º 13
0
        /// <summary>
        /// Handles the Click event of the btnSave control. Perform a save operation on
        /// the person being edited and then navigate to the return page.
        /// </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)
        {
            RockContext rockContext           = new RockContext();
            Person      person                = new PersonService(rockContext).Get(TargetPersonId);
            Guid        emailWorkflowTypeGuid = Guid.Empty;

            rockContext.WrapTransaction(() =>
            {
                var changes = new List <string>();

                //
                // Process the nick name.
                //
                if (GetAttributeValue("EditNickName").AsBoolean(true))
                {
                    History.EvaluateChange(changes, "Nick Name", person.NickName, tbNickName.Text.Trim());
                    person.NickName = tbNickName.Text.Trim();
                }

                //
                // Process the gender.
                //
                var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>();
                History.EvaluateChange(changes, "Gender", person.Gender, newGender);
                person.Gender = newGender;

                //
                // Process the birthday.
                //
                if (GetAttributeValue("EditBirthday").AsBoolean(true))
                {
                    var birthMonth = person.BirthMonth;
                    var birthDay   = person.BirthDay;
                    var birthYear  = person.BirthYear;
                    var birthday   = bpBirthDay.SelectedDate;

                    if (birthday.HasValue)
                    {
                        // If setting a future birthdate, subtract a century until birthdate 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;
                        }
                    }
                    else
                    {
                        person.SetBirthDate(null);
                    }

                    History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth);
                    History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay);
                    History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear);
                }

                //
                // Process the grade / graduation year.
                //
                if (GetAttributeValue("EditGrade").AsBoolean(true))
                {
                    int?graduationYear = null;
                    if (ypGraduation.SelectedYear.HasValue)
                    {
                        graduationYear = ypGraduation.SelectedYear.Value;
                    }

                    History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear);
                    person.GraduationYear = graduationYear;
                }

                //
                // Process the marital status and anniversary date.
                //
                if (GetAttributeValue("EditMaritalStatus").AsBoolean(true))
                {
                    int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();
                    History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId));
                    person.MaritalStatusValueId = newMaritalStatusId;

                    History.EvaluateChange(changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate);
                    person.AnniversaryDate = dpAnniversaryDate.SelectedDate;
                }

                //
                // Process the e-mail address.
                //
                if (GetAttributeValue("EditEmail").AsBoolean(true))
                {
                    emailWorkflowTypeGuid = GetAttributeValue("EmailChangeWorkflow").AsGuid();

                    if (emailWorkflowTypeGuid == Guid.Empty)
                    {
                        History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text.Trim());
                        person.Email = tbEmail.Text.Trim();
                    }
                }

                //
                // Process all the phone numbers for this person.
                //
                bool smsSelected       = false;
                var phoneNumberTypeIds = new List <int>();
                foreach (RepeaterItem item in rContactInfo.Items)
                {
                    HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                    PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox;
                    CheckBox cbSms          = item.FindControl("cbSms") as CheckBox;

                    if (hfPhoneType != null &&
                        pnbPhone != null &&
                        cbSms != null)
                    {
                        if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number)))
                        {
                            int phoneNumberTypeId;
                            if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                            {
                                var phoneNumber       = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                                string oldPhoneNumber = string.Empty;
                                if (phoneNumber == null)
                                {
                                    phoneNumber = new PhoneNumber {
                                        NumberTypeValueId = phoneNumberTypeId
                                    };
                                    person.PhoneNumbers.Add(phoneNumber);
                                }
                                else
                                {
                                    oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode;
                                }

                                phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode);
                                phoneNumber.Number      = PhoneNumber.CleanNumber(pnbPhone.Number);

                                // Only allow one number to have SMS selected
                                if (smsSelected)
                                {
                                    phoneNumber.IsMessagingEnabled = false;
                                }
                                else
                                {
                                    phoneNumber.IsMessagingEnabled = cbSms.Checked;
                                    smsSelected = cbSms.Checked;
                                }

                                phoneNumberTypeIds.Add(phoneNumberTypeId);

                                History.EvaluateChange(
                                    changes,
                                    string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumberTypeId)),
                                    oldPhoneNumber,
                                    phoneNumber.NumberFormattedWithCountryCode);
                            }
                        }
                    }
                }

                //
                // Remove any blank numbers.
                //
                var phoneNumberService = new PhoneNumberService(rockContext);
                foreach (var phoneNumber in person.PhoneNumbers
                         .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value))
                         .ToList())
                {
                    History.EvaluateChange(
                        changes,
                        string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)),
                        phoneNumber.ToString(),
                        string.Empty);

                    person.PhoneNumbers.Remove(phoneNumber);
                    phoneNumberService.Delete(phoneNumber);
                }

                //
                // If the person is valid then save the person and begin
                // working on the family (address).
                //
                if (person.IsValid)
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(Person),
                                Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                person.Id,
                                changes);

                            changes.Clear();
                        }
                    }

                    //
                    // Save the family address information.
                    //
                    if (pnlAddress.Visible)
                    {
                        Guid?familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();
                        if (familyGroupTypeGuid.HasValue)
                        {
                            var familyGroup = new GroupService(rockContext).Queryable()
                                              .Where(f => f.GroupType.Guid == familyGroupTypeGuid.Value &&
                                                     f.Members.Any(m => m.PersonId == person.Id))
                                              .FirstOrDefault();
                            if (familyGroup != null)
                            {
                                Guid?addressTypeGuid = GetAttributeValue("AddressType").AsGuidOrNull();
                                if (addressTypeGuid.HasValue)
                                {
                                    var groupLocationService = new GroupLocationService(rockContext);

                                    var addressTypeDv = DefinedValueCache.Read(addressTypeGuid.Value);
                                    var familyAddress = groupLocationService.Queryable().Where(l => l.GroupId == familyGroup.Id && l.GroupLocationTypeValueId == addressTypeDv.Id).FirstOrDefault();
                                    if (familyAddress != null && string.IsNullOrWhiteSpace(acAddress.Street1))
                                    {
                                        // delete the current address
                                        History.EvaluateChange(changes, familyAddress.GroupLocationTypeValue.Value + " Location", familyAddress.Location.ToString(), string.Empty);
                                        groupLocationService.Delete(familyAddress);
                                        rockContext.SaveChanges();
                                    }
                                    else
                                    {
                                        if (!string.IsNullOrWhiteSpace(acAddress.Street1))
                                        {
                                            var previousAddressValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());

                                            if (familyAddress == null)
                                            {
                                                familyAddress = new GroupLocation();
                                                groupLocationService.Add(familyAddress);
                                                familyAddress.GroupLocationTypeValueId = addressTypeDv.Id;
                                                familyAddress.GroupId           = familyGroup.Id;
                                                familyAddress.IsMailingLocation = true;
                                                familyAddress.IsMappedLocation  = true;
                                            }
                                            else if (addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid() && previousAddressValue != null)
                                            {
                                                var isChanged = familyAddress.Location.Street1 != acAddress.Street1 ||
                                                                familyAddress.Location.Street2 != acAddress.Street2 ||
                                                                familyAddress.Location.City != acAddress.City ||
                                                                familyAddress.Location.State != acAddress.State ||
                                                                familyAddress.Location.PostalCode != acAddress.PostalCode;

                                                var hasPrevious = groupLocationService
                                                                  .Queryable("Location")
                                                                  .Where(l => l.GroupLocationTypeValueId == previousAddressValue.Id && l.GroupId == familyGroup.Id)
                                                                  .Where(l => l.Location.Street1 == familyAddress.Location.Street1)
                                                                  .Where(l => l.Location.Street2 == familyAddress.Location.Street2)
                                                                  .Where(l => l.Location.City == familyAddress.Location.City)
                                                                  .Where(l => l.Location.State == familyAddress.Location.State)
                                                                  .Where(l => l.Location.PostalCode == familyAddress.Location.PostalCode)
                                                                  .Where(l => l.Location.Country == familyAddress.Location.Country)
                                                                  .Any();

                                                //
                                                // Only save the previous address if it has actually changed and there is not
                                                // already a matching previous address.
                                                //
                                                if (isChanged && !hasPrevious)
                                                {
                                                    var previousAddress = new GroupLocation();
                                                    groupLocationService.Add(previousAddress);

                                                    previousAddress.GroupLocationTypeValueId = previousAddressValue.Id;
                                                    previousAddress.GroupId = familyGroup.Id;

                                                    Location previousAddressLocation   = new Location();
                                                    previousAddressLocation.Street1    = familyAddress.Location.Street1;
                                                    previousAddressLocation.Street2    = familyAddress.Location.Street2;
                                                    previousAddressLocation.City       = familyAddress.Location.City;
                                                    previousAddressLocation.State      = familyAddress.Location.State;
                                                    previousAddressLocation.PostalCode = familyAddress.Location.PostalCode;
                                                    previousAddressLocation.Country    = familyAddress.Location.Country;

                                                    previousAddress.Location = previousAddressLocation;
                                                }
                                            }

                                            familyAddress.IsMailingLocation = cbIsMailingAddress.Checked;
                                            familyAddress.IsMappedLocation  = cbIsPhysicalAddress.Checked;

                                            var updatedHomeAddress = new Location();
                                            acAddress.GetValues(updatedHomeAddress);

                                            History.EvaluateChange(changes, addressTypeDv.Value + " Location", familyAddress.Location != null ? familyAddress.Location.ToString() : string.Empty, updatedHomeAddress.ToString());

                                            familyAddress.Location = updatedHomeAddress;
                                            rockContext.SaveChanges();
                                        }
                                    }

                                    HistoryService.SaveChanges(
                                        rockContext,
                                        typeof(Person),
                                        Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                                        person.Id,
                                        changes);
                                }
                            }
                        }
                    }
                }
            });

            if (emailWorkflowTypeGuid != Guid.Empty)
            {
                LaunchEmailWorkflow(emailWorkflowTypeGuid, person, tbEmail.Text.Trim());
            }

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SuccessTemplate")))
            {
                pnlEdit.Visible    = false;
                pnlSuccess.Visible = true;

                nbSuccess.Text = GetAttributeValue("SuccessTemplate").ResolveMergeFields(new Dictionary <string, object>());
            }
            else
            {
                NavigateToParentPage();
            }
        }
Ejemplo n.º 14
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);
        }