/// <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)
        {
            Location location;

            var                       rockContext               = new RockContext();
            LocationService           locationService           = new LocationService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);

            int locationId = int.Parse(hfLocationId.Value);

            if (locationId == 0)
            {
                location      = new Location();
                location.Name = string.Empty;
            }
            else
            {
                location = locationService.Get(locationId);
                FlushCampus(locationId);
            }

            int?orphanedImageId = null;

            if (location.ImageId != imgImage.BinaryFileId)
            {
                orphanedImageId  = location.ImageId;
                location.ImageId = imgImage.BinaryFileId;
            }

            location.Name                = tbName.Text;
            location.IsActive            = cbIsActive.Checked;
            location.LocationTypeValueId = ddlLocationType.SelectedValueAsId();
            if (gpParentLocation != null && gpParentLocation.Location != null)
            {
                location.ParentLocationId = gpParentLocation.Location.Id;
            }
            else
            {
                location.ParentLocationId = null;
            }

            location.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();

            acAddress.GetValues(location);

            location.GeoPoint = geopPoint.SelectedValue;
            if (geopPoint.SelectedValue != null)
            {
                location.IsGeoPointLocked = true;
            }
            location.GeoFence = geopFence.SelectedValue;

            location.IsGeoPointLocked = cbGeoPointLocked.Checked;

            location.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributeEdits, location);

            if (!Page.IsValid)
            {
                return;
            }

            // if the location IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of location didn't pass.
            // So, make sure a message is displayed in the validation summary
            cvLocation.IsValid = location.IsValid;

            if (!cvLocation.IsValid)
            {
                cvLocation.ErrorMessage = location.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                return;
            }

            rockContext.WrapTransaction(() =>
            {
                if (location.Id.Equals(0))
                {
                    locationService.Add(location);
                }
                rockContext.SaveChanges();

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

                location.SaveAttributeValues(rockContext);
            });

            if (_personId.HasValue)
            {
                NavigateToParentPage(new Dictionary <string, string> {
                    { "PersonId", _personId.Value.ToString() }
                });
            }
            else
            {
                Rock.CheckIn.KioskDevice.FlushAll();

                var qryParams = new Dictionary <string, string>();
                qryParams["LocationId"]  = location.Id.ToString();
                qryParams["ExpandedIds"] = PageParameter("ExpandedIds");

                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
 public void Add_Should_Call_AddLocation(Add location)
 {
     _sut.Add(location);
     _storage.Verify(x => x.AddLocation(It.IsAny <string>(), It.IsAny <Location>()), Times.Once);
 }
Example #3
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (GetAttributeValue(AttributeKeys.DisplayTerms).AsBoolean() && !cbTOS.Checked)
            {
                nbTOS.Visible = true;
                return;
            }

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

            var person = GetPerson(personService);

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

                List <string> errors;

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

                    changeRequest.CompleteChanges(rockContext, out errors);
                }

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

                person.PhotoId = imgPhoto.BinaryFileId;

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

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

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

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

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

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


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

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

                PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);

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

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

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

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

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

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

            NavigateToParentPage();
        }
        public static Person CreatePersonFromMember(Member member, DefinedValueCache defaultConnectionValue)
        {
            Person person = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

                rockContext.SaveChanges();
            }


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

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


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

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

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

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

            return(person);
        }
