Exemplo n.º 1
0
        /// <summary>
        /// Creates a Linq Expression that can be applied to an IQueryable to filter the result set.
        /// </summary>
        /// <param name="entityType">The type of entity in the result set.</param>
        /// <param name="serviceInstance">A service instance that can be queried to obtain the result set.</param>
        /// <param name="parameterExpression">The input parameter that will be injected into the filter expression.</param>
        /// <param name="selection">A formatted string representing the filter settings.</param>
        /// <returns>
        /// A Linq Expression that can be used to filter an IQueryable.
        /// </returns>
        /// <exception cref="System.Exception">Filter issue(s):  + errorMessages.AsDelimited( ;  )</exception>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            var settings = new FilterSettings(selection);

            var context = ( RockContext )serviceInstance.Context;

            var locationService = new LocationService(context);
            var locationQuery   = locationService.Queryable();

            if (locationQuery != null)
            {
                if (!string.IsNullOrWhiteSpace(settings.Street1))
                {
                    locationQuery = locationQuery.Where(l => l.Street1.Contains(settings.Street1));
                }

                if (!string.IsNullOrWhiteSpace(settings.City))
                {
                    locationQuery = locationQuery.Where(l => l.City == settings.City);
                }

                if (!string.IsNullOrWhiteSpace(settings.State))
                {
                    locationQuery = locationQuery.Where(l => l.State == settings.State);
                }

                if (!string.IsNullOrWhiteSpace(settings.PostalCode))
                {
                    locationQuery = locationQuery.Where(l => l.PostalCode.StartsWith(settings.PostalCode));
                }

                if (!string.IsNullOrWhiteSpace(settings.Country))
                {
                    locationQuery = locationQuery.Where(l => l.Country == settings.Country);
                }
            }

            // Get all the Family Groups that have a Location matching one of the candidate Locations.
            int familyGroupTypeId = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

            var groupLocationsQuery = new GroupLocationService(context).Queryable()
                                      .Where(gl => gl.Group.GroupTypeId == familyGroupTypeId && locationQuery.Any(l => l.Id == gl.LocationId));

            // If a Location Type is specified, apply the filter condition.
            if (settings.LocationTypeGuid.HasValue)
            {
                int groupLocationTypeId = DefinedValueCache.Read(settings.LocationTypeGuid.Value).Id;
                groupLocationsQuery = groupLocationsQuery.Where(x => x.GroupLocationTypeValue.Id == groupLocationTypeId);
            }

            // Get all of the Group Members of the qualifying Families.
            var groupMemberServiceQry = new GroupMemberService(context).Queryable()
                                        .Where(gm => groupLocationsQuery.Any(gl => gl.GroupId == gm.GroupId));

            // Get all of the People corresponding to the qualifying Group Members.
            var qry = new PersonService(context).Queryable()
                      .Where(p => groupMemberServiceQry.Any(gm => gm.PersonId == p.Id));

            // Retrieve the Filter Expression.
            var extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p");

            return(extractedFilterExpression);
        }
Exemplo n.º 2
0
        private void DisplayResults()
        {
            RockContext rockContext = new RockContext();

            var statementYear = RockDateTime.Now.Year;

            if (Request["StatementYear"] != null)
            {
                Int32.TryParse(Request["StatementYear"].ToString(), out statementYear);
            }

            FinancialTransactionDetailService financialTransactionDetailService = new FinancialTransactionDetailService(rockContext);

            Person targetPerson = CurrentPerson;

            List <Guid> excludedCurrencyTypes = new List <Guid>();

            if (!string.IsNullOrWhiteSpace(GetAttributeValue("ExcludedCurrencyTypes")))
            {
                excludedCurrencyTypes = GetAttributeValue("ExcludedCurrencyTypes").Split(',').Select(Guid.Parse).ToList();
            }

            if (GetAttributeValue("AllowPersonQuerystring").AsBoolean())
            {
                if (!string.IsNullOrWhiteSpace(Request["PersonGuid"]))
                {
                    Guid?personGuid = Request["PersonGuid"].AsGuidOrNull();

                    if (personGuid.HasValue)
                    {
                        var person = new PersonService(rockContext).Get(personGuid.Value);
                        if (person != null)
                        {
                            targetPerson = person;
                        }
                    }
                }
            }

            var qry = financialTransactionDetailService.Queryable().AsNoTracking()
                      .Where(t => t.Transaction.AuthorizedPersonAlias.Person.GivingId == targetPerson.GivingId);

            qry = qry.Where(t => t.Transaction.TransactionDateTime.Value.Year == statementYear);

            if (string.IsNullOrWhiteSpace(GetAttributeValue("Accounts")))
            {
                qry = qry.Where(t => t.Account.IsTaxDeductible);
            }
            else
            {
                var accountGuids = GetAttributeValue("Accounts").Split(',').Select(Guid.Parse).ToList();
                qry = qry.Where(t => accountGuids.Contains(t.Account.Guid));
            }

            if (excludedCurrencyTypes.Count > 0)
            {
                qry = qry.Where(t => !excludedCurrencyTypes.Contains(t.Transaction.FinancialPaymentDetail.CurrencyTypeValue.Guid));
            }

            qry = qry.OrderByDescending(t => t.Transaction.TransactionDateTime);

            var mergeFields = new Dictionary <string, object>();

            mergeFields.Add("StatementStartDate", "1/1/" + statementYear.ToString());
            if (statementYear == RockDateTime.Now.Year)
            {
                mergeFields.Add("StatementEndDate", RockDateTime.Now);
            }
            else
            {
                mergeFields.Add("StatementEndDate", "12/31/" + statementYear.ToString());
            }

            var familyGroupTypeId = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY).Id;
            var groupMemberQry    = new GroupMemberService(rockContext).Queryable().Where(m => m.Group.GroupTypeId == familyGroupTypeId);

            // get giving group members in order by family role (adult -> child) and then gender (male -> female)
            var givingGroup = new PersonService(rockContext).Queryable().AsNoTracking()
                              .Where(p => p.GivingId == targetPerson.GivingId)
                              .GroupJoin(
                groupMemberQry,
                p => p.Id,
                m => m.PersonId,
                (p, m) => new { p, m })
                              .SelectMany(x => x.m.DefaultIfEmpty(), (y, z) => new { Person = y.p, GroupMember = z })
                              .Select(p => new { FirstName = p.Person.NickName, LastName = p.Person.LastName, FamilyRoleOrder = p.GroupMember.GroupRole.Order, Gender = p.Person.Gender, PersonId = p.Person.Id })
                              .DistinctBy(p => p.PersonId)
                              .OrderBy(p => p.FamilyRoleOrder).ThenBy(p => p.Gender)
                              .ToList();

            string salutation = string.Empty;

            if (givingGroup.GroupBy(g => g.LastName).Count() == 1)
            {
                salutation = string.Join(", ", givingGroup.Select(g => g.FirstName)) + " " + givingGroup.FirstOrDefault().LastName;
                if (salutation.Contains(","))
                {
                    salutation = salutation.ReplaceLastOccurrence(",", " &");
                }
            }
            else
            {
                salutation = string.Join(", ", givingGroup.Select(g => g.FirstName + " " + g.LastName));
                if (salutation.Contains(","))
                {
                    salutation = salutation.ReplaceLastOccurrence(",", " &");
                }
            }
            mergeFields.Add("Salutation", salutation);

            var homeAddress = targetPerson.GetHomeLocation();

            if (homeAddress != null)
            {
                mergeFields.Add("StreetAddress1", homeAddress.Street1);
                mergeFields.Add("StreetAddress2", homeAddress.Street2);
                mergeFields.Add("City", homeAddress.City);
                mergeFields.Add("State", homeAddress.State);
                mergeFields.Add("PostalCode", homeAddress.PostalCode);
                mergeFields.Add("Country", homeAddress.Country);
            }
            else
            {
                mergeFields.Add("StreetAddress1", string.Empty);
                mergeFields.Add("StreetAddress2", string.Empty);
                mergeFields.Add("City", string.Empty);
                mergeFields.Add("State", string.Empty);
                mergeFields.Add("PostalCode", string.Empty);
                mergeFields.Add("Country", string.Empty);
            }

            mergeFields.Add("TransactionDetails", qry.ToList());

            mergeFields.Add("AccountSummary", qry.GroupBy(t => t.Account.Name).Select(s => new AccountSummary {
                AccountName = s.Key, Total = s.Sum(a => a.Amount), Order = s.Max(a => a.Account.Order)
            }).OrderBy(s => s.Order));

            // pledge information
            var pledges = new FinancialPledgeService(rockContext).Queryable().AsNoTracking()
                          .Where(p =>
                                 p.PersonAlias.Person.GivingId == targetPerson.GivingId &&
                                 (p.StartDate.Year == statementYear || p.EndDate.Year == statementYear))
                          .GroupBy(p => p.Account)
                          .Select(g => new PledgeSummary
            {
                AccountId       = g.Key.Id,
                AccountName     = g.Key.Name,
                AmountPledged   = g.Sum(p => p.TotalAmount),
                PledgeStartDate = g.Min(p => p.StartDate),
                PledgeEndDate   = g.Max(p => p.EndDate)
            })
                          .ToList();

            // add detailed pledge information
            foreach (var pledge in pledges)
            {
                var adjustedPedgeEndDate = pledge.PledgeEndDate.Value.Date.AddHours(23).AddMinutes(59).AddSeconds(59);
                pledge.AmountGiven = new FinancialTransactionDetailService(rockContext).Queryable()
                                     .Where(t =>
                                            t.AccountId == pledge.AccountId &&
                                            t.Transaction.TransactionDateTime >= pledge.PledgeStartDate &&
                                            t.Transaction.TransactionDateTime <= adjustedPedgeEndDate)
                                     .Sum(t => t.Amount);

                pledge.AmountRemaining = (pledge.AmountGiven > pledge.AmountPledged) ? 0 : (pledge.AmountPledged - pledge.AmountGiven);

                if (pledge.AmountPledged > 0)
                {
                    var test = (double)pledge.AmountGiven / (double)pledge.AmountPledged;
                    pledge.PercentComplete = (int)((pledge.AmountGiven * 100) / pledge.AmountPledged);
                }
            }

            mergeFields.Add("Pledges", pledges);

            var template = GetAttributeValue("LavaTemplate");

            lResults.Text = template.ResolveMergeFields(mergeFields);

            // show debug info
            if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
            {
                lDebug.Visible = true;
                lDebug.Text    = mergeFields.lavaDebugInfo();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Shows the details.
        /// </summary>
        private void ShowDetails()
        {
            RockContext rockContext = new RockContext();

            pnlAddress.Visible = GetAttributeValue("ShowAddress").AsBoolean();
            acAddress.Required = GetAttributeValue("AddressRequired").AsBoolean();

            var person = CurrentPerson;

            if (person != null)
            {
                imgPhoto.BinaryFileId            = person.PhotoId;
                imgPhoto.NoPictureUrl            = Person.GetPersonNoPictureUrl(person, 200, 200);
                ddlTitle.SelectedValue           = person.TitleValueId.HasValue ? person.TitleValueId.Value.ToString() : string.Empty;
                tbFirstName.Text                 = person.FirstName;
                tbNickName.Text                  = person.NickName;
                tbLastName.Text                  = person.LastName;
                ddlSuffix.SelectedValue          = person.SuffixValueId.HasValue ? person.SuffixValueId.Value.ToString() : string.Empty;
                bpBirthDay.SelectedDate          = person.BirthDate;
                rblGender.SelectedValue          = person.Gender.ConvertToString();
                tbEmail.Text                     = person.Email;
                rblEmailPreference.SelectedValue = person.EmailPreference.ConvertToString(false);

                Guid?locationTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                if (locationTypeGuid.HasValue)
                {
                    var addressTypeDv = DefinedValueCache.Read(locationTypeGuid.Value);

                    // if address type is home enable the move and is mailing/physical
                    if (addressTypeDv.Guid == Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid())
                    {
                        lbMoved.Visible             = true;
                        cbIsMailingAddress.Visible  = true;
                        cbIsPhysicalAddress.Visible = true;
                    }
                    else
                    {
                        lbMoved.Visible             = false;
                        cbIsMailingAddress.Visible  = false;
                        cbIsPhysicalAddress.Visible = false;
                    }

                    lAddressTitle.Text = addressTypeDv.Value + " Address";

                    var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();

                    if (familyGroupTypeGuid.HasValue)
                    {
                        var familyGroupType = GroupTypeCache.Read(familyGroupTypeGuid.Value);

                        var familyAddress = new GroupLocationService(rockContext).Queryable()
                                            .Where(l => l.Group.GroupTypeId == familyGroupType.Id &&
                                                   l.GroupLocationTypeValueId == addressTypeDv.Id &&
                                                   l.Group.Members.Any(m => m.PersonId == person.Id))
                                            .FirstOrDefault();
                        if (familyAddress != null)
                        {
                            acAddress.SetValues(familyAddress.Location);

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

                var mobilePhoneType = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE));

                var phoneNumbers     = new List <PhoneNumber>();
                var phoneNumberTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE));
                if (phoneNumberTypes.DefinedValues.Any())
                {
                    foreach (var phoneNumberType in phoneNumberTypes.DefinedValues)
                    {
                        var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberType.Id);
                        if (phoneNumber == null)
                        {
                            var numberType = new DefinedValue();
                            numberType.Id    = phoneNumberType.Id;
                            numberType.Value = phoneNumberType.Value;

                            phoneNumber = new PhoneNumber {
                                NumberTypeValueId = numberType.Id, NumberTypeValue = numberType
                            };
                            phoneNumber.IsMessagingEnabled = mobilePhoneType != null && phoneNumberType.Id == mobilePhoneType.Id;
                        }
                        else
                        {
                            // Update number format, just in case it wasn't saved correctly
                            phoneNumber.NumberFormatted = PhoneNumber.FormattedNumber(phoneNumber.CountryCode, phoneNumber.Number);
                        }

                        phoneNumbers.Add(phoneNumber);
                    }

                    rContactInfo.DataSource = phoneNumbers;
                    rContactInfo.DataBind();
                }
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="KioskGroupType"/> class.
 /// </summary>
 /// <param name="groupTypeid">The group typeid.</param>
 public KioskGroupType(int groupTypeid)
     : base()
 {
     GroupType   = GroupTypeCache.Read(groupTypeid);
     KioskGroups = new List <KioskGroup>();
 }
Exemplo n.º 5
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            //
            // Verify we have at least one domain name entered.
            //
            if (vlDomains.Value.SplitDelimitedValues().Length == 0)
            {
                nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning;
                nbMessage.Text = "You must enter at least one domain to vaidate.";

                return;
            }

            //
            // Verify we have at least one binding configured.
            // TODO: This should probably be removed so offline mode will work correctly.
            //
            if (BindingsState.Count == 0)
            {
                nbMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning;
                nbMessage.Text = "You must add at least one IIS binding.";

                return;
            }

            //
            // Load the existing data or create a new entry.
            //
            var rockContext  = new RockContext();
            var groupService = new GroupService(rockContext);
            var group        = groupService.Get(PageParameter("Id").AsInteger());

            if (group == null)
            {
                group             = new Group();
                group.GroupTypeId = GroupTypeCache.Read(com.blueboxmoon.AcmeCertificate.SystemGuid.GroupType.ACME_CERTIFICATES).Id;

                groupService.Add(group);
            }

            group.LoadAttributes(rockContext);

            //
            // Store the data.
            //
            group.Name = tbFriendlyName.Text;
            group.SetAttributeValue("RemoveOldCertificate", cbRemoveOldCertificate.Checked.ToString());
            group.SetAttributeValue("Domains", vlDomains.Value);
            group.SetAttributeValue("Bindings", string.Join("|", BindingsState));

            //
            // Save all the information.
            //
            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();

                group.SaveAttributeValues(rockContext);
            });

            NavigateToParentPage();
        }