Example #5
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            RockContext rockContext           = new RockContext();
            var         person                = GetPerson();
            var         personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));
            var         changeRequest         = new ChangeRequest
            {
                EntityTypeId     = personAliasEntityType.Id,
                EntityId         = person.PrimaryAliasId ?? 0,
                RequestorAliasId = CurrentPersonAliasId ?? 0,
                RequestorComment = tbComments.Text
            };

            changeRequest.EvaluatePropertyChange(person, "PhotoId", iuPhoto.BinaryFileId);
            changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
            changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
            changeRequest.EvaluatePropertyChange(person, "MiddleName", tbMiddleName.Text);
            changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
            changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

            var families = person.GetFamilies();

            if (families.Count() == 1)
            {
                var groupMember = person.PrimaryFamily.Members.Where(gm => gm.PersonId == person.Id).FirstOrDefault();
                if (groupMember != null)
                {
                    GroupTypeRole        groupTypeRole;
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    if (ddlFamilyRole.SelectedValue == "A")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid());
                    }
                    else
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid());
                    }
                    changeRequest.EvaluatePropertyChange(groupMember, "GroupRole", groupTypeRole, true);
                }
            }

            //Evaluate PhoneNumbers
            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)
                {
                    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 && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                        {
                            phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                            changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNullOrWhiteSpace())   // delete number
                        {
                            var phoneComment = string.Format("{0}: {1}.", phoneNumber.NumberTypeValue.Value, phoneNumber.NumberFormatted);
                            changeRequest.DeleteEntity(phoneNumber, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                        {
                            changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                        }

                        if (hfPhoneType.Value.AsInteger() == DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()))
                        {
                            var validationInfo = ValidateMobilePhoneNumber(PhoneNumber.CleanNumber(pnbPhone.Number));
                            if (validationInfo.IsNotNullOrWhiteSpace())
                            {
                                changeRequest.RequestorComment += "<h4>Dynamically Generated Warnings:</h4>" + validationInfo;
                            }
                        }
                    }
                }
            }

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


            var birthday = bpBirthday.SelectedDate;

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

            changeRequest.EvaluatePropertyChange(person, "Gender", ddlGender.SelectedValueAsEnum <Gender>());
            changeRequest.EvaluatePropertyChange(person, "MaritalStatusValue", DefinedValueCache.Get(ddlMaritalStatus.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "AnniversaryDate", dpAnniversaryDate.SelectedDate);
            changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);

            var groupEntity         = EntityTypeCache.Get(typeof(Group));
            var groupLocationEntity = EntityTypeCache.Get(typeof(GroupLocation));
            var family = person.GetFamily();

            var familyChangeRequest = new ChangeRequest()
            {
                EntityTypeId     = groupEntity.Id,
                EntityId         = family.Id,
                RequestorAliasId = CurrentPersonAliasId ?? 0
            };

            familyChangeRequest.EvaluatePropertyChange(family, "Campus", CampusCache.Get(ddlCampus.SelectedValueAsInt() ?? 0));

            var      currentLocation = person.GetHomeLocation();
            Location location        = new Location
            {
                Street1    = acAddress.Street1,
                Street2    = acAddress.Street2,
                City       = acAddress.City,
                State      = acAddress.State,
                PostalCode = acAddress.PostalCode,
            };
            var globalAttributesCache = GlobalAttributesCache.Get();

            location.Country = globalAttributesCache.OrganizationCountry;
            location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

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

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

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

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

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

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

            //Adding a new family member
            if (pAddPerson.SelectedValue.HasValue)
            {
                PersonService personService = new PersonService(rockContext);
                var           insertPerson  = personService.Get(pAddPerson.SelectedValue.Value);
                if (insertPerson != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                    var familyGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

                    //Remove all other group members
                    if (cbRemovePerson.Checked)
                    {
                        var members = groupMemberService.Queryable()
                                      .Where(m => m.PersonId == pAddPerson.SelectedValue.Value && m.Group.GroupTypeId == familyGroupTypeId);
                        foreach (var member in members)
                        {
                            var comment = string.Format("Removed {0} from {1}", insertPerson.FullName, member.Group.Name);
                            familyChangeRequest.DeleteEntity(member, true, comment);
                        }
                    }

                    var personFamilies = person.GetFamilies().ToList();

                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);

                    var roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
                    if (insertPerson.Age.HasValue && insertPerson.Age.Value > 17)
                    {
                        roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
                    }

                    foreach (var personFamily in personFamilies)
                    {
                        //Make a new group member
                        GroupMember familyMember = new GroupMember
                        {
                            PersonId          = pAddPerson.SelectedValue.Value,
                            GroupId           = personFamily.Id,
                            GroupMemberStatus = GroupMemberStatus.Active,
                            Guid        = Guid.NewGuid(),
                            GroupRoleId = roleId
                        };
                        var insertComment = string.Format("Added {0} to {1}", insertPerson.FullName, personFamily.Name);
                        familyChangeRequest.AddEntity(familyMember, rockContext, true, insertComment);
                    }
                }
            }

            bool autoApply = CanAutoApply(person);


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

                changeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (familyChangeRequest.ChangeRecords.Any())
            {
                familyChangeRequest.RequestorComment = tbComments.Text;
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(familyChangeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    familyChangeRequest.CompleteChanges(rockContext);
                }
                familyChangeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (autoApply)
            {
                NavigateToPerson();
            }
            else
            {
                pnlMain.Visible     = false;
                pnlNoPerson.Visible = false;
                pnlDone.Visible     = true;
            }
        }
Example #6
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)
        {
            Campus campus;
            var    rockContext         = new RockContext();
            var    campusService       = new CampusService(rockContext);
            var    locationService     = new LocationService(rockContext);
            var    locationCampusValue = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.LOCATION_TYPE_CAMPUS.AsGuid());

            int campusId = int.Parse(hfCampusId.Value);

            if (campusId == 0)
            {
                campus = new Campus();
                campusService.Add(campus);
            }
            else
            {
                campus = campusService.Get(campusId);
            }

            campus.Name        = tbCampusName.Text;
            campus.IsActive    = cbIsActive.Checked;
            campus.Description = tbDescription.Text;
            campus.Url         = tbUrl.Text;

            campus.PhoneNumber = tbPhoneNumber.Text;
            if (campus.Location == null)
            {
                var location = locationService.Queryable()
                               .Where(l =>
                                      l.Name.Equals(campus.Name, StringComparison.OrdinalIgnoreCase) &&
                                      l.LocationTypeValueId == locationCampusValue.Id)
                               .FirstOrDefault();
                if (location == null)
                {
                    location = new Location();
                    locationService.Add(location);
                }

                campus.Location = location;
            }

            campus.Location.Name = campus.Name;
            campus.Location.LocationTypeValueId = locationCampusValue.Id;

            string preValue = campus.Location.GetFullStreetAddress();

            acAddress.GetValues(campus.Location);
            string postValue = campus.Location.GetFullStreetAddress();

            campus.ShortCode = tbCampusCode.Text;

            var personService = new PersonService(rockContext);
            var leaderPerson  = personService.Get(ppCampusLeader.SelectedValue ?? 0);

            campus.LeaderPersonAliasId = leaderPerson != null ? leaderPerson.PrimaryAliasId : null;

            campus.ServiceTimes = kvlServiceTimes.Value;

            campus.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributes, campus);

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

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

                if (preValue != postValue && !string.IsNullOrWhiteSpace(campus.Location.Street1))
                {
                    locationService.Verify(campus.Location, true);
                }
            });

            Rock.Web.Cache.CampusCache.Flush(campus.Id);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                                Person person = null;

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

                                                var age = person.Age;

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

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

                                        rockContext.SaveChanges();
                                    }

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

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


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

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

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

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

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

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

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

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

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

            if (warnings.Length > 0)
            {
                throw new Exception(warnings);
            }
            context.Result = "Successfully imported " + processed + " leagues.";
        }
Example #8
0
        /// <summary>
        /// Loads the kiosk locations.
        /// </summary>
        /// <param name="kioskDevice">The kiosk device.</param>
        /// <param name="location">The location.</param>
        /// <param name="campusId">The campus identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        private static void LoadKioskLocations(KioskDevice kioskDevice, Location location, int?campusId, RockContext rockContext)
        {
            // Get the child locations and the selected location
            var allLocations = new LocationService(rockContext).GetAllDescendentIds(location.Id).ToList();

            allLocations.Add(location.Id);

            DateTime currentDateTime = RockDateTime.Now;

            if (campusId.HasValue)
            {
                currentDateTime = CampusCache.Get(campusId.Value)?.CurrentDateTime ?? RockDateTime.Now;
            }

            kioskDevice.CampusId = campusId;

            var activeSchedules = new Dictionary <int, KioskSchedule>();

            foreach (var groupLocation in new GroupLocationService(rockContext).GetActiveByLocations(allLocations).OrderBy(l => l.Order).AsNoTracking())
            {
                var kioskLocation = new KioskLocation(groupLocation.Location);
                kioskLocation.CampusId = campusId;
                kioskLocation.Order    = groupLocation.Order;

                // Populate each kioskLocation with its schedules (kioskSchedules)
                foreach (var schedule in groupLocation.Schedules.Where(s => s.CheckInStartOffsetMinutes.HasValue))
                {
                    if (activeSchedules.Keys.Contains(schedule.Id))
                    {
                        kioskLocation.KioskSchedules.Add(activeSchedules[schedule.Id]);
                    }
                    else
                    {
                        var kioskSchedule = new KioskSchedule(schedule);
                        kioskSchedule.CampusId     = kioskLocation.CampusId;
                        kioskSchedule.CheckInTimes = schedule.GetCheckInTimes(currentDateTime);
                        if (kioskSchedule.IsCheckInActive || kioskSchedule.IsCheckOutActive || kioskSchedule.NextActiveDateTime.HasValue)
                        {
                            kioskLocation.KioskSchedules.Add(kioskSchedule);
                            activeSchedules.Add(schedule.Id, kioskSchedule);
                        }
                    }
                }

                // If the group location has any active OR future schedules, add the group's group type to the kiosk's
                // list of group types
                if (kioskLocation.KioskSchedules.Count > 0)
                {
                    KioskGroupType kioskGroupType = kioskDevice.KioskGroupTypes.Where(g => g.GroupType.Id == groupLocation.Group.GroupTypeId).FirstOrDefault();
                    if (kioskGroupType == null)
                    {
                        kioskGroupType = new KioskGroupType(groupLocation.Group.GroupTypeId);
                        kioskDevice.KioskGroupTypes.Add(kioskGroupType);
                    }

                    KioskGroup kioskGroup = kioskGroupType.KioskGroups.Where(g => g.Group.Id == groupLocation.GroupId).FirstOrDefault();
                    if (kioskGroup == null)
                    {
                        kioskGroup = new KioskGroup(groupLocation.Group);
                        kioskGroup.Group.LoadAttributes(rockContext);
                        kioskGroupType.KioskGroups.Add(kioskGroup);
                    }

                    kioskGroup.KioskLocations.Add(kioskLocation);
                }
            }
        }