Exemplo n.º 6
0
        /// <summary>
        /// Handles a recieved message
        /// </summary>
        /// <param name="toPhone">To phone.</param>
        /// <param name="fromPhone">From phone.</param>
        /// <param name="message">The message.</param>
        /// <param name="response">The response.</param>
        public static void MessageRecieved(string toPhone, string fromPhone, string message, out string response)
        {
            response = string.Empty;
            bool foundWorkflow = false;

            // get TextToWorkflow defined types for this number
            var definedType = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.TEXT_TO_WORKFLOW.AsGuid());

            if (definedType != null && definedType.DefinedValues != null && definedType.DefinedValues.Any())
            {
                var smsWorkflows = definedType.DefinedValues.Where(v => v.Value.AsNumeric() == toPhone.AsNumeric()).OrderBy(v => v.Order).ToList();

                // iterate through workflows looking for a keyword match
                foreach (DefinedValueCache dvWorkflow in smsWorkflows)
                {
                    string keywordExpression  = dvWorkflow.GetAttributeValue("KeywordExpression");
                    string workflowAttributes = dvWorkflow.GetAttributeValue("WorkflowAttributes");
                    string nameTemplate       = dvWorkflow.GetAttributeValue("WorkflowNameTemplate");

                    // if not keyword expression add wildcard expression
                    if (string.IsNullOrWhiteSpace(keywordExpression))
                    {
                        keywordExpression = ".*";
                    }

                    // if the keyword is just a * then replace it
                    if (keywordExpression == "*")
                    {
                        keywordExpression = ".*";
                    }

                    // Prefix keyword with start-of-string assertion (input needs to start with selected expression)
                    if (!keywordExpression.StartsWith("^"))
                    {
                        keywordExpression = $"^{keywordExpression}";
                    }

                    if (!string.IsNullOrWhiteSpace(keywordExpression))
                    {
                        Match match = Regex.Match(message, keywordExpression, RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            foundWorkflow = true;

                            var workflowTypeGuid = dvWorkflow.GetAttributeValue("WorkflowType").AsGuidOrNull();
                            if (workflowTypeGuid.HasValue)
                            {
                                // launch workflow
                                using (var rockContext = new Data.RockContext())
                                {
                                    var personService      = new PersonService(rockContext);
                                    var groupMemberService = new GroupMemberService(rockContext);

                                    var workflowType = WorkflowTypeCache.Read(workflowTypeGuid.Value);
                                    if (workflowType != null)
                                    {
                                        // Activate a new workflow
                                        var workflow = Rock.Model.Workflow.Activate(workflowType, "Request from " + (fromPhone ?? "??"), rockContext);

                                        // give preference to people with the phone in the mobile phone type
                                        // first look for a person with the phone number as a mobile phone order by family role then age
                                        var mobilePhoneType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE);
                                        var familyGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);

                                        // Get all people phone number
                                        var peopleWithMobileNumber = personService.Queryable()
                                                                     .Where(p =>
                                                                            p.PhoneNumbers.Any(n =>
                                                                                               (n.CountryCode + n.Number) == fromPhone.Replace("+", "") &&
                                                                                               n.NumberTypeValueId == mobilePhoneType.Id)
                                                                            )
                                                                     .Select(p => p.Id);

                                        // Find first person ordered by role (adult first), then by birthdate (oldest first)
                                        var fromPerson = groupMemberService.Queryable()
                                                         .Where(m =>
                                                                m.Group.GroupTypeId == familyGroupType.Id &&
                                                                peopleWithMobileNumber.Contains(m.PersonId))
                                                         .OrderBy(m => m.GroupRole.Order)
                                                         .ThenBy(m => m.Person.BirthDate ?? DateTime.MinValue)
                                                         .Select(m => m.Person)
                                                         .FirstOrDefault();

                                        // if no match then look for the phone in any phone type ordered by family role then age
                                        if (fromPerson == null)
                                        {
                                            var peopleWithAnyNumber = personService.Queryable()
                                                                      .Where(p =>
                                                                             p.PhoneNumbers.Any(n =>
                                                                                                (n.CountryCode + n.Number) == fromPhone.Replace("+", "") &&
                                                                                                n.NumberTypeValueId == mobilePhoneType.Id)
                                                                             )
                                                                      .Select(p => p.Id);

                                            fromPerson = groupMemberService.Queryable()
                                                         .Where(m =>
                                                                m.Group.GroupTypeId == familyGroupType.Id &&
                                                                peopleWithMobileNumber.Contains(m.PersonId))
                                                         .OrderBy(m => m.GroupRole.Order)
                                                         .ThenBy(m => m.Person.BirthDate ?? DateTime.MinValue)
                                                         .Select(m => m.Person).FirstOrDefault();
                                        }

                                        // Set initiator
                                        if (fromPerson != null)
                                        {
                                            workflow.InitiatorPersonAliasId = fromPerson.PrimaryAliasId;
                                        }

                                        // create merge object
                                        var formattedPhoneNumber = PhoneNumber.CleanNumber(PhoneNumber.FormattedNumber(PhoneNumber.DefaultCountryCode(), fromPhone));

                                        List <string> matchGroups = new List <string>();
                                        foreach (var matchItem in match.Groups)
                                        {
                                            matchGroups.Add(matchItem.ToString());
                                        }

                                        Dictionary <string, object> mergeValues = new Dictionary <string, object>();
                                        mergeValues.Add("FromPhone", formattedPhoneNumber);
                                        mergeValues.Add("ToPhone", toPhone);
                                        mergeValues.Add("MessageBody", message);
                                        mergeValues.Add("MatchedGroups", matchGroups);
                                        mergeValues.Add("ReceivedTime", RockDateTime.Now.ToString("HH:mm:ss"));
                                        mergeValues.Add("ReceivedDate", RockDateTime.Now.ToShortDateString());
                                        mergeValues.Add("ReceivedDateTime", RockDateTime.Now.ToString("o"));
                                        mergeValues.Add("FromPerson", fromPerson);

                                        // add phone number attribute
                                        workflow.SetAttributeValue("FromPhone", fromPhone);

                                        // set workflow attributes
                                        string[] attributes = workflowAttributes.Split('|');
                                        foreach (string attribute in attributes)
                                        {
                                            if (attribute.Contains('^'))
                                            {
                                                string[] settings = attribute.Split('^');
                                                workflow.SetAttributeValue(settings[0], settings[1].ResolveMergeFields(mergeValues));
                                            }
                                        }

                                        // set workflow name
                                        string name = nameTemplate.ResolveMergeFields(mergeValues);
                                        if (name.IsNotNullOrWhitespace())
                                        {
                                            workflow.Name = name;
                                        }

                                        // process the workflow
                                        List <string> workflowErrors;
                                        new Rock.Model.WorkflowService(rockContext).Process(workflow, out workflowErrors);

                                        // check to see if there is a response to return
                                        string responseAttribute = workflow.GetAttributeValue("SMSResponse");
                                        if (responseAttribute != null && !string.IsNullOrWhiteSpace(responseAttribute))
                                        {
                                            response = responseAttribute;
                                        }
                                    }
                                    else
                                    {
                                        response = "This keyword is no longer valid.";
                                    }
                                }
                            }
                            else
                            {
                                response = "No response could be provided for this keyword.";
                            }


                            // once we find one match stop processing
                            break;
                        }
                    }
                }

                if (!foundWorkflow)
                {
                    response = "The keyword you provided was not valid. ";
                }
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    var commonMergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null);
                    var attendanceService = new AttendanceService(rockContext);

                    foreach (var person in family.CheckOutPeople.Where(p => p.Selected))
                    {
                        person.Labels = new List <CheckInLabel>();

                        var attendanceRecs = attendanceService
                                             .Queryable().AsNoTracking()
                                             .Where(a =>
                                                    person.AttendanceIds.Contains(a.Id) &&
                                                    a.PersonAlias != null &&
                                                    a.PersonAlias.Person != null &&
                                                    a.Group != null &&
                                                    a.Location != null)
                                             .ToList();

                        foreach (var attendanceRec in attendanceRecs)
                        {
                            var key = string.Format("{0}:{1}", attendanceRec.Group.Id, attendanceRec.Location.Id);
                            if (!person.Labels.Any(l => l.LabelKey.StartsWith(key)))
                            {
                                var groupType = GroupTypeCache.Read(attendanceRec.Group.GroupTypeId);
                                if (groupType != null)
                                {
                                    var groupLocAttendance = attendanceRecs
                                                             .Where(a =>
                                                                    a.GroupId.HasValue &&
                                                                    a.GroupId == attendanceRec.Group.Id &&
                                                                    a.LocationId.HasValue &&
                                                                    a.LocationId == attendanceRec.Location.Id)
                                                             .ToList();

                                    var PrinterIPs = new Dictionary <int, string>();

                                    var groupTypeLabels = GetGroupTypeLabels(groupType);

                                    foreach (var labelCache in groupTypeLabels.OrderBy(l => l.LabelType).ThenBy(l => l.Order))
                                    {
                                        var mergeObjects = new Dictionary <string, object>();
                                        foreach (var keyValue in commonMergeFields)
                                        {
                                            mergeObjects.Add(keyValue.Key, keyValue.Value);
                                        }
                                        mergeObjects.Add("Attendances", groupLocAttendance);
                                        mergeObjects.Add("Person", attendanceRec.PersonAlias.Person);
                                        mergeObjects.Add("GroupType", groupType);
                                        mergeObjects.Add("Group", attendanceRec.Group);
                                        mergeObjects.Add("Location", attendanceRec.Location);

                                        //string debugInfo = mergeObjects.lavaDebugInfo();
                                        var label = new CheckInLabel(labelCache, mergeObjects, person.Person.Id);
                                        label.LabelKey  = string.Format("{0}:{1}:{2}", attendanceRec.Group.Id, attendanceRec.Location.Id, labelCache.Guid);
                                        label.FileGuid  = labelCache.Guid;
                                        label.PrintFrom = checkInState.Kiosk.Device.PrintFrom;

                                        if (label.PrintTo == PrintTo.Default)
                                        {
                                            label.PrintTo = groupType.AttendancePrintTo;
                                        }

                                        if (label.PrintTo == PrintTo.Kiosk)
                                        {
                                            var device = checkInState.Kiosk.Device;
                                            if (device != null)
                                            {
                                                label.PrinterDeviceId = device.PrinterDeviceId;
                                            }
                                        }
                                        else if (label.PrintTo == PrintTo.Location)
                                        {
                                            var deviceId = attendanceRec.Location.PrinterDeviceId;
                                            if (deviceId != null)
                                            {
                                                label.PrinterDeviceId = deviceId;
                                            }
                                        }

                                        if (label.PrinterDeviceId.HasValue)
                                        {
                                            if (PrinterIPs.ContainsKey(label.PrinterDeviceId.Value))
                                            {
                                                label.PrinterAddress = PrinterIPs[label.PrinterDeviceId.Value];
                                            }
                                            else
                                            {
                                                var printerDevice = new DeviceService(rockContext).Get(label.PrinterDeviceId.Value);
                                                if (printerDevice != null)
                                                {
                                                    PrinterIPs.Add(printerDevice.Id, printerDevice.IPAddress);
                                                    label.PrinterAddress = printerDevice.IPAddress;
                                                }
                                            }
                                        }

                                        person.Labels.Add(label);
                                    }
                                }
                            }
                        }
                    }
                }

                return(true);
            }

            return(false);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CheckinType"/> class.
 /// </summary>
 /// <param name="checkinTypeId">The checkin type identifier.</param>
 public CheckinType(int checkinTypeId)
 {
     _checkinType = GroupTypeCache.Read(checkinTypeId);
 }