Example #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)
        {
            Location location;

            var                       rockContext               = new RockContext();
            LocationService           locationService           = new LocationService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);

            int locationId = int.Parse(hfLocationId.Value);

            if (locationId == 0)
            {
                location      = new Location();
                location.Name = string.Empty;
            }
            else
            {
                location = locationService.Get(locationId);
            }

            location.Name                = tbName.Text;
            location.IsActive            = cbIsActive.Checked;
            location.LocationTypeValueId = ddlLocationType.SelectedValueAsId();
            if (gpParentLocation != null && gpParentLocation.Location != null)
            {
                location.ParentLocationId = gpParentLocation.Location.Id;
            }
            else
            {
                location.ParentLocationId = null;
            }

            location.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();

            var addrLocation = locapAddress.Location;

            if (addrLocation != null)
            {
                location.Street1 = addrLocation.Street1;
                location.Street2 = addrLocation.Street2;
                location.City    = addrLocation.City;
                location.State   = addrLocation.State;
                location.Zip     = addrLocation.Zip;
            }

            location.GeoPoint = geopPoint.SelectedValue;
            if (geopPoint.SelectedValue != null)
            {
                location.IsGeoPointLocked = true;
            }
            location.GeoFence = geopFence.SelectedValue;

            location.IsGeoPointLocked = cbGeoPointLocked.Checked;

            location.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributeEdits, location);

            if (!Page.IsValid)
            {
                return;
            }

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

            RockTransactionScope.WrapTransaction(() =>
            {
                if (location.Id.Equals(0))
                {
                    locationService.Add(location);
                }
                rockContext.SaveChanges();

                location.SaveAttributeValues(rockContext);
            });



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

            qryParams["LocationId"] = location.Id.ToString();

            NavigateToPage(RockPage.Guid, qryParams);
        }
Example #10
0
 public async Task <IActionResult> Post([FromBody] Location location)
 {
     return(CreatedAtAction("Get", new { id = location.CarID }, locationService.Add(location)));
 }
Example #11
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            if (HasFilterErrors())
            {
                return;
            }

            var         checkinAreaFilter = CheckinManagerHelper.GetCheckinAreaFilter(this);
            CampusCache campus            = GetCampusFromContext();

            var selectedScheduleIds = lbSchedules.SelectedValues.AsIntegerList();

            if (selectedScheduleIds.Any())
            {
                btnShowFilter.AddCssClass("criteria-exists bg-warning");
            }
            else
            {
                btnShowFilter.RemoveCssClass("criteria-exists bg-warning");
            }

            CheckinManagerHelper.SaveRoomListFilterToCookie(selectedScheduleIds.ToArray());

            var rockContext      = new RockContext();
            var groupService     = new GroupService(rockContext);
            var groupTypeService = new GroupTypeService(rockContext);
            IEnumerable <CheckinAreaPath> checkinAreaPaths;

            if (checkinAreaFilter != null)
            {
                checkinAreaPaths = groupTypeService.GetCheckinAreaDescendantsPath(checkinAreaFilter.Id);
            }
            else
            {
                checkinAreaPaths = groupTypeService.GetAllCheckinAreaPaths();
            }

            var selectedGroupTypeIds = checkinAreaPaths.Select(a => a.GroupTypeId).Distinct().ToArray();

            var groupLocationService = new GroupLocationService(rockContext);
            var groupLocationsQuery  = groupLocationService.Queryable()
                                       .Where(gl => selectedGroupTypeIds.Contains(gl.Group.GroupTypeId) && gl.Group.IsActive && (!gl.Group.IsArchived));

            var parentLocationIdParameter = PageParameter(PageParameterKey.ParentLocationId).AsIntegerOrNull();
            var locationIdParameter       = PageParameter(PageParameterKey.LocationId).AsIntegerOrNull();
            var locationGridField         = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lRoomName");

            if (locationGridField != null && !locationGridField.Visible)
            {
                locationGridField.Visible = true;
            }

            List <int> locationIds;

            if (locationIdParameter.HasValue)
            {
                // If LocationId is specified in the URL, list only items for the specified location.
                // Also, hide the Location Grid Column and set the PanelTitle as the location's name
                // This will take precedence over the selected campus+locations and/or <seealso cref="ParentLocationId"/>
                var locationService = new LocationService(rockContext);
                lPanelTitle.Text = locationService.GetSelect(locationIdParameter.Value, s => s.Name);

                locationIds = new List <int>();
                locationIds.Add(locationIdParameter.Value);

                if (locationGridField != null)
                {
                    // since a LocationId parameter was specified, the LocationGrid field doesn't need to be shown
                    locationGridField.Visible = false;
                }
            }
            else if (parentLocationIdParameter.HasValue)
            {
                // If parentLocationId is specified, show the direct (first level) child locations of the specified ParentLocationId.
                // This will take precedence over the selected campus+locations.
                var locationService = new LocationService(rockContext);
                locationIds = locationService.Queryable()
                              .Where(a => a.ParentLocationId.HasValue && a.ParentLocationId.Value == parentLocationIdParameter.Value)
                              .Select(a => a.Id).ToList();

                lPanelTitle.Text = string.Format("{0} Child Locations", locationService.GetSelect(parentLocationIdParameter.Value, s => s.Name));
            }
            else
            {
                // Limit locations (rooms) to locations within the selected campus.
                locationIds = new LocationService(rockContext).GetAllDescendentIds(campus.LocationId.Value).ToList();
                locationIds.Add(campus.LocationId.Value, true);

                lPanelTitle.Text = "Room List";
            }

            groupLocationsQuery = groupLocationsQuery.Where(a => locationIds.Contains(a.LocationId));

            if (selectedScheduleIds.Any())
            {
                groupLocationsQuery = groupLocationsQuery.Where(a => a.Schedules.Any(s => s.IsActive && s.CheckInStartOffsetMinutes.HasValue && selectedScheduleIds.Contains(s.Id)));
            }
            else
            {
                groupLocationsQuery = groupLocationsQuery.Where(a => a.Schedules.Any(s => s.IsActive && s.CheckInStartOffsetMinutes.HasValue));
            }

            var groupLocationList = groupLocationsQuery.Select(a => new GroupLocationInfo
            {
                LocationId      = a.LocationId,
                LocationName    = a.Location.Name,
                ParentGroupId   = a.Group.ParentGroupId,
                ParentGroupName = a.Group.ParentGroup.Name,
                GroupId         = a.Group.Id,
                GroupName       = a.Group.Name,
                GroupTypeId     = a.Group.GroupTypeId
            }).ToList();

            var      startDateTime = RockDateTime.Today;
            DateTime currentDateTime;

            if (campus != null)
            {
                currentDateTime = campus.CurrentDateTime;
            }
            else
            {
                currentDateTime = RockDateTime.Now;
            }

            // Get all Attendance records for the current day and location.
            var attendanceQuery = new AttendanceService(rockContext).Queryable().Where(a =>
                                                                                       a.StartDateTime >= startDateTime &&
                                                                                       a.DidAttend == true &&
                                                                                       a.StartDateTime <= currentDateTime &&
                                                                                       a.PersonAliasId.HasValue &&
                                                                                       a.Occurrence.GroupId.HasValue &&
                                                                                       a.Occurrence.LocationId.HasValue &&
                                                                                       a.Occurrence.ScheduleId.HasValue);

            // Limit attendances (rooms) to the groupLocations' LocationId and GroupIds that we'll be showing
            var groupLocationLocationIds = groupLocationList.Select(a => a.LocationId).Distinct().ToList();
            var groupLocationGroupsIds   = groupLocationList.Select(a => a.GroupId).Distinct().ToList();

            attendanceQuery = attendanceQuery.Where(a =>
                                                    groupLocationLocationIds.Contains(a.Occurrence.LocationId.Value) &&
                                                    groupLocationGroupsIds.Contains(a.Occurrence.GroupId.Value));

            attendanceQuery = attendanceQuery.Where(a => selectedGroupTypeIds.Contains(a.Occurrence.Group.GroupTypeId));

            if (selectedScheduleIds.Any())
            {
                attendanceQuery = attendanceQuery.Where(a => selectedScheduleIds.Contains(a.Occurrence.ScheduleId.Value));
            }

            var rosterAttendeeAttendanceList = RosterAttendeeAttendance.Select(attendanceQuery).ToList();

            var groupTypeIdsWithAllowCheckout = selectedGroupTypeIds
                                                .Select(a => GroupTypeCache.Get(a))
                                                .Where(a => a != null)
                                                .Where(gt => gt.GetCheckInConfigurationAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_GROUPTYPE_ALLOW_CHECKOUT).AsBoolean())
                                                .Select(a => a.Id)
                                                .Distinct().ToList();

            var groupTypeIdsWithEnablePresence = selectedGroupTypeIds
                                                 .Select(a => GroupTypeCache.Get(a))
                                                 .Where(a => a != null)
                                                 .Where(gt => gt.GetCheckInConfigurationAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_GROUPTYPE_ENABLE_PRESENCE).AsBoolean())
                                                 .Select(a => a.Id)
                                                 .Distinct();

            var scheduleIds  = rosterAttendeeAttendanceList.Select(a => a.ScheduleId.Value).Distinct().ToList();
            var scheduleList = new ScheduleService(rockContext).GetByIds(scheduleIds).ToList();
            var scheduleIdsWasScheduleOrCheckInActiveForCheckOut = new HashSet <int>(scheduleList.Where(a => a.WasScheduleOrCheckInActiveForCheckOut(currentDateTime)).Select(a => a.Id).ToList());

            rosterAttendeeAttendanceList = rosterAttendeeAttendanceList.Where(a =>
            {
                var allowCheckout = groupTypeIdsWithAllowCheckout.Contains(a.GroupTypeId);
                if (!allowCheckout)
                {
                    /*
                     *  If AllowCheckout is false, remove all Attendees whose schedules are not currently active. Per the 'WasSchedule...ActiveForCheckOut()'
                     *  method below: "Check-out can happen while check-in is active or until the event ends (start time + duration)." This will help to keep
                     *  the list of 'Present' attendees cleaned up and accurate, based on the room schedules, since the volunteers have no way to manually mark
                     *  an Attendee as 'Checked-out'.
                     *
                     *  If, on the other hand, AllowCheckout is true, it will be the volunteers' responsibility to click the [Check-out] button when an
                     *  Attendee leaves the room, in order to keep the list of 'Present' Attendees in order. This will also allow the volunteers to continue
                     *  'Checking-out' Attendees in the case that the parents are running late in picking them up.
                     */

                    return(scheduleIdsWasScheduleOrCheckInActiveForCheckOut.Contains(a.ScheduleId.Value));
                }
                else
                {
                    return(true);
                }
            }).ToList();

            var attendancesByLocationId = rosterAttendeeAttendanceList
                                          .GroupBy(a => a.LocationId.Value).ToDictionary(k => k.Key, v => v.ToList());

            _attendancesByLocationIdAndGroupId = attendancesByLocationId.ToDictionary(
                k => k.Key,
                v => v.Value.GroupBy(x => x.GroupId.Value).ToDictionary(x => x.Key, xx => xx.ToList()));

            _checkinAreaPathsLookupByGroupTypeId = checkinAreaPaths.ToDictionary(k => k.GroupTypeId, v => v);

            _showOnlyParentGroup = this.GetAttributeValue(AttributeKey.ShowOnlyParentGroup).AsBoolean();

            var roomList = new List <RoomInfo>();

            foreach (var groupLocation in groupLocationList)
            {
                AddToRoomList(roomList, groupLocation);
            }

            List <RoomInfo> sortedRoomList;

            if (_showOnlyParentGroup)
            {
                sortedRoomList = roomList.OrderBy(a => a.LocationName).ToList();
            }
            else
            {
                sortedRoomList = new List <RoomInfo>();
                sortedRoomList.AddRange(roomList.OfType <RoomInfoByGroup>().OrderBy(a => a.LocationName).ThenBy(a => a.GroupName).ToList());
            }

            var checkedInCountField  = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lCheckedInCount");
            var presentCountField    = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lPresentCount");
            var checkedOutCountField = gRoomList.ColumnsOfType <RockLiteralField>().FirstOrDefault(a => a.ID == "lCheckedOutCount");

            checkedOutCountField.Visible = groupTypeIdsWithAllowCheckout.Any();

            // Always show Present Count regardless of the 'Enable Presence' setting. (A person gets automatically marked present if 'Enable Presence' is disabled.)
            presentCountField.Visible = true;
            if (groupTypeIdsWithEnablePresence.Any())
            {
                // Presence is enabled, so records could be in the 'Checked-in' state
                // and Present column should be labeled 'Present'.
                checkedInCountField.Visible  = true;
                presentCountField.HeaderText = "Present";
            }
            else
            {
                // https://app.asana.com/0/0/1199637795718017/f
                // 'Enable Presence' is disabled, so a person automatically gets marked present.
                // So, no records will be in the 'Checked-In (but no present)' state.
                // Also, a user thinks of 'Present' as 'Checked-In' if they don't use the 'Enable Presence' feature
                checkedInCountField.Visible  = false;
                presentCountField.HeaderText = "Checked-In";
            }

            if (_showOnlyParentGroup)
            {
                gRoomList.DataKeyNames = new string[1] {
                    "LocationId"
                };
            }
            else
            {
                gRoomList.DataKeyNames = new string[2] {
                    "LocationId", "GroupId"
                };
            }

            gRoomList.DataSource = sortedRoomList;
            gRoomList.DataBind();
        }