Exemplo n.º 9
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            // Find all the Group Types
            var groupTypeIds = GetAvailableGroupTypes();

            if (GetAttributeValue("DisplayFilter").AsBooleanOrNull() ?? false)
            {
                int?groupTypeFilter = gfSettings.GetUserPreference("Group Type").AsIntegerOrNull();
                if (groupTypeFilter.HasValue)
                {
                    groupTypeIds = groupTypeIds.Where(g => g == groupTypeFilter.Value).ToList();
                }
            }

            var rockContext  = new RockContext();
            var groupService = new GroupService(rockContext);

            SortProperty sortProperty = gGroups.SortProperty;

            if (sortProperty == null)
            {
                sortProperty = new SortProperty(new GridViewSortEventArgs("IsActiveOrder, GroupTypeOrder, GroupTypeName, GroupOrder, Name", SortDirection.Ascending));
            }

            bool onlySecurityGroups = GetAttributeValue("LimittoSecurityRoleGroups").AsBoolean();

            var qryGroups = groupService.Queryable()
                            .Where(g => groupTypeIds.Contains(g.GroupTypeId) && (!onlySecurityGroups || g.IsSecurityRole));

            string limitToActiveStatus = GetAttributeValue("LimittoActiveStatus");

            bool showActive   = true;
            bool showInactive = true;

            if (limitToActiveStatus == "all" && gfSettings.Visible)
            {
                // Filter by active/inactive unless the block settings restrict it
                if (ddlActiveFilter.SelectedIndex > -1)
                {
                    switch (ddlActiveFilter.SelectedValue)
                    {
                    case "active":
                        showInactive = false;
                        break;

                    case "inactive":
                        showActive = false;
                        break;
                    }
                }
            }
            else if (limitToActiveStatus != "all")
            {
                // filter by the block setting for Active Status
                if (limitToActiveStatus == "active")
                {
                    showInactive = false;
                }
            }

            var groupList = new List <GroupListRowInfo>();

            // Person context will exist if used on a person detail page
            int personEntityTypeId = EntityTypeCache.Read("Rock.Model.Person").Id;

            if (ContextTypesRequired.Any(e => e.Id == personEntityTypeId))
            {
                var personContext = ContextEntity <Person>();
                if (personContext != null)
                {
                    // limit to Groups that the person is a member of
                    var qry = new GroupMemberService(rockContext).Queryable(true)
                              .Where(m => m.PersonId == personContext.Id)
                              .Join(qryGroups, gm => gm.GroupId, g => g.Id, (gm, g) => new { Group = g, GroupMember = gm });

                    // Filter by Active Status of Group and Group Membership.
                    if (showActive && !showInactive)
                    {
                        // Show only active Groups and active Memberships.
                        qry = qry.Where(gmg => gmg.Group.IsActive && gmg.GroupMember.GroupMemberStatus == GroupMemberStatus.Active);
                    }
                    else if (!showActive)
                    {
                        // Show only inactive Groups or inactive Memberships.
                        qry = qry.Where(gmg => !gmg.Group.IsActive || gmg.GroupMember.GroupMemberStatus == GroupMemberStatus.Inactive);
                    }

                    groupList = qry
                                .Select(m => new GroupListRowInfo {
                        Id             = m.Group.Id,
                        Path           = string.Empty,
                        Name           = m.Group.Name,
                        GroupTypeName  = m.Group.GroupType.Name,
                        GroupOrder     = m.Group.Order,
                        GroupTypeOrder = m.Group.GroupType.Order,
                        Description    = m.Group.Description,
                        IsSystem       = m.Group.IsSystem,
                        GroupRole      = m.GroupMember.GroupRole.Name,
                        DateAdded      = m.GroupMember.CreatedDateTime,
                        IsActive       = m.Group.IsActive && (m.GroupMember.GroupMemberStatus == GroupMemberStatus.Active),
                        IsActiveOrder  = (m.Group.IsActive && (m.GroupMember.GroupMemberStatus == GroupMemberStatus.Active) ? 1 : 2),
                        MemberCount    = 0
                    })
                                .Sort(sortProperty)
                                .ToList();
                }
            }
            else
            {
                var  roleGroupType   = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid());
                int  roleGroupTypeId = roleGroupType != null ? roleGroupType.Id : 0;
                bool useRolePrefix   = onlySecurityGroups || groupTypeIds.Contains(roleGroupTypeId);

                if (!showInactive)
                {
                    qryGroups = qryGroups.Where(x => x.IsActive);
                }
                else if (!showActive)
                {
                    qryGroups = qryGroups.Where(x => !x.IsActive);
                }

                groupList = qryGroups
                            .Select(g => new GroupListRowInfo {
                    Id             = g.Id,
                    Path           = string.Empty,
                    Name           = ((useRolePrefix && g.GroupType.Id != roleGroupTypeId) ? "GROUP - " : "") + g.Name,
                    GroupTypeName  = g.GroupType.Name,
                    GroupOrder     = g.Order,
                    GroupTypeOrder = g.GroupType.Order,
                    Description    = g.Description,
                    IsSystem       = g.IsSystem,
                    IsActive       = g.IsActive,
                    IsActiveOrder  = g.IsActive ? 1 : 2,
                    GroupRole      = string.Empty,
                    DateAdded      = DateTime.MinValue,
                    MemberCount    = g.Members.Count()
                })
                            .Sort(sortProperty)
                            .ToList();
            }

            if (_showGroupPath)
            {
                foreach (var groupRow in groupList)
                {
                    groupRow.Path = groupService.GroupAncestorPathName(groupRow.Id);
                }
            }

            gGroups.DataSource   = groupList;
            gGroups.EntityTypeId = EntityTypeCache.Read <Group>().Id;
            gGroups.DataBind();

            // hide the group type column if there's only one type; must come after DataBind()
            if (_groupTypesCount == 1)
            {
                this.gGroups.Columns[1].Visible = false;
            }
        }