Example #12
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)
        {
            Location location;

            var                       rockContext               = new RockContext();
            LocationService           locationService           = new LocationService(rockContext);
            AttributeService          attributeService          = new AttributeService(rockContext);
            AttributeQualifierService attributeQualifierService = new AttributeQualifierService(rockContext);

            int locationId = int.Parse(hfLocationId.Value);

            if (locationId == 0)
            {
                location      = new Location();
                location.Name = string.Empty;
            }
            else
            {
                location = locationService.Get(locationId);
                FlushCampus(locationId);
            }

            int?orphanedImageId = null;

            if (location.ImageId != imgImage.BinaryFileId)
            {
                orphanedImageId  = location.ImageId;
                location.ImageId = imgImage.BinaryFileId;
            }

            location.Name                = tbName.Text;
            location.IsActive            = cbIsActive.Checked;
            location.LocationTypeValueId = ddlLocationType.SelectedValueAsId();
            if (gpParentLocation != null && gpParentLocation.Location != null)
            {
                location.ParentLocationId = gpParentLocation.Location.Id;
            }
            else
            {
                location.ParentLocationId = null;
            }

            location.PrinterDeviceId = ddlPrinter.SelectedValueAsInt();

            acAddress.GetValues(location);

            location.GeoPoint = geopPoint.SelectedValue;
            if (geopPoint.SelectedValue != null)
            {
                location.IsGeoPointLocked = true;
            }
            location.GeoFence = geopFence.SelectedValue;

            location.IsGeoPointLocked = cbGeoPointLocked.Checked;

            location.LoadAttributes(rockContext);
            Rock.Attribute.Helper.GetEditValues(phAttributeEdits, location);

            if (!Page.IsValid)
            {
                return;
            }

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

            rockContext.WrapTransaction(() =>
            {
                if (location.Id.Equals(0))
                {
                    locationService.Add(location);
                }
                rockContext.SaveChanges();

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

                location.SaveAttributeValues(rockContext);
            });



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

            qryParams["LocationId"]  = location.Id.ToString();
            qryParams["ExpandedIds"] = PageParameter("ExpandedIds");

            NavigateToPage(RockPage.Guid, qryParams);
        }
Example #13
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);

            // #TODO test card through gateway

            if (btnFrequency.SelectedIndex > -1 && btnFrequency.SelectedValueAsInt() > 0)
            {
                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();
        }
 public void Add(SaveLocationMessage message)
 {
     _locationService.Add(message);
 }