Exemplo n.º 10
0
        /// <summary>
        /// Pres the save changes.
        /// </summary>
        /// <param name="dbContext">The database context.</param>
        /// <param name="state">The state.</param>
        public override void PreSaveChanges(Rock.Data.DbContext dbContext, System.Data.Entity.EntityState state)
        {
            try
            {
                string verb   = string.Empty;
                string action = string.Empty;

                var   rockContext = (RockContext)dbContext;
                Group group       = null;

                if (state == System.Data.Entity.EntityState.Added)
                {
                    verb   = "ADD";
                    action = "Added to group.";
                    if (!this.DateTimeAdded.HasValue)
                    {
                        this.DateTimeAdded = RockDateTime.Now;
                    }
                }
                else if (state == System.Data.Entity.EntityState.Modified)
                {
                    verb = "UPDATE";

                    var changeEntry = dbContext.ChangeTracker.Entries <GroupMember>().Where(a => a.Entity == this).FirstOrDefault();
                    if (changeEntry != null)
                    {
                        var origGroupMemberStatus = (GroupMemberStatus)changeEntry.OriginalValues["GroupMemberStatus"];
                        if (origGroupMemberStatus != this.GroupMemberStatus)
                        {
                            action = string.Format("Group member status changed from {0} to {1}", origGroupMemberStatus.ToString(), this.GroupMemberStatus.ToString());
                        }

                        var origGroupRoleId = (int)changeEntry.OriginalValues["GroupRoleId"];
                        if (origGroupRoleId != this.GroupRoleId)
                        {
                            if (group == null)
                            {
                                group = this.Group;
                            }
                            if (group == null)
                            {
                                group = new GroupService(rockContext).Get(this.GroupId);
                            }
                            if (group != null)
                            {
                                var groupType = GroupTypeCache.Read(group.GroupTypeId);
                                if (groupType != null)
                                {
                                    var origRole = groupType.Roles.FirstOrDefault(r => r.Id == origGroupRoleId);
                                    var newRole  = groupType.Roles.FirstOrDefault(r => r.Id == this.GroupRoleId);
                                    action = string.Format("Group role changed from {0} to {1}",
                                                           (origRole != null ? origRole.Name : "??"),
                                                           (newRole != null ? newRole.Name : "??"));
                                }
                            }
                        }
                    }
                }
                else if (state == System.Data.Entity.EntityState.Deleted)
                {
                    verb   = "DELETE";
                    action = "Removed from group.";
                }

                // process universal search indexing if required
                if (group == null)
                {
                    group = this.Group;
                }
                if (group == null)
                {
                    group = new GroupService(rockContext).Get(this.GroupId);
                }
                if (group != null)
                {
                    var groupType = GroupTypeCache.Read(group.GroupTypeId);
                    if (groupType != null)
                    {
                        if (groupType.IsIndexEnabled)
                        {
                            IndexEntityTransaction transaction = new IndexEntityTransaction();
                            transaction.EntityTypeId = groupType.Id;
                            transaction.EntityId     = group.Id;

                            RockQueue.TransactionQueue.Enqueue(transaction);
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(action))
                {
                    if (group == null)
                    {
                        group = this.Group;
                    }
                    if (group == null)
                    {
                        group = new GroupService(rockContext).Get(this.GroupId);
                    }
                    if (group != null)
                    {
                        var personEntityTypeId        = EntityTypeCache.Read("Rock.Model.Person").Id;
                        var groupEntityTypeId         = EntityTypeCache.Read("Rock.Model.Group").Id;
                        var groupMembershipCategoryId = CategoryCache.Read(Rock.SystemGuid.Category.HISTORY_PERSON_GROUP_MEMBERSHIP.AsGuid(), rockContext).Id;

                        new HistoryService(rockContext).Add(new History
                        {
                            EntityTypeId        = personEntityTypeId,
                            CategoryId          = groupMembershipCategoryId,
                            EntityId            = this.PersonId,
                            Summary             = action,
                            Caption             = group.Name,
                            RelatedEntityTypeId = groupEntityTypeId,
                            RelatedEntityId     = this.GroupId,
                            Verb = verb
                        });
                    }
                }
            }
            catch { }

            base.PreSaveChanges(dbContext, state);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Validates the group membership.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        private bool ValidateGroupMembership(RockContext rockContext, out string errorMessage)
        {
            errorMessage = string.Empty;

            // load group including members to save queries in group member validation
            var group = this.Group ?? new GroupService(rockContext).Queryable("Members").Where(g => g.Id == this.GroupId).FirstOrDefault();

            var groupType = GroupTypeCache.Read(group.GroupTypeId);
            var groupRole = groupType.Roles.First(a => a.Id == this.GroupRoleId);

            var existingGroupMembership = group.Members.Where(m => m.PersonId == this.PersonId);

            // check to see if the person is already a member of the group/role
            bool allowDuplicateGroupMembers = ConfigurationManager.AppSettings["AllowDuplicateGroupMembers"].AsBoolean();

            if (!allowDuplicateGroupMembers)
            {
                if (existingGroupMembership.Any(a => a.GroupRoleId == this.GroupRoleId && a.Id != this.Id))
                {
                    var person = this.Person ?? new PersonService(rockContext).Get(this.PersonId);

                    errorMessage = string.Format(
                        "{0} already belongs to the {1} role for this {2}, and cannot be added again with the same role",
                        person,
                        groupRole.Name.ToLower(),
                        groupType.GroupTerm.ToLower());

                    return(false);
                }
            }

            if (groupRole.MaxCount.HasValue && this.GroupMemberStatus == GroupMemberStatus.Active)
            {
                int memberCountInRole = group.Members
                                        .Where(m =>
                                               m.GroupRoleId == this.GroupRoleId &&
                                               m.GroupMemberStatus == GroupMemberStatus.Active)
                                        .Where(m => m != this)
                                        .Count();

                bool roleMembershipAboveMax = false;

                // if adding new group member..
                if (this.Id.Equals(0))
                {
                    // verify that active count has not exceeded the max
                    if ((memberCountInRole + 1) > groupRole.MaxCount)
                    {
                        roleMembershipAboveMax = true;
                    }
                }
                else
                {
                    // if existing group member changing role or status..
                    if (this.IsStatusOrRoleModified(rockContext))
                    {
                        // verify that active count has not exceeded the max
                        if (groupRole.MaxCount != null && (memberCountInRole + 1) > groupRole.MaxCount)
                        {
                            roleMembershipAboveMax = true;
                        }
                    }
                }

                // throw error if above max.. do not proceed
                if (roleMembershipAboveMax)
                {
                    errorMessage = string.Format(
                        "The number of {0} for this {1} is above its maximum allowed limit of {2:N0} active {3}.",
                        groupRole.Name.Pluralize().ToLower(),
                        groupType.GroupTerm.ToLower(),
                        groupRole.MaxCount,
                        groupType.GroupMemberTerm.Pluralize(groupRole.MaxCount == 1)).ToLower();
                    return(false);
                }
            }

            // if the GroupMember is getting Added (or if Person or Role is different), and if this Group has requirements that must be met before the person is added, check those
            if (this.IsNewOrChangedGroupMember(rockContext))
            {
                var requirementStatusesRequiredForAdd = group.PersonMeetsGroupRequirements(rockContext, this.PersonId, this.GroupRoleId)
                                                        .Where(a => a.MeetsGroupRequirement == MeetsGroupRequirement.NotMet &&
                                                               ((a.GroupRequirement.GroupRequirementType.RequirementCheckType != RequirementCheckType.Manual) && (a.GroupRequirement.MustMeetRequirementToAddMember == true)));

                if (requirementStatusesRequiredForAdd.Any())
                {
                    // deny if any of the non-manual MustMeetRequirementToAddMember requirements are not met
                    errorMessage = "This person must meet the following requirements before they are added to this group: "
                                   + requirementStatusesRequiredForAdd
                                   .Select(a => string.Format("{0}", a.GroupRequirement.GroupRequirementType))
                                   .ToList().AsDelimited(", ");

                    return(false);
                }
            }

            // check group capacity
            if (groupType.GroupCapacityRule == GroupCapacityRule.Hard && group.GroupCapacity.HasValue)
            {
                var currentActiveGroupMemberCount = group.Members.Where(m => m.GroupMemberStatus == GroupMemberStatus.Active).Count();

                // check if this would be adding an active group member (new active group member or changing existing group member status to active)
                if (
                    (this.Id.Equals(0) && this.GroupMemberStatus == GroupMemberStatus.Active) ||
                    (!this.Id.Equals(0) &&
                     existingGroupMembership.Where(m => m.Id == this.Id && m.GroupMemberStatus != GroupMemberStatus.Active).Any() &&
                     this.GroupMemberStatus == GroupMemberStatus.Active)
                    )
                {
                    if (currentActiveGroupMemberCount + 1 > group.GroupCapacity)
                    {
                        errorMessage = "Adding this individual would put the group over capacity.";
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            string cacheKey = "Rock.FindRelationships.Roles";

            ObjectCache cache = Rock.Web.Cache.RockMemoryCache.Default;
            List <int>  roles = cache[cacheKey] as List <int>;

            if (roles == null)
            {
                roles = new List <int>();

                foreach (var role in new GroupTypeRoleService(rockContext)
                         .Queryable().AsNoTracking()
                         .Where(r => r.GroupType.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS))))
                {
                    role.LoadAttributes(rockContext);
                    if (role.Attributes.ContainsKey("CanCheckin"))
                    {
                        bool canCheckIn = false;
                        if (bool.TryParse(role.GetAttributeValue("CanCheckin"), out canCheckIn) && canCheckIn)
                        {
                            roles.Add(role.Id);
                        }
                    }
                }

                CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
                cacheItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(300);
                cache.Set(cacheKey, roles, cacheItemPolicy);
            }

            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                if (!roles.Any())
                {
                    return(true);
                }

                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    bool preventInactive = (checkInState.CheckInType != null && checkInState.CheckInType.PreventInactivePeople);
                    var  dvInactive      = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid());

                    var groupMemberService = new GroupMemberService(rockContext);

                    var familyMemberIds = family.People.Select(p => p.Person.Id).ToList();

                    var knownRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                    if (knownRelationshipGroupType != null)
                    {
                        var ownerRole = knownRelationshipGroupType.Roles.FirstOrDefault(r => r.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid());
                        if (ownerRole != null)
                        {
                            // Get the Known Relationship group id's for each person in the family
                            var relationshipGroupIds = groupMemberService
                                                       .Queryable().AsNoTracking()
                                                       .Where(g =>
                                                              g.GroupRoleId == ownerRole.Id &&
                                                              familyMemberIds.Contains(g.PersonId))
                                                       .Select(g => g.GroupId);

                            // Get anyone in any of those groups that has a role with the canCheckIn attribute set
                            var personIds = groupMemberService
                                            .Queryable().AsNoTracking()
                                            .Where(g =>
                                                   relationshipGroupIds.Contains(g.GroupId) &&
                                                   roles.Contains(g.GroupRoleId))
                                            .Select(g => g.PersonId)
                                            .ToList();

                            foreach (var person in new PersonService(rockContext)
                                     .Queryable().AsNoTracking()
                                     .Where(p => personIds.Contains(p.Id))
                                     .ToList())
                            {
                                if (!family.People.Any(p => p.Person.Id == person.Id))
                                {
                                    if (!preventInactive || dvInactive == null || person.RecordStatusValueId != dvInactive.Id)
                                    {
                                        var relatedPerson = new CheckInPerson();
                                        relatedPerson.Person       = person.Clone(false);
                                        relatedPerson.FamilyMember = false;
                                        family.People.Add(relatedPerson);
                                    }
                                }
                            }
                        }
                    }

                    return(true);
                }
                else
                {
                    errorMessages.Add("There is not a family that is selected");
                }

                return(false);
            }

            return(false);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="entityIdProperty">The entity identifier property.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        private IQueryable <RelatedPersonInfo> GetAllRelatedPeopleQuery(RockContext context, MemberExpression entityIdProperty, string selection)
        {
            var settings = new RelatedPeopleSelectSettings(selection);

            bool showRelationship = (settings.ListFormat == ListFormatSpecifier.NameAndRelationship);

            // Get Support Data.
            var adultGuid = GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
            var childGuid = GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid();

            int familyGroupTypeId            = GroupTypeCache.Read(SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;
            int knownRelationshipGroupTypeId = GroupTypeCache.Read(SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()).Id;

            //
            // Construct a Query to return the list of Related People matching the filter conditions.
            //
            IQueryable <RelatedPersonInfo> allRelatedPeopleQuery = null;

            // If we are looking for Parents...
            // Add the Adults from the Family Group in which the Principal participates as a Child.
            if (settings.FamilyRelationshipTypeGuids.Contains(FamilyRelationshipParentGuid.AsGuid()))
            {
                var familyMembersQuery = GetRelatedPeopleQuery(context, new List <int> {
                    familyGroupTypeId
                }, new List <Guid> {
                    childGuid
                }, new List <Guid> {
                    adultGuid
                }, showRelationship ? "Parent" : null);

                allRelatedPeopleQuery = GetRelatedPeopleUnionQuery(allRelatedPeopleQuery, familyMembersQuery);
            }

            // If we are looking for Children...
            // Add the Children from the Family Group in which the Principal participates as an Adult.
            if (settings.FamilyRelationshipTypeGuids.Contains(FamilyRelationshipChildGuid.AsGuid()))
            {
                var familyMembersQuery = GetRelatedPeopleQuery(context, new List <int> {
                    familyGroupTypeId
                }, new List <Guid> {
                    adultGuid
                }, new List <Guid> {
                    childGuid
                }, showRelationship ? "Child" : null);

                allRelatedPeopleQuery = GetRelatedPeopleUnionQuery(allRelatedPeopleQuery, familyMembersQuery);
            }

            // If we are looking for Siblings...
            // Add other Children from the Family Group in which the Principal participates as a Child.
            if (settings.FamilyRelationshipTypeGuids.Contains(FamilyRelationshipSiblingGuid.AsGuid()))
            {
                var familyMembersQuery = GetRelatedPeopleQuery(context, new List <int> {
                    familyGroupTypeId
                }, new List <Guid> {
                    childGuid
                }, new List <Guid> {
                    childGuid
                }, showRelationship ? "Sibling" : null);

                allRelatedPeopleQuery = GetRelatedPeopleUnionQuery(allRelatedPeopleQuery, familyMembersQuery);
            }

            // If we are looking for a Spouse...
            // Add other Married Adult in the Family Group in which the Principal participates as a Married Adult.
            if (settings.FamilyRelationshipTypeGuids.Contains(FamilyRelationshipSpouseGuid.AsGuid()))
            {
                var marriedStatusGuid = SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid();
                int marriedStatusId   = DefinedValueCache.Read(marriedStatusGuid).Id;

                var familyGroupMembers = new GroupMemberService(context).Queryable()
                                         .Where(m => m.Group.GroupTypeId == familyGroupTypeId);

                var personSpouseQuery = new PersonService(context).Queryable()
                                        .SelectMany(
                    p =>
                    familyGroupMembers.Where(gm => gm.PersonId == p.Id && gm.Person.MaritalStatusValueId == marriedStatusId && gm.GroupRole.Guid == adultGuid)
                    .SelectMany(gm => gm.Group.Members)
                    .Where(gm => gm.PersonId != p.Id && gm.GroupRole.Guid == adultGuid && gm.Person.MaritalStatusValueId == marriedStatusId)
                    .Select(
                        gm =>
                        new RelatedPersonInfo
                {
                    RelatedToPersonId = p.Id,
                    PersonId          = gm.Person.Id,
                    FirstName         = gm.Person.FirstName,
                    LastName          = gm.Person.LastName,
                    Suffix            = gm.Person.SuffixValue.Value,
                    RelationshipName  = showRelationship ? "Spouse" : null
                }));

                allRelatedPeopleQuery = GetRelatedPeopleUnionQuery(allRelatedPeopleQuery, personSpouseQuery);
            }

            // If we are looking for a Known Relationship...
            // Add other People from the Known Relationship Group having the specified Roles and in which the Principal is the Owner.
            if (settings.KnownRelationshipTypeGuids.Any())
            {
                var ownerGuid          = GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid();
                var principalRoleGuids = new List <Guid>();
                var targetRoleGuids    = new List <Guid>(settings.KnownRelationshipTypeGuids);

                principalRoleGuids.Add(ownerGuid);

                var knownPersonsQuery = GetRelatedPeopleQuery(context, new List <int> {
                    knownRelationshipGroupTypeId
                }, principalRoleGuids, targetRoleGuids, showRelationship ? "*" : null);

                allRelatedPeopleQuery = GetRelatedPeopleUnionQuery(allRelatedPeopleQuery, knownPersonsQuery);
            }

            return(allRelatedPeopleQuery);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Gets the person search details.
        /// </summary>
        /// <param name="personSearchResult">The person search result.</param>
        /// <param name="person">The person.</param>
        private void GetPersonSearchDetails(PersonSearchResult personSearchResult, Person person)
        {
            var rockContext = this.Service.Context as Rock.Data.RockContext;

            var    appPath          = System.Web.VirtualPathUtility.ToAbsolute("~");
            string itemDetailFormat = @"
<div class='picker-select-item-details clearfix' style='display: none;'>
	{0}
	<div class='contents'>
        {1}
	</div>
</div>
";

            var familyGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
            int adultRoleId     = familyGroupType.Roles.First(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;

            int groupTypeFamilyId = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

            // figure out Family, Address, Spouse
            GroupMemberService groupMemberService = new GroupMemberService(rockContext);

            Guid?recordTypeValueGuid = null;

            if (person.RecordTypeValueId.HasValue)
            {
                recordTypeValueGuid = DefinedValueCache.Read(person.RecordTypeValueId.Value).Guid;
            }

            personSearchResult.ImageHtmlTag     = Person.GetPersonPhotoImageTag(person, 50, 50);
            personSearchResult.Age              = person.Age.HasValue ? person.Age.Value : -1;
            personSearchResult.ConnectionStatus = person.ConnectionStatusValueId.HasValue ? DefinedValueCache.Read(person.ConnectionStatusValueId.Value).Value : string.Empty;
            personSearchResult.Gender           = person.Gender.ConvertToString();
            personSearchResult.Email            = person.Email;

            string imageHtml = string.Format(
                "<div class='person-image' style='background-image:url({0}&width=65);background-size:cover;background-position:50%'></div>",
                Person.GetPersonPhotoUrl(person, 200, 200));

            string personInfoHtml = string.Empty;
            Guid   matchLocationGuid;
            bool   isBusiness;

            if (recordTypeValueGuid.HasValue && recordTypeValueGuid == Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid())
            {
                isBusiness        = true;
                matchLocationGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK.AsGuid();
            }
            else
            {
                isBusiness        = false;
                matchLocationGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid();
            }

            var familyGroupMember = groupMemberService.Queryable()
                                    .Where(a => a.PersonId == person.Id)
                                    .Where(a => a.Group.GroupTypeId == groupTypeFamilyId)
                                    .OrderBy(a => a.GroupOrder ?? int.MaxValue)
                                    .Select(s => new
            {
                s.GroupRoleId,
                GroupLocation = s.Group.GroupLocations.Where(a => a.GroupLocationTypeValue.Guid == matchLocationGuid).Select(a => a.Location).FirstOrDefault()
            }).FirstOrDefault();

            int?personAge = person.Age;

            if (familyGroupMember != null)
            {
                if (isBusiness)
                {
                    personInfoHtml += "Business";
                }
                else
                {
                    personInfoHtml += "<div class='role'>" + familyGroupType.Roles.First(a => a.Id == familyGroupMember.GroupRoleId).Name + "</div>";
                }

                if (personAge != null)
                {
                    personInfoHtml += " <em class='age'>(" + person.FormatAge() + " old)</em>";
                }

                if (familyGroupMember.GroupRoleId == adultRoleId)
                {
                    var personService = this.Service as PersonService;
                    var spouse        = personService.GetSpouse(person, a => new
                    {
                        a.Person.NickName,
                        a.Person.LastName,
                        a.Person.SuffixValueId
                    });

                    if (spouse != null)
                    {
                        string spouseFullName = Person.FormatFullName(spouse.NickName, spouse.LastName, spouse.SuffixValueId);
                        personInfoHtml += "<p class='spouse'><strong>Spouse:</strong> " + spouseFullName + "</p>";
                        personSearchResult.SpouseName = spouseFullName;
                    }
                }
            }
            else
            {
                if (personAge != null)
                {
                    personInfoHtml += personAge.ToString() + " yrs old";
                }
            }

            if (familyGroupMember != null)
            {
                var location = familyGroupMember.GroupLocation;

                if (location != null)
                {
                    string addressHtml = "<div class='address'><h5>Address</h5>" + location.GetFullStreetAddress().ConvertCrLfToHtmlBr() + "</div>";
                    personSearchResult.Address = location.GetFullStreetAddress();
                    personInfoHtml            += addressHtml;
                }
            }

            // Generate the HTML for Email and PhoneNumbers
            if (!string.IsNullOrWhiteSpace(person.Email) || person.PhoneNumbers.Any())
            {
                string emailAndPhoneHtml = "<div class='margin-t-sm'>";
                emailAndPhoneHtml += "<span class='email'>" + person.Email + "</span>";
                string phoneNumberList = "<div class='phones'>";
                foreach (var phoneNumber in person.PhoneNumbers)
                {
                    var phoneType = DefinedValueCache.Read(phoneNumber.NumberTypeValueId ?? 0);
                    phoneNumberList += string.Format(
                        "<br>{0} <small>{1}</small>",
                        phoneNumber.IsUnlisted ? "Unlisted" : phoneNumber.NumberFormatted,
                        phoneType != null ? phoneType.Value : string.Empty);
                }

                emailAndPhoneHtml += phoneNumberList + "</div></div>";

                personInfoHtml += emailAndPhoneHtml;
            }

            // force the link to open a new scrollable,resizable browser window (and make it work in FF, Chrome and IE) http://stackoverflow.com/a/2315916/1755417
            personInfoHtml += $"<p class='margin-t-sm'><small><a class='cursor-pointer' onclick=\"javascript: window.open('/person/{person.Id}', '_blank', 'scrollbars=1,resizable=1,toolbar=1'); return false;\" data-toggle=\"tooltip\" title=\"View Profile\">View Profile</a></small></p>";

            personSearchResult.PickerItemDetailsImageHtml      = imageHtml;
            personSearchResult.PickerItemDetailsPersonInfoHtml = personInfoHtml;
            personSearchResult.PickerItemDetailsHtml           = string.Format(itemDetailFormat, imageHtml, personInfoHtml);
        }
Exemplo n.º 15
0
        private void BindFamilies(RockContext rockContext, IQueryable <Person> personQry, IQueryable <int> dataviewPersonIdQry)
        {
            var familyGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());

            var personIds = personQry.Select(p => p.Id);

            var groupMemberQry = new GroupMemberService(rockContext)
                                 .Queryable().AsNoTracking()
                                 .Where(m =>
                                        m.Group.GroupTypeId == familyGroupType.Id &&
                                        personIds.Contains(m.PersonId));

            var familyIdQry = groupMemberQry.Select(m => m.GroupId).Distinct();

            _familyMembers = new GroupService(rockContext)
                             .Queryable().AsNoTracking()
                             .Where(g => familyIdQry.Contains(g.Id))
                             .Select(g => new
            {
                GroupId = g.Id,
                People  = g.Members
                          .Where(m => dataviewPersonIdQry.Contains(m.PersonId))
                          .OrderBy(m => m.GroupRole.Order)
                          .ThenBy(m => m.Person.BirthDate)
                          .Select(m => m.Person)
                          .Select(p => new PersonDirectoryItem
                {
                    Id = p.Id,
                    RecordTypeValueId = p.RecordTypeValueId,
                    NickName          = p.NickName,
                    LastName          = p.LastName,
                    Email             = p.Email,
                    BirthMonth        = p.BirthMonth,
                    BirthDay          = p.BirthDay,
                    BirthDate         = p.BirthDate,
                    Gender            = p.Gender,
                    PhotoId           = p.PhotoId,
                    GraduationYear    = p.GraduationYear
                })
                          .ToList()
            })
                             .ToDictionary(k => k.GroupId, v => v.People);

            if (_showAddress)
            {
                var homeLoc = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
                if (familyGroupType != null && homeLoc != null)
                {
                    _addresses = new GroupService(rockContext)
                                 .Queryable().AsNoTracking()
                                 .Where(g => familyIdQry.Contains(g.Id))
                                 .Select(g => new
                    {
                        g.Id,
                        HomeLocations = g.GroupLocations
                                        .Where(gl =>
                                               gl.GroupLocationTypeValueId.HasValue &&
                                               gl.GroupLocationTypeValueId == homeLoc.Id)
                                        .Select(gl => gl.Location)
                                        .ToList()
                    })
                                 .ToDictionary(k => k.Id, v => v.HomeLocations);
                }
            }

            var familyPersonIds = _familyMembers
                                  .SelectMany(m => m.Value)
                                  .Select(p => p.Id)
                                  .Distinct()
                                  .ToList();

            if (_phoneNumberCaptions.Any())
            {
                LoadPhoneNumbers(rockContext, familyPersonIds);
            }

            if (_showEnvelopeNumber && GlobalAttributesCache.Read().EnableGivingEnvelopeNumber)
            {
                LoadEnvelopeNumbers(rockContext, familyPersonIds);
            }

            var families = groupMemberQry.Select(m => new FamilyDirectoryItem
            {
                Id   = m.GroupId,
                Name = m.Group.Name
            })
                           .Distinct()
                           .OrderBy(f => f.Name)
                           .Take(GetAttributeValue("MaxResults").AsInteger())
                           .ToList();

            rptFamilies.DataSource = families;
            rptFamilies.DataBind();
            rptFamilies.Visible = true;

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

            // Determine which group to add the person to
            Group group       = null;
            int?  groupRoleId = null;

            var guidGroupAttribute = GetAttributeValue(action, "Group").AsGuidOrNull();

            if (guidGroupAttribute.HasValue)
            {
                var attributeGroup = AttributeCache.Read(guidGroupAttribute.Value, rockContext);
                if (attributeGroup != null)
                {
                    var groupGuid = action.GetWorklowAttributeValue(guidGroupAttribute.Value).AsGuidOrNull();

                    if (groupGuid.HasValue)
                    {
                        group = new GroupService(rockContext).Get(groupGuid.Value);

                        if (group != null)
                        {
                            // use the group's grouptype's default group role if a group role wasn't specified
                            groupRoleId = GroupTypeCache.Read(group.GroupTypeId).DefaultGroupRoleId;
                        }
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }

            if (!groupRoleId.HasValue)
            {
                errorMessages.Add("Provided group doesn't have a default group role");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

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

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var groupMember        = new GroupMember();
                groupMember.PersonId          = person.Id;
                groupMember.GroupId           = group.Id;
                groupMember.GroupRoleId       = groupRoleId.Value;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                if (groupMember.IsValidGroupMember(rockContext))
                {
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
                else
                {
                    // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

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

            return(true);
        }
Exemplo n.º 17
0
        /// <summary>
        /// logic to setup the groups location entry panel
        /// </summary>
        /// <param name="group">The group.</param>
        private void ConfigureGroupLocationControls(Group group)
        {
            var rockContext = new RockContext();

            ddlMember.Items.Clear();

            var groupType = GroupTypeCache.Read(group.GroupTypeId);

            if (groupType != null)
            {
                // only allow editing groups with single locations
                if (!groupType.AllowMultipleLocations)
                {
                    GroupLocationPickerMode groupTypeModes = groupType.LocationSelectionMode;
                    if (groupTypeModes != GroupLocationPickerMode.None)
                    {
                        // Set the location picker modes allowed based on the group type's allowed modes
                        LocationPickerMode modes = LocationPickerMode.None;
                        if ((groupTypeModes & GroupLocationPickerMode.Named) == GroupLocationPickerMode.Named)
                        {
                            modes = modes | LocationPickerMode.Named;
                        }

                        if ((groupTypeModes & GroupLocationPickerMode.Address) == GroupLocationPickerMode.Address)
                        {
                            modes = modes | LocationPickerMode.Address;
                        }

                        if ((groupTypeModes & GroupLocationPickerMode.Point) == GroupLocationPickerMode.Point)
                        {
                            modes = modes | LocationPickerMode.Point;
                        }

                        if ((groupTypeModes & GroupLocationPickerMode.Polygon) == GroupLocationPickerMode.Polygon)
                        {
                            modes = modes | LocationPickerMode.Polygon;
                        }

                        bool displayMemberTab = (groupTypeModes & GroupLocationPickerMode.GroupMember) == GroupLocationPickerMode.GroupMember;
                        bool displayOtherTab  = modes != LocationPickerMode.None;

                        ulNav.Visible             = displayOtherTab && displayMemberTab;
                        pnlMemberSelect.Visible   = displayMemberTab;
                        pnlLocationSelect.Visible = displayOtherTab && !displayMemberTab;

                        if (displayMemberTab)
                        {
                            var  personService        = new PersonService(rockContext);
                            Guid previousLocationType = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid();

                            foreach (GroupMember member in new GroupMemberService(rockContext).GetByGroupId(group.Id))
                            {
                                foreach (Group family in personService.GetFamilies(member.PersonId))
                                {
                                    foreach (GroupLocation familyGroupLocation in family.GroupLocations
                                             .Where(l => l.IsMappedLocation && !l.GroupLocationTypeValue.Guid.Equals(previousLocationType)))
                                    {
                                        ListItem li = new ListItem(
                                            string.Format("{0} {1} ({2})", member.Person.FullName, familyGroupLocation.GroupLocationTypeValue.Value, familyGroupLocation.Location.ToString()),
                                            string.Format("{0}|{1}", familyGroupLocation.Location.Id, member.PersonId));

                                        ddlMember.Items.Add(li);
                                    }
                                }
                            }
                        }

                        if (displayOtherTab)
                        {
                            locpGroupLocation.AllowedPickerModes = modes;
                        }

                        ddlLocationType.DataSource = groupType.LocationTypeValues.ToList();
                        ddlLocationType.DataBind();

                        LocationTypeTab = (displayMemberTab && ddlMember.Items.Count > 0) ? MEMBER_LOCATION_TAB_TITLE : OTHER_LOCATION_TAB_TITLE;

                        var groupLocation = group.GroupLocations.FirstOrDefault();
                        if (groupLocation != null && groupLocation.Location != null)
                        {
                            if (displayOtherTab)
                            {
                                locpGroupLocation.CurrentPickerMode = locpGroupLocation.GetBestPickerModeForLocation(groupLocation.Location);

                                locpGroupLocation.MapStyleValueGuid = GetAttributeValue("MapStyle").AsGuid();

                                if (groupLocation.Location != null)
                                {
                                    locpGroupLocation.Location = new LocationService(rockContext).Get(groupLocation.Location.Id);
                                }
                            }

                            if (displayMemberTab && ddlMember.Items.Count > 0 && groupLocation.GroupMemberPersonAliasId.HasValue)
                            {
                                LocationTypeTab = MEMBER_LOCATION_TAB_TITLE;
                                int?personId = new PersonAliasService(rockContext).GetPersonId(groupLocation.GroupMemberPersonAliasId.Value);
                                if (personId.HasValue)
                                {
                                    ddlMember.SetValue(string.Format("{0}|{1}", groupLocation.LocationId, personId.Value));
                                }
                            }
                            else if (displayOtherTab)
                            {
                                LocationTypeTab = OTHER_LOCATION_TAB_TITLE;
                            }

                            ddlLocationType.SetValue(groupLocation.GroupLocationTypeValueId);
                        }
                        else
                        {
                            LocationTypeTab = (displayMemberTab && ddlMember.Items.Count > 0) ? MEMBER_LOCATION_TAB_TITLE : OTHER_LOCATION_TAB_TITLE;
                        }

                        rptLocationTypes.DataSource = _tabs;
                        rptLocationTypes.DataBind();

                        ShowSelectedPane();
                    }
                }
                else
                {
                    lContent.Text = "<div class='alert alert-warning'>This editor only allows editing groups with a single location.</div>";
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap   = context.JobDetail.JobDataMap;
            var        groupType = GroupTypeCache.Read(dataMap.GetString("GroupType").AsGuid());

            if (groupType.TakesAttendance && groupType.SendAttendanceReminder)
            {
                // Get the occurrence dates that apply
                var dates = new List <DateTime>();
                dates.Add(RockDateTime.Today);
                try
                {
                    string[] reminderDays = dataMap.GetString("SendReminders").Split(',');
                    foreach (string reminderDay in reminderDays)
                    {
                        if (reminderDay.Trim() != string.Empty)
                        {
                            var reminderDate = RockDateTime.Today.AddDays(0 - Convert.ToInt32(reminderDay));
                            if (!dates.Contains(reminderDate))
                            {
                                dates.Add(reminderDate);
                            }
                        }
                    }
                }
                catch { }

                var rockContext        = new RockContext();
                var groupService       = new GroupService(rockContext);
                var groupMemberService = new GroupMemberService(rockContext);
                var scheduleService    = new ScheduleService(rockContext);
                var attendanceService  = new AttendanceService(rockContext);

                var startDate = dates.Min();
                var endDate   = dates.Max().AddDays(1);

                // Find all 'occurrences' for the groups that occur on the affected dates
                var occurrences = new Dictionary <int, List <DateTime> >();
                foreach (var group in groupService
                         .Queryable("Schedule").AsNoTracking()
                         .Where(g =>
                                g.GroupTypeId == groupType.Id &&
                                g.IsActive &&
                                g.Schedule != null &&
                                g.Members.Any(m =>
                                              m.GroupMemberStatus == GroupMemberStatus.Active &&
                                              m.GroupRole.IsLeader &&
                                              m.Person.Email != null &&
                                              m.Person.Email != "")))
                {
                    // Add the group
                    occurrences.Add(group.Id, new List <DateTime>());

                    // Check for a iCal schedule
                    DDay.iCal.Event calEvent = group.Schedule.GetCalenderEvent();
                    if (calEvent != null)
                    {
                        // If schedule has an iCal schedule, get occurrences between first and last dates
                        foreach (var occurrence in calEvent.GetOccurrences(startDate, endDate))
                        {
                            var startTime = occurrence.Period.StartTime.Value;
                            if (dates.Contains(startTime.Date))
                            {
                                occurrences[group.Id].Add(startTime);
                            }
                        }
                    }
                    else
                    {
                        // if schedule does not have an iCal, then check for weekly schedule and calculate occurrences starting with first attendance or current week
                        if (group.Schedule.WeeklyDayOfWeek.HasValue)
                        {
                            foreach (var date in dates)
                            {
                                if (date.DayOfWeek == group.Schedule.WeeklyDayOfWeek.Value)
                                {
                                    var startTime = date;
                                    if (group.Schedule.WeeklyTimeOfDay.HasValue)
                                    {
                                        startTime = startTime.Add(group.Schedule.WeeklyTimeOfDay.Value);
                                    }
                                    occurrences[group.Id].Add(startTime);
                                }
                            }
                        }
                    }
                }

                // Remove any occurrences during group type exclusion date ranges
                foreach (var exclusion in groupType.GroupScheduleExclusions)
                {
                    if (exclusion.Start.HasValue && exclusion.End.HasValue)
                    {
                        foreach (var keyVal in occurrences)
                        {
                            foreach (var occurrenceDate in keyVal.Value.ToList())
                            {
                                if (occurrenceDate >= exclusion.Start.Value &&
                                    occurrenceDate < exclusion.End.Value.AddDays(1))
                                {
                                    keyVal.Value.Remove(occurrenceDate);
                                }
                            }
                        }
                    }
                }

                // Remove any 'occurrenes' that already have attendance data entered
                foreach (var occurrence in attendanceService
                         .Queryable().AsNoTracking()
                         .Where(a =>
                                a.Group != null &&
                                a.ScheduleId.HasValue &&
                                a.Group.GroupTypeId == groupType.Id &&
                                a.Group.IsActive &&
                                a.StartDateTime > startDate &&
                                a.StartDateTime < endDate)
                         .Select(a => new
                {
                    GroupId = a.GroupId.Value,
                    a.StartDateTime
                })
                         .Distinct()
                         .ToList())
                {
                    if (occurrences.ContainsKey(occurrence.GroupId))
                    {
                        occurrences[occurrence.GroupId].RemoveAll(d => d == occurrence.StartDateTime);
                    }
                }

                // Get the groups that have occurrences
                var groupIds = occurrences.Where(o => o.Value.Any()).Select(o => o.Key).ToList();

                // Get the leaders of those groups
                var leaders = groupMemberService
                              .Queryable("Group,Person").AsNoTracking()
                              .Where(m =>
                                     groupIds.Contains(m.GroupId) &&
                                     m.GroupMemberStatus == GroupMemberStatus.Active &&
                                     m.GroupRole.IsLeader &&
                                     m.Person.Email != null &&
                                     m.Person.Email != "")
                              .ToList();

                // Loop through the leaders
                foreach (var leader in leaders)
                {
                    foreach (var group in occurrences.Where(o => o.Key == leader.GroupId))
                    {
                        var mergeObjects = GlobalAttributesCache.GetMergeFields(leader.Person);
                        mergeObjects.Add("Person", leader.Person);
                        mergeObjects.Add("Group", leader.Group);
                        mergeObjects.Add("Occurrence", group.Value.Max());

                        var recipients = new List <RecipientData>();
                        recipients.Add(new RecipientData(leader.Person.Email, mergeObjects));

                        Email.Send(dataMap.GetString("SystemEmail").AsGuid(), recipients);
                    }
                }
            }
        }
Exemplo n.º 19
0
        /// <summary>
        /// Loads the dropdowns.
        /// </summary>
        /// <param name="mergeObjects">The merge objects.</param>
        private void LoadDropdowns(Dictionary <string, object> mergeObjects)
        {
            var availableOptions = GetAttributeValue("AvailableOptions").SplitDelimitedValues(false);

            rbUnsubscribe.Visible = availableOptions.Contains(UNSUBSCRIBE);
            rbUnsubscribe.Text    = GetAttributeValue("UnsubscribefromListsText").ResolveMergeFields(mergeObjects);
            if (rbUnsubscribe.Visible)
            {
                cblUnsubscribeFromLists.Items.Clear();
                var rockContext        = new RockContext();
                var groupService       = new GroupService(rockContext);
                var groupMemberService = new GroupMemberService(rockContext);
                var categoryService    = new CategoryService(rockContext);

                int communicationListGroupTypeId = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_COMMUNICATIONLIST.AsGuid()).Id;

                // Get a list of all the Active CommunicationLists that the person is an active member of
                var communicationListQry = groupService.Queryable()
                                           .Where(a => a.GroupTypeId == communicationListGroupTypeId && a.IsActive && a.Members.Any(m => m.PersonId == this.CurrentPersonId && m.GroupMemberStatus == GroupMemberStatus.Active));

                var categoryGuids = this.GetAttributeValue("CommunicationListCategories").SplitDelimitedValues().AsGuidList();

                var communicationLists         = communicationListQry.ToList();
                var viewableCommunicationLists = new List <Group>();
                foreach (var communicationList in communicationLists)
                {
                    communicationList.LoadAttributes(rockContext);
                    if (!categoryGuids.Any())
                    {
                        // if no categories where specified, only show lists that the person has VIEW auth
                        if (communicationList.IsAuthorized(Rock.Security.Authorization.VIEW, this.CurrentPerson))
                        {
                            viewableCommunicationLists.Add(communicationList);
                        }
                    }
                    else
                    {
                        Guid?categoryGuid = communicationList.GetAttributeValue("Category").AsGuidOrNull();
                        if (categoryGuid.HasValue && categoryGuids.Contains(categoryGuid.Value))
                        {
                            viewableCommunicationLists.Add(communicationList);
                        }
                    }
                }

                viewableCommunicationLists = viewableCommunicationLists.OrderBy(a =>
                {
                    var name = a.GetAttributeValue("PublicName");
                    if (name.IsNullOrWhiteSpace())
                    {
                        name = a.Name;
                    }

                    return(name);
                }).ToList();

                foreach (var communicationList in viewableCommunicationLists)
                {
                    var listItem = new ListItem();
                    listItem.Value = communicationList.Id.ToString();
                    listItem.Text  = communicationList.GetAttributeValue("PublicName");
                    if (listItem.Text.IsNullOrWhiteSpace())
                    {
                        listItem.Text = communicationList.Name;
                    }

                    cblUnsubscribeFromLists.Items.Add(listItem);
                }

                // if there are no communication lists, hide the option
                rbUnsubscribe.Visible = viewableCommunicationLists.Any();
            }

            rbEmailPreferenceEmailAllowed.Visible = availableOptions.Contains(EMAILS_ALLOWED);
            rbEmailPreferenceEmailAllowed.Text    = GetAttributeValue("EmailsAllowedText").ResolveMergeFields(mergeObjects);

            rbEmailPreferenceNoMassEmails.Visible = availableOptions.Contains(NO_MASS_EMAILS);
            rbEmailPreferenceNoMassEmails.Text    = GetAttributeValue("NoMassEmailsText").ResolveMergeFields(mergeObjects);

            rbEmailPreferenceDoNotEmail.Visible = availableOptions.Contains(NO_EMAILS);
            rbEmailPreferenceDoNotEmail.Text    = GetAttributeValue("NoEmailsText").ResolveMergeFields(mergeObjects);

            rbNotInvolved.Visible = availableOptions.Contains(NOT_INVOLVED);
            rbNotInvolved.Text    = GetAttributeValue("NotInvolvedText").ResolveMergeFields(mergeObjects);

            rbUpdateEmailAddress.Visible = availableOptions.Contains(UPDATE_EMAIL_ADDRESS);
            rbUpdateEmailAddress.Text    = GetAttributeValue("UpdateEmailAddressText").ResolveMergeFields(mergeObjects);

            // NOTE: OnLoad will set the default selection based the communication.ListGroup and/or the person's current email preference

            var excludeReasons = GetAttributeValue("ReasonstoExclude").SplitDelimitedValues(false).ToList();
            var ds             = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.PERSON_RECORD_STATUS_REASON.AsGuid()).DefinedValues
                                 .Where(v => !excludeReasons.Contains(v.Value, StringComparer.OrdinalIgnoreCase))
                                 .Select(v => new
            {
                Name = v.Value,
                v.Id
            });


            ddlInactiveReason.SelectedIndex  = -1;
            ddlInactiveReason.DataSource     = ds;
            ddlInactiveReason.DataTextField  = "Name";
            ddlInactiveReason.DataValueField = "Id";
            ddlInactiveReason.DataBind();
        }
Exemplo n.º 20
0
        private void GetPersonSearchDetails(PersonSearchResult personSearchResult, Person person)
        {
            var    rockContext      = this.Service.Context as RockContext;
            string itemDetailFormat = @"
<div class='picker-select-item-details clearfix' style='display: none;'>
	{0}
	<div class='contents'>
        {1}
	</div>
</div>
";

            var familyGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
            int adultRoleId     = familyGroupType.Roles.First(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;

            int groupTypeFamilyId = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

            // figure out Family, Address, Spouse
            var groupMemberService = new GroupMemberService(rockContext);

            Guid?recordTypeValueGuid = null;

            if (person.RecordTypeValueId.HasValue)
            {
                recordTypeValueGuid = DefinedValueCache.Read(person.RecordTypeValueId.Value).Guid;
            }

            personSearchResult.ImageHtmlTag     = Person.GetPersonPhotoImageTag(person, 50, 50);
            personSearchResult.Age              = person.Age.HasValue ? person.Age.Value : -1;
            personSearchResult.ConnectionStatus = person.ConnectionStatusValueId.HasValue ? DefinedValueCache.Read(person.ConnectionStatusValueId.Value).Value : string.Empty;
            personSearchResult.Gender           = person.Gender.ConvertToString();
            personSearchResult.Email            = person.Email;

            string imageHtml = string.Format(
                "<div class='person-image' style='background-image:url({0}&width=65);background-size:cover;background-position:50%'></div>",
                Person.GetPersonPhotoUrl(person, 200, 200));

            string personInfoHtml = string.Empty;
            Guid   matchLocationGuid;
            bool   isBusiness;

            if (recordTypeValueGuid.HasValue && recordTypeValueGuid == Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid())
            {
                isBusiness        = true;
                matchLocationGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK.AsGuid();
            }
            else
            {
                isBusiness        = false;
                matchLocationGuid = Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid();
            }

            var familyGroupMember = groupMemberService.Queryable()
                                    .Where(a => a.PersonId == person.Id)
                                    .Where(a => a.Group.GroupTypeId == groupTypeFamilyId)
                                    .Select(s => new
            {
                s.GroupRoleId,
                GroupLocation = s.Group.GroupLocations.Where(a => a.GroupLocationTypeValue.Guid == matchLocationGuid).Select(a => a.Location).FirstOrDefault()
            }).FirstOrDefault();

            int?personAge = person.Age;

            if (familyGroupMember != null)
            {
                if (isBusiness)
                {
                    personInfoHtml += "Business";
                }
                else
                {
                    personInfoHtml += familyGroupType.Roles.First(a => a.Id == familyGroupMember.GroupRoleId).Name;
                }

                if (personAge != null)
                {
                    personInfoHtml += " <em>(" + personAge.ToString() + " yrs old)</em>";
                }

                if (familyGroupMember.GroupRoleId == adultRoleId)
                {
                    var personService = this.Service as PersonService;
                    var spouse        = personService.GetSpouse(person, a => new
                    {
                        a.Person.NickName,
                        a.Person.LastName,
                        a.Person.SuffixValueId
                    });

                    if (spouse != null)
                    {
                        string spouseFullName = Person.FormatFullName(spouse.NickName, spouse.LastName, spouse.SuffixValueId);
                        personInfoHtml += "<p><strong>Spouse:</strong> " + spouseFullName + "</p>";
                        personSearchResult.SpouseName = spouseFullName;
                    }
                }
            }
            else
            {
                if (personAge != null)
                {
                    personInfoHtml += personAge + " yrs old";
                }
            }

            if (familyGroupMember != null)
            {
                var location = familyGroupMember.GroupLocation;

                if (location != null)
                {
                    string addressHtml = "<h5>Address</h5>" + location.GetFullStreetAddress().ConvertCrLfToHtmlBr();
                    personSearchResult.Address = location.GetFullStreetAddress();
                    personInfoHtml            += addressHtml;
                }
            }

            // Generate the HTML for Email and PhoneNumbers
            if (!string.IsNullOrWhiteSpace(person.Email) || person.PhoneNumbers.Any())
            {
                string emailAndPhoneHtml = "<p class='margin-t-sm'>";
                emailAndPhoneHtml += person.Email;
                string phoneNumberList = string.Empty;
                foreach (var phoneNumber in person.PhoneNumbers)
                {
                    var phoneType = DefinedValueCache.Read(phoneNumber.NumberTypeValueId ?? 0);
                    phoneNumberList += string.Format(
                        "<br>{0} <small>{1}</small>",
                        phoneNumber.IsUnlisted ? "Unlisted" : phoneNumber.NumberFormatted,
                        phoneType != null ? phoneType.Value : string.Empty);
                }

                emailAndPhoneHtml += phoneNumberList + "<p>";

                personInfoHtml += emailAndPhoneHtml;
            }

            personSearchResult.PickerItemDetailsImageHtml      = imageHtml;
            personSearchResult.PickerItemDetailsPersonInfoHtml = personInfoHtml;
            personSearchResult.PickerItemDetailsHtml           = string.Format(itemDetailFormat, imageHtml, personInfoHtml);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Creates the known relationship.
        /// </summary>
        /// <param name="personId">The person identifier.</param>
        /// <param name="relatedPersonId">The related person identifier.</param>
        /// <param name="relationshipRoleId">The relationship role identifier.</param>
        public void CreateKnownRelationship(int personId, int relatedPersonId, int relationshipRoleId)
        {
            var groupMemberService = this;
            var rockContext        = this.Context as RockContext;

            var knownRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS);
            var ownerRole        = knownRelationshipGroupType.Roles.FirstOrDefault(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()));
            var relationshipRole = knownRelationshipGroupType.Roles.FirstOrDefault(r => r.Id == relationshipRoleId);

            if (ownerRole == null)
            {
                throw new Exception("Unable to find known relationships owner role");
            }

            if (relationshipRole == null)
            {
                throw new Exception("Specified relationshipRoleId is not a known relationships role");
            }

            var knownRelationshipGroup = groupMemberService.Queryable()
                                         .Where(m =>
                                                m.PersonId == personId &&
                                                m.GroupRole.Guid.Equals(ownerRole.Guid))
                                         .Select(m => m.Group)
                                         .FirstOrDefault();

            // Create known relationship group if doesn't exist
            if (knownRelationshipGroup == null)
            {
                var groupMember = new GroupMember();
                groupMember.PersonId    = personId;
                groupMember.GroupRoleId = ownerRole.Id;

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

                new GroupService(rockContext).Add(knownRelationshipGroup);
                rockContext.SaveChanges();
            }

            // Add relationships
            var relationshipMember = groupMemberService.Queryable()
                                     .FirstOrDefault(m =>
                                                     m.GroupId == knownRelationshipGroup.Id &&
                                                     m.PersonId == relatedPersonId &&
                                                     m.GroupRoleId == relationshipRoleId);

            if (relationshipMember == null)
            {
                relationshipMember             = new GroupMember();
                relationshipMember.GroupId     = knownRelationshipGroup.Id;
                relationshipMember.PersonId    = relatedPersonId;
                relationshipMember.GroupRoleId = relationshipRoleId;
                groupMemberService.Add(relationshipMember);
                rockContext.SaveChanges();
            }

            var inverseGroupMember = groupMemberService.GetInverseRelationship(relationshipMember, true);

            if (inverseGroupMember != null)
            {
                groupMemberService.Add(inverseGroupMember);
                rockContext.SaveChanges();
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Gets the people a person is related to
        /// </summary>
        /// <param name="context"></param>
        /// <param name="input"></param>
        /// <param name="relationshipTypeName">The relationship name you're search for</param>
        /// <returns></returns>
        public static List <Person> Relationship(DotLiquid.Context context, object input, string relationshipTypeName)
        {
            Person person      = null;
            var    rockContext = new RockContext();

            if (input is int)
            {
                person = new PersonService(rockContext).Get(( int )input);
            }
            else if (input is Person)
            {
                person = ( Person )input;
            }

            if (person != null)
            {
                var relationshipType = new GroupTypeRoleService(rockContext).GetByGroupTypeId(GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid()).Id).FirstOrDefault(r => relationshipTypeName == r.Name);
                if (relationshipType != null)
                {
                    var relatedPersons = new GroupMemberService(rockContext).GetKnownRelationship(person.Id, relationshipType.Id);
                    return(relatedPersons.Select(p => p.Person).ToList());
                }
            }

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

            // Get Group Type
            var groupTypeGuid = GetAttributeValue(action, "GroupType", true).AsGuid();
            var groupType     = GroupTypeCache.Read(groupTypeGuid);

            if (groupType == null)
            {
                // Appears Group type cache by gui is not always working.  Try to read from db.
                var groupTypeModel = new GroupTypeService(rockContext).Get(groupTypeGuid);
                if (groupTypeModel != null)
                {
                    groupType = GroupTypeCache.Read(groupTypeModel.Id);
                }
            }
            if (groupType == null)
            {
                errorMessages.Add("The Group Type could not be determined or found!");
            }

            // Group Name
            var groupName = GetAttributeValue(action, "GroupName", true);

            if (groupName.IsNullOrWhiteSpace())
            {
                errorMessages.Add("The Group Type could not be determined or found!");
            }

            // Parent Group
            Group parentGroup     = null;
            var   parentGroupGuid = GetAttributeValue(action, "ParentGroup", true).AsGuidOrNull();

            if (parentGroupGuid.HasValue)
            {
                parentGroup = new GroupService(rockContext).Get(parentGroupGuid.Value);
            }

            // Add request
            if (!errorMessages.Any())
            {
                var groupService = new GroupService(rockContext);

                Group group = null;

                int?parentGroupId = parentGroup != null ? parentGroup.Id : (int?)null;
                if (GetAttributeValue(action, "CheckExisting", true).AsBoolean())
                {
                    group = groupService.Queryable()
                            .Where(g =>
                                   g.GroupTypeId == groupType.Id &&
                                   g.Name == groupName &&
                                   ((!parentGroupId.HasValue && !g.ParentGroupId.HasValue) || (parentGroupId.HasValue && g.ParentGroupId.HasValue && g.ParentGroupId.Value == parentGroupId.Value)))
                            .FirstOrDefault();
                }

                if (group == null)
                {
                    group = new Group();
                    groupService.Add(group);
                    group.GroupTypeId = groupType.Id;
                    group.Name        = groupName;

                    if (parentGroup != null)
                    {
                        group.ParentGroupId = parentGroup.Id;
                    }

                    rockContext.SaveChanges();
                }

                if (group.Id > 0)
                {
                    string resultValue = group.Guid.ToString();
                    var    attribute   = SetWorkflowAttributeValue(action, "ResultAttribute", resultValue);
                    if (attribute != null)
                    {
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, resultValue));
                    }
                }
            }

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

            return(!errorMessages.Any());
        }
Exemplo n.º 24
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var rockContext = new RockContext();

            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);
                var changes       = new List <string>();
                Person business   = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                rockContext.SaveChanges();

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

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

                if (string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    if (workLocation != null)
                    {
                        groupLocationService.Delete(workLocation);
                        History.EvaluateChange(changes, "Address", workLocation.Location.ToString(), string.Empty);
                    }
                }
                else
                {
                    var oldValue = string.Empty;

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

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

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

                rockContext.SaveChanges();

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

            ShowSummary(hfBusinessId.Value.AsInteger());
        }
Exemplo n.º 25
0
        /// <summary>
        /// Job that will run quick SQL queries on a schedule.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            Guid?entryWorkflowType = dataMap.GetString("EraEntryWorkflow").AsGuidOrNull();
            Guid?exitWorkflowType  = dataMap.GetString("EraExitWorkflow").AsGuidOrNull();
            bool updateVisitDates  = dataMap.GetBooleanValue("SetVisitDates");
            var  groupTypeList     = dataMap.GetString("GroupTypes");

            // configuration
            //

            // giving
            int exitGivingCount = 1;

            // attendance
            int exitAttendanceCountShort = 1;
            int exitAttendanceCountLong  = 8;

            // get era dataset from stored proc
            var resultContext = new RockContext();


            var eraAttribute      = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid());
            var eraStartAttribute = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_START_DATE.AsGuid());
            var eraEndAttribute   = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_END_DATE.AsGuid());

            resultContext.Database.CommandTimeout = 3600;

            var results = resultContext.Database.SqlQuery <EraResult>("spCrm_FamilyAnalyticsEraDataset").ToList();

            int personEntityTypeId        = EntityTypeCache.Read("Rock.Model.Person").Id;
            int attributeEntityTypeId     = EntityTypeCache.Read("Rock.Model.Attribute").Id;
            int eraAttributeId            = AttributeCache.Read(SystemGuid.Attribute.PERSON_ERA_CURRENTLY_AN_ERA.AsGuid()).Id;
            int personAnalyticsCategoryId = CategoryCache.Read(SystemGuid.Category.HISTORY_PERSON_ANALYTICS.AsGuid()).Id;

            foreach (var result in results)
            {
                // create new rock context for each family (https://weblog.west-wind.com/posts/2014/Dec/21/Gotcha-Entity-Framework-gets-slow-in-long-Iteration-Loops)
                RockContext updateContext         = new RockContext();
                var         attributeValueService = new AttributeValueService(updateContext);
                var         historyService        = new HistoryService(updateContext);

                // if era ensure it still meets requirements
                if (result.IsEra)
                {
                    if (result.ExitGiftCountDuration < exitGivingCount && result.ExitAttendanceCountDurationShort < exitAttendanceCountShort && result.ExitAttendanceCountDurationLong < exitAttendanceCountLong)
                    {
                        // exit era (delete attribute value from each person in family)
                        var family = new GroupService(updateContext).Queryable("Members, Members.Person").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                        if (family != null)
                        {
                            foreach (var person in family.Members.Select(m => m.Person))
                            {
                                // remove the era flag
                                var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraAttributeValue != null)
                                {
                                    attributeValueService.Delete(eraAttributeValue);
                                }

                                // set end date
                                var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                                if (eraEndAttributeValue == null)
                                {
                                    eraEndAttributeValue             = new AttributeValue();
                                    eraEndAttributeValue.EntityId    = person.Id;
                                    eraEndAttributeValue.AttributeId = eraEndAttribute.Id;
                                    attributeValueService.Add(eraEndAttributeValue);
                                }
                                eraEndAttributeValue.Value = RockDateTime.Now.ToString();

                                // add a history record
                                if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                                {
                                    History historyRecord = new History();
                                    historyService.Add(historyRecord);
                                    historyRecord.EntityTypeId           = personEntityTypeId;
                                    historyRecord.EntityId               = person.Id;
                                    historyRecord.CreatedDateTime        = RockDateTime.Now;
                                    historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                    historyRecord.Caption             = "eRA";
                                    historyRecord.Summary             = "Exited eRA Status";
                                    historyRecord.Verb                = "EXITED";
                                    historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                    historyRecord.RelatedEntityId     = eraAttributeId;
                                    historyRecord.CategoryId          = personAnalyticsCategoryId;
                                }

                                updateContext.SaveChanges();
                            }

                            // launch exit workflow
                            if (exitWorkflowType.HasValue)
                            {
                                LaunchWorkflow(exitWorkflowType.Value, family);
                            }
                        }
                    }
                }
                else
                {
                    // entered era
                    var family = new GroupService(updateContext).Queryable("Members").AsNoTracking().Where(m => m.Id == result.FamilyId).FirstOrDefault();

                    if (family != null)
                    {
                        foreach (var person in family.Members.Where(m => !m.Person.IsDeceased).Select(m => m.Person))
                        {
                            // set era attribute to true
                            var eraAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraAttributeValue == null)
                            {
                                eraAttributeValue             = new AttributeValue();
                                eraAttributeValue.EntityId    = person.Id;
                                eraAttributeValue.AttributeId = eraAttribute.Id;
                                attributeValueService.Add(eraAttributeValue);
                            }
                            eraAttributeValue.Value = bool.TrueString;

                            // add start date
                            var eraStartAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraStartAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraStartAttributeValue == null)
                            {
                                eraStartAttributeValue             = new AttributeValue();
                                eraStartAttributeValue.EntityId    = person.Id;
                                eraStartAttributeValue.AttributeId = eraStartAttribute.Id;
                                attributeValueService.Add(eraStartAttributeValue);
                            }
                            eraStartAttributeValue.Value = RockDateTime.Now.ToString();

                            // delete end date if it exists
                            var eraEndAttributeValue = attributeValueService.Queryable().Where(v => v.AttributeId == eraEndAttribute.Id && v.EntityId == person.Id).FirstOrDefault();
                            if (eraEndAttributeValue != null)
                            {
                                attributeValueService.Delete(eraEndAttributeValue);
                            }

                            // add a history record
                            if (personAnalyticsCategoryId != 0 && personEntityTypeId != 0 && attributeEntityTypeId != 0 && eraAttributeId != 0)
                            {
                                History historyRecord = new History();
                                historyService.Add(historyRecord);
                                historyRecord.EntityTypeId           = personEntityTypeId;
                                historyRecord.EntityId               = person.Id;
                                historyRecord.CreatedDateTime        = RockDateTime.Now;
                                historyRecord.CreatedByPersonAliasId = person.PrimaryAliasId;
                                historyRecord.Caption             = "eRA";
                                historyRecord.Summary             = "Entered eRA Status";
                                historyRecord.Verb                = "ENTERED";
                                historyRecord.RelatedEntityTypeId = attributeEntityTypeId;
                                historyRecord.RelatedEntityId     = eraAttributeId;
                                historyRecord.CategoryId          = personAnalyticsCategoryId;
                            }

                            updateContext.SaveChanges();
                        }

                        // launch entry workflow
                        if (entryWorkflowType.HasValue)
                        {
                            LaunchWorkflow(entryWorkflowType.Value, family);
                        }
                    }
                }

                // update stats
            }

            // load giving attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsGiving");

            // load attendance attributes
            resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsAttendance");

            // process history for group types
            if (!string.IsNullOrWhiteSpace(groupTypeList))
            {
                string[] groupTypeGuids = groupTypeList.Split(',');

                var inactiveRecordValue = DefinedValueCache.Read(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE);

                var groupTypeEntityTypeId = EntityTypeCache.Read("Rock.Model.GroupType").Id;

                foreach (var groupTypeGuid in groupTypeGuids)
                {
                    var groupType = GroupTypeCache.Read(groupTypeGuid.AsGuid());

                    if (groupType != null)
                    {
                        // if the person is in a group of that type and the last history record for that group type isn't START write a start
                        RockContext rockContext = new RockContext();

                        // get history for this group type
                        var historyRecords = new HistoryService(rockContext).Queryable()
                                             .Where(h =>
                                                    h.EntityTypeId == personEntityTypeId &&
                                                    h.RelatedEntityTypeId == groupTypeEntityTypeId &&
                                                    h.RelatedEntityId == groupType.Id
                                                    )
                                             .GroupBy(h => h.EntityId)
                                             .Select(g => g.OrderByDescending(h => h.CreatedDateTime).Select(h => new { h.EntityId, h.Verb }).FirstOrDefault())
                                             .ToList();

                        // get group member information
                        var groupMemberInfo = new GroupMemberService(rockContext).Queryable()
                                              .Where(m =>
                                                     m.Group.GroupTypeId == groupType.Id &&
                                                     m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                     m.Group.IsActive
                                                     //&& m.Person.RecordStatusValueId != inactiveRecordValue.Id
                                                     )
                                              .GroupBy(m => m.PersonId)
                                              .Select(g => g.OrderBy(m => m.CreatedDateTime).Select(m => new { m.PersonId, m.CreatedDateTime, PersonAliasId = m.Person.Aliases.Select(p => p.Id).FirstOrDefault() }).FirstOrDefault())
                                              .ToList();

                        var needsStartDate = groupMemberInfo.Where(m => !historyRecords.Any(h => h.EntityId == m.PersonId && h.Verb == "STARTED"));

                        foreach (var startItem in needsStartDate)
                        {
                            using (RockContext updateContext = new RockContext())
                            {
                                var     historyService = new HistoryService(updateContext);
                                History history        = new History();
                                historyService.Add(history);
                                history.EntityTypeId        = personEntityTypeId;
                                history.EntityId            = startItem.PersonId;
                                history.RelatedEntityTypeId = groupTypeEntityTypeId;
                                history.RelatedEntityId     = groupType.Id;
                                history.Caption             = groupType.Name;
                                history.Summary             = "Started Membership in Group Of Type";
                                history.Verb                   = "STARTED";
                                history.CreatedDateTime        = startItem.CreatedDateTime;
                                history.CreatedByPersonAliasId = startItem.PersonAliasId;
                                history.CategoryId             = personAnalyticsCategoryId;

                                updateContext.SaveChanges();
                            }
                        }

                        var needsStoppedDate = historyRecords.Where(h => h.Verb == "STARTED" && !groupMemberInfo.Any(m => m.PersonId == h.EntityId));

                        foreach (var stopItem in needsStoppedDate)
                        {
                            using (RockContext updateContext = new RockContext())
                            {
                                var person = new PersonService(updateContext).Get(stopItem.EntityId);

                                if (person != null)
                                {
                                    var     historyService = new HistoryService(updateContext);
                                    History history        = new History();
                                    historyService.Add(history);
                                    history.EntityTypeId        = personEntityTypeId;
                                    history.EntityId            = person.Id;
                                    history.RelatedEntityTypeId = groupTypeEntityTypeId;
                                    history.RelatedEntityId     = groupType.Id;
                                    history.Caption             = groupType.Name;
                                    history.Summary             = "Stopped Membership in Group Of Type";
                                    history.Verb                   = "STOPPED";
                                    history.CreatedDateTime        = RockDateTime.Now;
                                    history.CreatedByPersonAliasId = person.PrimaryAliasId;
                                    history.CategoryId             = personAnalyticsCategoryId;

                                    updateContext.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }

            // process visit dates
            if (updateVisitDates)
            {
                resultContext.Database.ExecuteSqlCommand("spCrm_FamilyAnalyticsUpdateVisitDates");
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Handles the SaveClick event of the mdAddContact control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void mdAddContact_SaveClick(object sender, EventArgs e)
        {
            var rockContext        = new RockContext();
            var personService      = new PersonService(rockContext);
            var groupService       = new GroupService(rockContext);
            var groupMemberService = new GroupMemberService(rockContext);
            var business           = personService.Get(int.Parse(hfBusinessId.Value));
            int?contactId          = ppContact.PersonId;

            if (contactId.HasValue && contactId.Value > 0)
            {
                // Get the relationship roles to use
                var knownRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid());
                int businessContactRoleId      = knownRelationshipGroupType.Roles
                                                 .Where(r =>
                                                        r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT.AsGuid()))
                                                 .Select(r => r.Id)
                                                 .FirstOrDefault();
                int businessRoleId = knownRelationshipGroupType.Roles
                                     .Where(r =>
                                            r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS.AsGuid()))
                                     .Select(r => r.Id)
                                     .FirstOrDefault();
                int ownerRoleId = knownRelationshipGroupType.Roles
                                  .Where(r =>
                                         r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()))
                                  .Select(r => r.Id)
                                  .FirstOrDefault();

                if (ownerRoleId > 0 && businessContactRoleId > 0 && businessRoleId > 0)
                {
                    // get the known relationship group of the business contact
                    // add the business as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS
                    var contactKnownRelationshipGroup = groupMemberService.Queryable()
                                                        .Where(g =>
                                                               g.GroupRoleId == ownerRoleId &&
                                                               g.PersonId == contactId.Value)
                                                        .Select(g => g.Group)
                                                        .FirstOrDefault();
                    if (contactKnownRelationshipGroup == null)
                    {
                        // In some cases person may not yet have a know relationship group type
                        contactKnownRelationshipGroup = new Group();
                        groupService.Add(contactKnownRelationshipGroup);
                        contactKnownRelationshipGroup.Name        = "Known Relationship";
                        contactKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                        var ownerMember = new GroupMember();
                        ownerMember.PersonId    = contactId.Value;
                        ownerMember.GroupRoleId = ownerRoleId;
                        contactKnownRelationshipGroup.Members.Add(ownerMember);
                    }
                    var groupMember = new GroupMember();
                    groupMember.PersonId    = int.Parse(hfBusinessId.Value);
                    groupMember.GroupRoleId = businessRoleId;
                    contactKnownRelationshipGroup.Members.Add(groupMember);

                    // get the known relationship group of the business
                    // add the business contact as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT
                    var businessKnownRelationshipGroup = groupMemberService.Queryable()
                                                         .Where(g =>
                                                                g.GroupRole.Guid.Equals(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER)) &&
                                                                g.PersonId == business.Id)
                                                         .Select(g => g.Group)
                                                         .FirstOrDefault();
                    if (businessKnownRelationshipGroup == null)
                    {
                        // In some cases business may not yet have a know relationship group type
                        businessKnownRelationshipGroup = new Group();
                        groupService.Add(businessKnownRelationshipGroup);
                        businessKnownRelationshipGroup.Name        = "Known Relationship";
                        businessKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                        var ownerMember = new GroupMember();
                        ownerMember.PersonId    = int.Parse(hfBusinessId.Value);
                        ownerMember.GroupRoleId = ownerRoleId;
                        businessKnownRelationshipGroup.Members.Add(ownerMember);
                    }
                    var businessGroupMember = new GroupMember();
                    businessGroupMember.PersonId    = contactId.Value;
                    businessGroupMember.GroupRoleId = businessContactRoleId;
                    businessKnownRelationshipGroup.Members.Add(businessGroupMember);

                    rockContext.SaveChanges();
                }
            }

            mdAddContact.Hide();
            hfModalOpen.Value = string.Empty;
            BindContactListGrid(business);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            RockPage.AddCSSLink(ResolveRockUrl("~/Styles/fluidbox.css"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/imagesloaded.min.js"));
            RockPage.AddScriptLink(ResolveRockUrl("~/Scripts/jquery.fluidbox.min.js"));

            if (CurrentPerson != null)
            {
                lName.Text = CurrentPerson.FullName;

                // Setup Image
                var imgTag = new LiteralControl(Rock.Model.Person.GetPersonPhotoImageTag(CurrentPerson, 188, 188));
                if (CurrentPerson.PhotoId.HasValue)
                {
                    var imgLink = new HyperLink();
                    imgLink.Attributes.Add("href", CurrentPerson.PhotoUrl);
                    phImage.Controls.Add(imgLink);
                    imgLink.Controls.Add(imgTag);
                }
                else
                {
                    phImage.Controls.Add(imgTag);
                }

                if (CurrentPerson.BirthDate.HasValue)
                {
                    var    dtf = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
                    string mdp = dtf.ShortDatePattern;
                    mdp = mdp.Replace(dtf.DateSeparator + "yyyy", "").Replace("yyyy" + dtf.DateSeparator, "");

                    string ageText = (CurrentPerson.BirthYear.HasValue && CurrentPerson.BirthYear != DateTime.MinValue.Year) ?
                                     string.Format("{0} yrs old ", CurrentPerson.BirthDate.Value.Age()) : string.Empty;
                    lAge.Text = string.Format("{0}<small>({1})</small><br/>", ageText, CurrentPerson.BirthDate.Value.ToMonthDayString());
                }

                lGender.Text = CurrentPerson.Gender != Gender.Unknown ? CurrentPerson.Gender.ToString() : string.Empty;

                if (CurrentPerson.PhoneNumbers != null)
                {
                    rptPhones.DataSource = CurrentPerson.PhoneNumbers.ToList();
                    rptPhones.DataBind();
                }

                lEmail.Text = CurrentPerson.Email;

                Guid?locationTypeGuid = GetAttributeValue("LocationType").AsGuidOrNull();
                if (locationTypeGuid.HasValue)
                {
                    var addressTypeDv = DefinedValueCache.Read(locationTypeGuid.Value);

                    var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuidOrNull();

                    if (familyGroupTypeGuid.HasValue)
                    {
                        var familyGroupType = GroupTypeCache.Read(familyGroupTypeGuid.Value);

                        RockContext rockContext = new RockContext();
                        var         address     = new GroupLocationService(rockContext).Queryable()
                                                  .Where(l => l.Group.GroupTypeId == familyGroupType.Id &&
                                                         l.GroupLocationTypeValueId == addressTypeDv.Id &&
                                                         l.Group.Members.Any(m => m.PersonId == CurrentPerson.Id))
                                                  .Select(l => l.Location)
                                                  .FirstOrDefault();
                        if (address != null)
                        {
                            lAddress.Text = string.Format("<div class='margin-b-md'><small>{0} Address</small><br />{1}</div>", addressTypeDv.Value, address.FormattedHtmlAddress);
                        }
                    }
                }

                if (GetAttributeValue("ShowHomeAddress").AsBoolean())
                {
                    var homeAddress = CurrentPerson.GetHomeLocation();
                    if (homeAddress != null)
                    {
                    }
                }
            }
            else
            {
                pnlView.Visible         = false;
                nbNotAuthorized.Visible = true;
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Create an EntityField for an Attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes"></param>
        public static EntityField GetEntityFieldForAttribute(AttributeCache attribute, bool limitToFilterableAttributes = true)
        {
            // Ensure field name only has Alpha, Numeric and underscore chars
            string fieldName = attribute.Key.RemoveSpecialCharacters().Replace(".", "");

            EntityField entityField = null;

            // Make sure that the attributes field type actually renders a filter control if limitToFilterableAttributes
            var fieldType = FieldTypeCache.Read(attribute.FieldTypeId);

            if (fieldType != null && (!limitToFilterableAttributes || fieldType.Field.HasFilterControl()))
            {
                entityField       = new EntityField(fieldName, FieldKind.Attribute, typeof(string), attribute.Guid, fieldType);
                entityField.Title = attribute.Name.SplitCase();
                entityField.TitleWithoutQualifier = entityField.Title;

                foreach (var config in attribute.QualifierValues)
                {
                    entityField.FieldConfig.Add(config.Key, config.Value);
                }

                // Special processing for Entity Type "Group" or "GroupMember" to handle sub-types that are distinguished by GroupTypeId.
                if ((attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Group)) || attribute.EntityTypeId == EntityTypeCache.GetId(typeof(GroupMember)) && attribute.EntityTypeQualifierColumn == "GroupTypeId"))
                {
                    using (var rockContext = new RockContext())
                    {
                        var groupType = GroupTypeCache.Read(attribute.EntityTypeQualifierValue.AsInteger(), rockContext);
                        if (groupType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = groupType.Name;
                            entityField.Title = string.Format("{0} ({1})", attribute.Name, groupType.Name);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var contentChannelType = new ContentChannelTypeService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (contentChannelType != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = contentChannelType.Name;
                            entityField.Title = string.Format("{0} (ChannelType: {1})", attribute.Name, contentChannelType.Name);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var contentChannel = new ContentChannelService(rockContext).Get(attribute.EntityTypeQualifierValue.AsInteger());
                        if (contentChannel != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = contentChannel.Name;
                            entityField.Title = string.Format("{0} (Channel: {1})", attribute.Name, contentChannel.Name);
                        }
                    }
                }

                // Special processing for Entity Type "Workflow" to handle sub-types that are distinguished by WorkflowTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Rock.Model.Workflow)) && attribute.EntityTypeQualifierColumn == "WorkflowTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        int workflowTypeId = attribute.EntityTypeQualifierValue.AsInteger();
                        if (_workflowTypeNameLookup == null)
                        {
                            _workflowTypeNameLookup = new WorkflowTypeService(rockContext).Queryable().ToDictionary(k => k.Id, v => v.Name);
                        }

                        var workflowTypeName = _workflowTypeNameLookup.ContainsKey(workflowTypeId) ? _workflowTypeNameLookup[workflowTypeId] : null;
                        if (workflowTypeName != null)
                        {
                            // Append the Qualifier to the title for Workflow Attributes
                            entityField.AttributeEntityTypeQualifierName = workflowTypeName;
                            entityField.Title = string.Format("({1}) {0} ", attribute.Name, workflowTypeName);
                        }
                    }
                }
            }

            return(entityField);
        }
Exemplo n.º 29
0
        private void BindGroupTypes(string selectedValues)
        {
            var selectedItems = selectedValues.Split(',');

            cblPrimaryGroupTypes.Items.Clear();
            cblAlternateGroupTypes.Items.Clear();

            if (ddlKiosk.SelectedValue != None.IdValue)
            {
                using (var rockContext = new RockContext())
                {
                    var deviceGroupTypes = GetDeviceGroupTypes(ddlKiosk.SelectedValueAsInt() ?? 0, rockContext);

                    var primaryGroupTypeIds = GetDescendentGroupTypes(GroupTypeCache.Read(ddlCheckinType.SelectedValueAsInt() ?? 0)).Select(t => t.Id).ToList();

                    cblPrimaryGroupTypes.DataSource = deviceGroupTypes.Where(t => primaryGroupTypeIds.Contains(t.Id)).ToList();
                    cblPrimaryGroupTypes.DataBind();
                    cblPrimaryGroupTypes.Visible = cblPrimaryGroupTypes.Items.Count > 0;

                    cblAlternateGroupTypes.DataSource = deviceGroupTypes.Where(t => !primaryGroupTypeIds.Contains(t.Id)).ToList();
                    cblAlternateGroupTypes.DataBind();
                    cblAlternateGroupTypes.Visible = cblPrimaryGroupTypes.Items.Count > 0;
                }

                if (selectedValues != string.Empty)
                {
                    foreach (string id in selectedValues.Split(','))
                    {
                        ListItem item = cblPrimaryGroupTypes.Items.FindByValue(id);
                        if (item != null)
                        {
                            item.Selected = true;
                        }

                        item = cblAlternateGroupTypes.Items.FindByValue(id);
                        if (item != null)
                        {
                            item.Selected = true;
                        }
                    }
                }
                else
                {
                    if (CurrentGroupTypeIds != null)
                    {
                        foreach (int id in CurrentGroupTypeIds)
                        {
                            ListItem item = cblPrimaryGroupTypes.Items.FindByValue(id.ToString());
                            if (item != null)
                            {
                                item.Selected = true;
                            }

                            item = cblAlternateGroupTypes.Items.FindByValue(id.ToString());
                            if (item != null)
                            {
                                item.Selected = true;
                            }
                        }
                    }
                }
            }
            else
            {
                cblPrimaryGroupTypes.Visible   = false;
                cblAlternateGroupTypes.Visible = false;
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Adds a person alias, known relationship group, implied relationship group, and optionally a family group for
        /// a new person.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="campusId">The campus identifier.</param>
        /// <param name="savePersonAttributes">if set to <c>true</c> [save person attributes].</param>
        /// <returns>Family Group</returns>
        public static Group SaveNewPerson(Person person, RockContext rockContext, int?campusId = null, bool savePersonAttributes = false)
        {
            // Create/Save Known Relationship Group
            var knownRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS);

            if (knownRelationshipGroupType != null)
            {
                var ownerRole = knownRelationshipGroupType.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()));
                if (ownerRole != null)
                {
                    var groupMember = new GroupMember();
                    groupMember.Person      = person;
                    groupMember.GroupRoleId = ownerRole.Id;

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

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

            // Create/Save Implied Relationship Group
            var impliedRelationshipGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_IMPLIED_RELATIONSHIPS);

            if (impliedRelationshipGroupType != null)
            {
                var ownerRole = impliedRelationshipGroupType.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_IMPLIED_RELATIONSHIPS_OWNER.AsGuid()));
                if (ownerRole != null)
                {
                    var groupMember = new GroupMember();
                    groupMember.Person      = person;
                    groupMember.GroupRoleId = ownerRole.Id;

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

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

            // Create/Save family
            var familyGroupType = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);

            if (familyGroupType != null)
            {
                var adultRole = familyGroupType.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()));
                if (adultRole != null)
                {
                    var groupMember = new GroupMember();
                    groupMember.Person      = person;
                    groupMember.GroupRoleId = adultRole.Id;

                    var groupMembers = new List <GroupMember>();
                    groupMembers.Add(groupMember);

                    return(GroupService.SaveNewFamily(rockContext, groupMembers, campusId, savePersonAttributes));
                }
            }

            return(null);
        }