示例#1
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>
        public override System.Linq.Expressions.Expression GetExpression(Data.RockContext context, System.Linq.Expressions.MemberExpression entityIdProperty, string selection)
        {
            bool showAsLink = this.GetAttributeValueFromSelection("ShowAsLink", selection).AsBooleanOrNull() ?? false;

            var memberQuery = new GroupMemberService(context).Queryable();

            IQueryable <FormattedDataValue> groupLinkQuery;

            if (showAsLink)
            {
                groupLinkQuery = memberQuery.Select(gm => new HtmlLinkDataValue {
                    SourceValue = gm.Group.Name, Url = "/group/" + gm.GroupId.ToString()
                });
            }
            else
            {
                groupLinkQuery = memberQuery.Select(gm => new FormattedDataValue {
                    SourceValue = gm.Group.Name
                });
            }

            var exp = SelectExpressionExtractor.Extract(groupLinkQuery, entityIdProperty, "gm");

            return(exp);
        }
        /// <summary>
        /// Handles the SaveClick event of the modalAddPerson control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        void modalAddPerson_SaveClick(object sender, EventArgs e)
        {
            if (hfActiveTab.Value == "Existing")
            {
                int?personId = ppExistingPerson.PersonId;
                if (personId.HasValue)
                {
                    using (new UnitOfWorkScope())
                    {
                        var person = new PersonService().Get(personId.Value);
                        if (person != null)
                        {
                            var familyMember = new FamilyMember();
                            familyMember.SetValuesFromPerson(person);

                            var familyRoleIds = familyRoles.Select(r => r.Id).ToList();

                            var existingFamilyRoles = new GroupMemberService().Queryable("GroupRole")
                                                      .Where(m => m.PersonId == person.Id && familyRoleIds.Contains(m.GroupRoleId))
                                                      .OrderBy(m => m.GroupRole.SortOrder)
                                                      .ToList();

                            var existingRole = existingFamilyRoles.Select(m => m.GroupRole).FirstOrDefault();
                            if (existingRole != null)
                            {
                                familyMember.RoleGuid = existingRole.Guid;
                                familyMember.RoleName = existingRole.Name;
                            }

                            familyMember.ExistingFamilyMember    = existingFamilyRoles.Any(r => r.GroupId == _family.Id);
                            familyMember.RemoveFromOtherFamilies = cbRemoveOtherFamilies.Checked;

                            FamilyMembers.Add(familyMember);
                        }
                    }
                }
            }
            else
            {
                var familyMember = new FamilyMember();
                familyMember.FirstName = tbNewPersonFirstName.Text;
                familyMember.LastName  = tbNewPersonLastName.Text;
                familyMember.Gender    = ddlNewPersonGender.SelectedValueAsEnum <Gender>();
                familyMember.BirthDate = dpNewPersonBirthDate.SelectedDate;
                var role = familyRoles.Where(r => r.Id == (rblNewPersonRole.SelectedValueAsInt() ?? 0)).FirstOrDefault();
                if (role != null)
                {
                    familyMember.RoleGuid = role.Guid;
                    familyMember.RoleName = role.Name;
                }
                FamilyMembers.Add(familyMember);
            }

            tbNewPersonFirstName.Required = false;
            tbNewPersonLastName.Required  = false;

            confirmExit.Enabled = true;

            BindMembers();
        }
示例#3
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns(BenevolenceRequest benevolenceRequest)
        {
            ddlRequestStatus.BindToDefinedType(DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.BENEVOLENCE_REQUEST_STATUS)), false);
            ddlConnectionStatus.BindToDefinedType(DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS)), true);

            Guid groupGuid  = GetAttributeValue("CaseWorkerRole").AsGuid();
            var  personList = new GroupMemberService(new RockContext())
                              .Queryable("Person, Group")
                              .Where(gm => gm.Group.Guid == groupGuid)
                              .Select(gm => gm.Person)
                              .ToList();

            string caseWorkerPersonAliasValue = benevolenceRequest.CaseWorkerPersonAliasId.ToString();

            if (benevolenceRequest.CaseWorkerPersonAlias != null &&
                benevolenceRequest.CaseWorkerPersonAlias.Person != null &&
                !personList.Select(p => p.Id).ToList().Contains(benevolenceRequest.CaseWorkerPersonAlias.Person.Id))
            {
                personList.Add(benevolenceRequest.CaseWorkerPersonAlias.Person);
            }

            ddlCaseWorker.DataSource     = personList.OrderBy(p => p.NickName).ThenBy(p => p.LastName).ToList();
            ddlCaseWorker.DataTextField  = "FullName";
            ddlCaseWorker.DataValueField = "PrimaryAliasId";
            ddlCaseWorker.DataBind();
            ddlCaseWorker.Items.Insert(0, new ListItem());
        }
        /// <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>());
        }
        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();

            var groupService = new GroupService(rockContext);

            _families = groupService
                        .Queryable().AsNoTracking()
                        .Where(g => familyIdQry.Contains(g.Id))
                        .ToList();

            _familyMembers = groupService
                             .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)
                          .ToList()
            })
                             .ToDictionary(k => k.GroupId, v => v.People);

            var families = groupMemberQry.Select(m => m.GroupId)
                           .Distinct()
                           .Take(GetAttributeValue("MaxResults").AsInteger())
                           .ToList();

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

            rptPeople.Visible = false;
        }
示例#6
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>
        public override System.Linq.Expressions.Expression GetExpression(Data.RockContext context, System.Linq.Expressions.MemberExpression entityIdProperty, string selection)
        {
            bool showAsLink   = this.GetAttributeValueFromSelection("ShowAsLink", selection).AsBooleanOrNull() ?? false;
            int  displayOrder = this.GetAttributeValueFromSelection("DisplayOrder", selection).AsIntegerOrNull() ?? 0;

            var memberQuery = new GroupMemberService(context).Queryable();

            IQueryable <FormattedDataValue> personLinkQuery;

            if (showAsLink)
            {
                if (displayOrder == 0)
                {
                    personLinkQuery = memberQuery.Select(gm => new HtmlLinkDataValue {
                        SourceValue = gm.Person.NickName + " " + gm.Person.LastName, Url = "/person/" + gm.PersonId.ToString()
                    });
                }
                else
                {
                    personLinkQuery = memberQuery.Select(gm => new HtmlLinkDataValue {
                        SourceValue = gm.Person.LastName + ", " + gm.Person.NickName, Url = "/person/" + gm.PersonId.ToString()
                    });
                }
            }
            else
            {
                if (displayOrder == 0)
                {
                    personLinkQuery = memberQuery.Select(gm => new FormattedDataValue {
                        SourceValue = gm.Person.LastName + ", " + gm.Person.NickName
                    });
                }
                else
                {
                    personLinkQuery = memberQuery.Select(gm => new FormattedDataValue {
                        SourceValue = gm.Person.LastName + ", " + gm.Person.NickName
                    });
                }
            }

            var exp = SelectExpressionExtractor.Extract(personLinkQuery, entityIdProperty, "gm");

            return(exp);
        }
        private void ListGroups()
        {
            RockContext rockContext = new RockContext();

            var qry = new GroupMemberService(rockContext)
                      .Queryable("Group")
                      .Where(m => m.PersonId == CurrentPersonId &&
                             m.GroupMemberStatus == GroupMemberStatus.Active &&
                             m.Group.IsActive == true);

            List <Guid> includeGroupTypeGuids = GetAttributeValue("IncludeGroupTypes").SplitDelimitedValues().Select(a => Guid.Parse(a)).ToList();

            if (includeGroupTypeGuids.Count > 0)
            {
                qry = qry.Where(t => includeGroupTypeGuids.Contains(t.Group.GroupType.Guid));
            }

            List <Guid> excludeGroupTypeGuids = GetAttributeValue("ExcludeGroupTypes").SplitDelimitedValues().Select(a => Guid.Parse(a)).ToList();

            if (excludeGroupTypeGuids.Count > 0)
            {
                qry = qry.Where(t => !excludeGroupTypeGuids.Contains(t.Group.GroupType.Guid));
            }

            var groups = qry.Select(m => new GroupInvolvementSummary  {
                Group = m.Group, Role = m.GroupRole.Name, IsLeader = m.GroupRole.IsLeader, GroupType = m.Group.GroupType.Name
            }).ToList();

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

            mergeFields.Add("Groups", groups);
            mergeFields.Add("CurrentPerson", CurrentPerson);
            var globalAttributeFields = Rock.Web.Cache.GlobalAttributesCache.GetMergeFields(CurrentPerson);

            globalAttributeFields.ToList().ForEach(d => mergeFields.Add(d.Key, d.Value));

            Dictionary <string, object> linkedPages = new Dictionary <string, object>();

            linkedPages.Add("DetailPage", LinkedPageUrl("DetailPage", null));
            mergeFields.Add("LinkedPages", linkedPages);

            string template = GetAttributeValue("LavaTemplate");

            // show debug info
            bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean();

            if (enableDebug && IsUserAuthorized(Authorization.EDIT))
            {
                lDebug.Visible = true;
                lDebug.Text    = mergeFields.lavaDebugInfo();
            }

            lContent.Text = template.ResolveMergeFields(mergeFields);
        }
示例#8
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>
        public override System.Linq.Expressions.Expression GetExpression(Data.RockContext context, System.Linq.Expressions.MemberExpression entityIdProperty, string selection)
        {
            var memberQuery = new GroupMemberService(context).Queryable();

            IQueryable <string> groupLinkQuery;

            groupLinkQuery = memberQuery.Select(gm => gm.Group.Campus.Name);

            var exp = SelectExpressionExtractor.Extract(groupLinkQuery, entityIdProperty, "gm");

            return(exp);
        }
示例#9
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>
        public override System.Linq.Expressions.Expression GetExpression(Data.RockContext context, System.Linq.Expressions.MemberExpression entityIdProperty, string selection)
        {
            bool showAsLink = this.GetAttributeValueFromSelection("ShowAsLink", selection).AsBooleanOrNull() ?? false;

            var memberQuery = new GroupMemberService(context).Queryable();

            IQueryable <string> groupLinkQuery;

            if (showAsLink)
            {
                // Return a string in the format: <a href='/group/{groupId}'>Group Name</a>
                groupLinkQuery = memberQuery.Select(gm => "<a href='/group/" + gm.GroupId.ToString() + "'>" + gm.Group.Name + "</a>");
            }
            else
            {
                groupLinkQuery = memberQuery.Select(gm => gm.Group.Name);
            }

            var exp = SelectExpressionExtractor.Extract(groupLinkQuery, entityIdProperty, "gm");

            return(exp);
        }
示例#10
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>
        public override System.Linq.Expressions.Expression GetExpression(Data.RockContext context, System.Linq.Expressions.MemberExpression entityIdProperty, string selection)
        {
            bool showAsLink   = this.GetAttributeValueFromSelection("ShowAsLink", selection).AsBooleanOrNull() ?? false;
            int  displayOrder = this.GetAttributeValueFromSelection("DisplayOrder", selection).AsIntegerOrNull() ?? 0;

            var memberQuery = new GroupMemberService(context).Queryable();

            IQueryable <string> personLinkQuery;

            if (showAsLink)
            {
                // Return a string in the format: <a href='/person/{personId}'>LastName, NickName</a>
                if (displayOrder == 0)
                {
                    personLinkQuery = memberQuery.Select(gm => "<a href='/person/" + gm.PersonId.ToString() + "'>" + gm.Person.NickName + " " + gm.Person.LastName + "</a>");
                }
                else
                {
                    personLinkQuery = memberQuery.Select(gm => "<a href='/person/" + gm.PersonId.ToString() + "'>" + gm.Person.LastName + ", " + gm.Person.NickName + "</a>");
                }
            }
            else
            {
                if (displayOrder == 0)
                {
                    personLinkQuery = memberQuery.Select(gm => gm.Person.NickName + " " + gm.Person.LastName);
                }
                else
                {
                    personLinkQuery = memberQuery.Select(gm => gm.Person.LastName + ", " + gm.Person.NickName);
                }
            }

            var exp = SelectExpressionExtractor.Extract(personLinkQuery, entityIdProperty, "gm");

            return(exp);
        }
示例#11
0
        /// <summary>
        /// Notifies the admins.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="message">The message.</param>
        /// <param name="appRoot">The application root.</param>
        /// <param name="themeRoot">The theme root.</param>
        /// <param name="createCommunicationHistory">if set to <c>true</c> [create communication history].</param>
        /// <exception cref="System.Exception">Error sending System Email: Could not read Email Medium Entity Type</exception>
        public static void NotifyAdmins(string subject, string message, string appRoot = "", string themeRoot = "", bool createCommunicationHistory = true)
        {
            try
            {
                List <Person> personList = null;

                Guid adminGroup = Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid();

                using (var rockContext = new RockContext())
                {
                    personList = new GroupMemberService(rockContext).Queryable()
                                 .Where(m =>
                                        m.Group.Guid.Equals(adminGroup) &&
                                        m.GroupMemberStatus == GroupMemberStatus.Active &&
                                        m.Person.Email != null &&
                                        m.Person.Email != "")
                                 .Select(m => m.Person)
                                 .ToList();
                }

                var errorMessages = new List <string>();

                var recipients = personList.Select(a => new RockEmailMessageRecipient(a, null)).ToList();

                var emailMessage = new RockEmailMessage();
                emailMessage.FromEmail = GlobalAttributesCache.Value("OrganizationEmail");
                emailMessage.Subject   = subject;
                emailMessage.SetRecipients(recipients);
                emailMessage.Message   = message;
                emailMessage.ThemeRoot = themeRoot;
                emailMessage.AppRoot   = appRoot;
                emailMessage.CreateCommunicationRecord = createCommunicationHistory;
                emailMessage.Send(out errorMessages);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, HttpContext.Current);
            }
        }
示例#12
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private void LoadDropDowns(BenevolenceRequest benevolenceRequest)
        {
            dvpRequestStatus.DefinedTypeId    = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.BENEVOLENCE_REQUEST_STATUS)).Id;
            dvpConnectionStatus.DefinedTypeId = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS)).Id;

            if (_caseWorkerGroupGuid.HasValue)
            {
                var personList = new GroupMemberService(new RockContext())
                                 .Queryable("Person, Group")
                                 .Where(gm => gm.Group.Guid == _caseWorkerGroupGuid.Value)
                                 .Select(gm => gm.Person)
                                 .ToList();

                string caseWorkerPersonAliasValue = benevolenceRequest.CaseWorkerPersonAliasId.ToString();
                if (benevolenceRequest.CaseWorkerPersonAlias != null &&
                    benevolenceRequest.CaseWorkerPersonAlias.Person != null &&
                    !personList.Select(p => p.Id).ToList().Contains(benevolenceRequest.CaseWorkerPersonAlias.Person.Id))
                {
                    personList.Add(benevolenceRequest.CaseWorkerPersonAlias.Person);
                }

                ddlCaseWorker.DataSource     = personList.OrderBy(p => p.NickName).ThenBy(p => p.LastName).ToList();
                ddlCaseWorker.DataTextField  = "FullName";
                ddlCaseWorker.DataValueField = "PrimaryAliasId";
                ddlCaseWorker.DataBind();
                ddlCaseWorker.Items.Insert(0, new ListItem());

                ppCaseWorker.Visible  = false;
                ddlCaseWorker.Visible = true;
            }
            else
            {
                ppCaseWorker.Visible  = true;
                ddlCaseWorker.Visible = false;
            }
        }
示例#13
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>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            var settings = new SelectSettings(selection);

            var context = ( RockContext )serviceInstance.Context;

            //
            // Evaluate the Data View that defines the candidate Groups.
            //
            var dataView = DataComponentSettingsHelper.GetDataViewForFilterComponent(settings.DataViewGuid, context);

            var groupService = new GroupService(context);

            var groupQuery = groupService.Queryable();

            if (dataView != null)
            {
                groupQuery = DataComponentSettingsHelper.FilterByDataView(groupQuery, dataView, groupService);
            }
            else
            {
                // Apply a default Group filter to only show Groups that would be visible in a Group List.
                groupQuery = groupQuery.Where(x => x.GroupType.ShowInGroupList);
            }

            var groupKeys = groupQuery.Select(x => x.Id);

            //
            // Construct the Query to return the list of Group Members matching the filter conditions.
            //
            var groupMemberQuery = new GroupMemberService(context).Queryable();

            // Filter By Group.
            groupMemberQuery = groupMemberQuery.Where(x => groupKeys.Contains(x.GroupId));

            // Filter By Group Role Type.
            switch (settings.RoleType)
            {
            case RoleTypeSpecifier.Member:
                groupMemberQuery = groupMemberQuery.Where(x => !x.GroupRole.IsLeader);
                break;

            case RoleTypeSpecifier.Leader:
                groupMemberQuery = groupMemberQuery.Where(x => x.GroupRole.IsLeader);
                break;
            }

            // Filter by Group Member Status.
            if (settings.MemberStatus.HasValue)
            {
                groupMemberQuery = groupMemberQuery.Where(x => x.GroupMemberStatus == settings.MemberStatus.Value);
            }

            //
            // Create a Select Expression to return the Person records referenced by the Group Members.
            //
            var personGroupsQuery = new PersonService(context).Queryable()
                                    .Where(p => groupMemberQuery.Select(gm => gm.PersonId).Contains(p.Id));

            var selectExpression = FilterExpressionExtractor.Extract <Model.Person>(personGroupsQuery, parameterExpression, "p");

            return(selectExpression);
        }
示例#14
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();

            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 = new GroupService(rockContext).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;
                }
            }

            // 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);
                    }

                    gGroups.DataSource = qry
                                         .Select(m => new GroupListRowInfo {
                        Id = m.Group.Id, 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);
                }

                gGroups.DataSource = qryGroups.Select(g => new GroupListRowInfo {
                    Id = g.Id, 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();
            }

            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;
            }
        }
示例#15
0
        public override Expression GetExpression(RockContext context, MemberExpression entityIdProperty, string selection)
        {
            var settings = new FilterSettings(selection);

            //
            // 1. Define Candidate Locations
            //
            bool useDefaultLocationsFilter = true;

            // Get the Location Data View that defines the set of candidates from which proximate Locations can be selected.
            DataView dataView = null;

            if (settings.DataViewGuid.HasValue)
            {
                var dsService = new DataViewService(context);

                dataView = dsService.Get(settings.DataViewGuid.Value);

                if (dataView != null)
                {
                    if (dataView.DataViewFilter == null)
                    {
                        dataView = null;
                    }
                    else
                    {
                        // Verify that the Group Data View does not contain any references to this Data View in any of its components.
                        if (dsService.IsViewInFilter(dataView.Id, dataView.DataViewFilter))
                        {
                            throw new Exception("Filter issue(s): One of the filters contains a circular reference to the Data View itself.");
                        }
                    }
                }
            }

            // Evaluate the Data View that defines the candidate Locations.
            var locationService = new LocationService(context);

            var locationQuery = locationService.Queryable();

            if (dataView != null)
            {
                var paramExpression = locationService.ParameterExpression;

                List <string> errorMessages;

                var whereExpression = dataView.GetExpression(locationService, paramExpression, out errorMessages);

                if (errorMessages.Any())
                {
                    throw new Exception("Filter issue(s): " + errorMessages.AsDelimited("; "));
                }

                locationQuery = locationQuery.Where(paramExpression, whereExpression, null);

                useDefaultLocationsFilter = false;

                // Include child groups?
                //if (true)
                //{
                //    var searchGroupKeys = new HashSet<int>();

                //    var parentGroups = groupQuery.Select(x => x.Id);

                //    foreach (var parentGroupId in parentGroups)
                //    {
                //        var branchKeys = this.GetGroupBranchKeys(groupService, parentGroupId);

                //        searchGroupKeys.UnionWith(branchKeys);
                //    }

                //    groupQuery = groupService.Queryable().Where(x => searchGroupKeys.Contains(x.Id));
                //}
            }

            if (useDefaultLocationsFilter)
            {
                locationQuery = locationQuery.Where(x => !(x.Name == null || x.Name.Trim() == string.Empty));
            }

            // TODO: Remove this
            locationQuery = locationQuery.Where(x => x.Name == "3149-Mount Waverley" || x.Name == "3140-Lilydale");
            //var locationKeys = locationQuery.Select( x => x.Id );

            //
            // 2. Find the Group Locations that are proximate to the candidate Locations and are associated with Family Groups.
            //
            var proximateGroupLocationsBaseQuery = new GroupLocationService(context).Queryable();

            // Filter for Groups that are Families.
            var familyGroupTypeGuid = GroupType.GROUPTYPE_FAMILY.AsGuid();

            proximateGroupLocationsBaseQuery = proximateGroupLocationsBaseQuery.Where(x => x.Group.GroupType.Guid == familyGroupTypeGuid);

            // Filter By Location Type.
            if (settings.LocationTypeGuid.HasValue)
            {
                proximateGroupLocationsBaseQuery = proximateGroupLocationsBaseQuery.Where(x => x.GroupLocationTypeValue.Guid == settings.LocationTypeGuid);
            }

            // Create Queries to find Family Group Locations that are proximate to each of the candidate Locations, then return a union of the result sets.
            // We do this to preserve the link between the candidate Location and the Families located near that candidate Location.
            double proximityInMeters = 0;

            var locations = locationQuery.ToList();

            IQueryable <PersonNearLocationResult> unionQuery = null;

            foreach (var l in locations)
            {
                var groupLocationPredicate = LinqPredicateBuilder.Begin <GroupLocation>();

                if (l.GeoPoint != null)
                {
                    var gp = l.GeoPoint;
                    groupLocationPredicate = groupLocationPredicate.Or(gl => gl.Location.GeoPoint.Distance(gp) <= proximityInMeters);
                }

                if (l.GeoFence != null)
                {
                    var gf = l.GeoFence;
                    groupLocationPredicate =
                        groupLocationPredicate.Or(gl => gl.Location.GeoPoint != null && gl.Location.GeoPoint.Intersects(gf) || gl.Location.GeoPoint.Distance(gf) <= proximityInMeters);
                    groupLocationPredicate =
                        groupLocationPredicate.Or(gl => gl.Location.GeoFence != null && gl.Location.GeoFence.Intersects(gf) || gl.Location.GeoFence.Distance(gf) <= proximityInMeters);
                }

                var proximateGroupLocationsQuery = proximateGroupLocationsBaseQuery.Where(groupLocationPredicate);

                // Return all of the People in the Groups identified in the Group Locations, and the set of candidate Locations their Family Group is associated with.
                var groupMembersOfProximateLocations = new GroupMemberService(context).Queryable()
                                                       .Where(gm => proximateGroupLocationsQuery.Select(gl => gl.GroupId).Contains(gm.GroupId));


                //
                // ** This Query produces the correct results.
                //
                string locationName = l.ToString();

                var personLocationsQuery = new PersonService(context).Queryable()
                                           .Where(p => groupMembersOfProximateLocations.Select(gm => gm.PersonId).Contains(p.Id))
                                           .Select(x => new PersonNearLocationResult
                {
                    Person       = x,
                    LocationName = locationName
                });

                //var result5 = personLocationsQuery.ToList();

                if (unionQuery == null)
                {
                    unionQuery = personLocationsQuery;
                }
                else
                {
                    unionQuery = unionQuery.Union(personLocationsQuery);
                }
            }

            //var finalQuery = unionQuery.Select(pnl => unionQuery.Where(uq => uq.Person.Id == pnl.Person.Id).Select(p => p.LocationName));

            //var resultUnion = unionQuery.ToList();

            var finalQuery = new PersonService(context).Queryable().Select(p => unionQuery.Where(uq => uq.Person.Id == p.Id).Select(x => x.LocationName));

            //var result6 = finalQuery.Where( x => x.Any() ).ToList();

            // Define the Select Expression containing the field output.
            var selectExpression = SelectExpressionExtractor.Extract <Model.Person>(finalQuery, entityIdProperty, "p");

            return(selectExpression);
        }
示例#16
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            // Find all the Group Types
            var groupTypeIds = GetAvailableGroupTypes();

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

            var rockContext = new RockContext();

            SortProperty sortProperty = gGroups.SortProperty;

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

            bool onlySecurityGroups     = GetAttributeValue("LimittoSecurityRoleGroups").AsBoolean();
            bool showDescriptionColumn  = GetAttributeValue("DisplayDescriptionColumn").AsBoolean();
            bool showActiveStatusColumn = GetAttributeValue("DisplayActiveStatusColumn").AsBoolean();
            bool showSystemColumn       = GetAttributeValue("DisplaySystemColumn").AsBoolean();

            if (!showDescriptionColumn)
            {
                gGroups.TooltipField = "Description";
            }

            Dictionary <string, BoundField> boundFields = gGroups.Columns.OfType <BoundField>().ToDictionary(a => a.DataField);

            boundFields["GroupTypeName"].Visible = GetAttributeValue("DisplayGroupTypeColumn").AsBoolean();
            boundFields["Description"].Visible   = showDescriptionColumn;

            Dictionary <string, BoolField> boolFields = gGroups.Columns.OfType <BoolField>().ToDictionary(a => a.DataField);

            boolFields["IsActive"].Visible = showActiveStatusColumn;
            boolFields["IsSystem"].Visible = showSystemColumn;

            // Person context will exist if used on a person detail page
            var personContext = ContextEntity <Person>();

            if (personContext != null)
            {
                boundFields["GroupRole"].Visible   = true;
                boundFields["DateAdded"].Visible   = true;
                boundFields["MemberCount"].Visible = false;

                gGroups.Actions.ShowAdd = false;
                gGroups.IsDeleteEnabled = false;
                gGroups.Columns.OfType <DeleteField>().ToList().ForEach(f => f.Visible = false);

                var qry = new GroupMemberService(rockContext).Queryable()
                          .Where(m =>
                                 m.PersonId == personContext.Id &&
                                 groupTypeIds.Contains(m.Group.GroupTypeId) &&
                                 (!onlySecurityGroups || m.Group.IsSecurityRole));

                // Filter by active/inactive
                if (ddlActiveFilter.SelectedIndex > -1)
                {
                    if (ddlActiveFilter.SelectedValue == "inactive")
                    {
                        qry = qry.Where(a => a.Group.IsActive == false);
                    }
                    else if (ddlActiveFilter.SelectedValue == "active")
                    {
                        qry = qry.Where(a => a.Group.IsActive == true);
                    }
                }

                gGroups.DataSource = qry
                                     .Select(m => new
                {
                    Id             = m.Group.Id,
                    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.GroupRole.Name,
                    DateAdded      = m.CreatedDateTime,
                    IsActive       = m.Group.IsActive,
                    MemberCount    = 0
                })
                                     .Sort(sortProperty)
                                     .ToList();
            }
            else
            {
                bool canEdit = IsUserAuthorized(Authorization.EDIT);
                gGroups.Actions.ShowAdd = canEdit;
                gGroups.IsDeleteEnabled = canEdit;

                boundFields["GroupRole"].Visible   = false;
                boundFields["DateAdded"].Visible   = false;
                boundFields["MemberCount"].Visible = true;

                var qry = new GroupService(rockContext).Queryable()
                          .Where(g =>
                                 groupTypeIds.Contains(g.GroupTypeId) &&
                                 (!onlySecurityGroups || g.IsSecurityRole));

                // Filter by active/inactive
                if (ddlActiveFilter.SelectedIndex > -1)
                {
                    if (ddlActiveFilter.SelectedValue == "inactive")
                    {
                        qry = qry.Where(a => a.IsActive == false);
                    }
                    else if (ddlActiveFilter.SelectedValue == "active")
                    {
                        qry = qry.Where(a => a.IsActive == true);
                    }
                }

                gGroups.DataSource = qry.Select(g => new
                {
                    Id             = g.Id,
                    Name           = g.Name,
                    GroupTypeName  = g.GroupType.Name,
                    GroupOrder     = g.Order,
                    GroupTypeOrder = g.GroupType.Order,
                    Description    = g.Description,
                    IsSystem       = g.IsSystem,
                    IsActive       = g.IsActive,
                    GroupRole      = string.Empty,
                    DateAdded      = DateTime.MinValue,
                    MemberCount    = g.Members.Count()
                })
                                     .Sort(sortProperty)
                                     .ToList();
            }

            gGroups.DataBind();
        }
        private void BindFamilies(RockContext rockContext, IQueryable <Person> personQry, IQueryable <int> dataviewPersonIdQry)
        {
            var familyGroupType = GroupTypeCache.Get(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.Get(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.Get().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;
        }
示例#18
0
        public void Execute(IJobExecutionContext context)
        {
            var    dataMap   = context.JobDetail.JobDataMap;
            string apiKey    = dataMap.GetString("APIKey");
            string listName  = dataMap.GetString("ListName");
            string groupGuid = dataMap.GetString("group");
            int    timeout   = dataMap.GetIntFromString("Timeout");

            var group = groupGuid.AsGuidOrNull();

            //Check API Key exists and group guid is not null
            if (string.IsNullOrWhiteSpace(apiKey) || !group.HasValue || string.IsNullOrWhiteSpace(listName))
            {
                return;
            }

            //Check all the custom fields have been created for the SendGrid marketing campaign.
            bool fieldsExist = SyncHelper.CheckCustomFields(apiKey);

            if (!fieldsExist)
            {
                return;
            }

            int?listId = SyncHelper.EnsureListExists(apiKey, listName);

            if (!listId.HasValue)
            {
                throw new Exception("Unable to identify list identifier");
            }

            var rockContext = new RockContext();

            rockContext.Database.CommandTimeout = 720;

            int activeRecordStatusValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE).Id;

            var groupMemberAliases = new GroupMemberService(rockContext)
                                     .Queryable()
                                     .AsNoTracking()
                                     .Where(gm => gm.Group.Guid == group.Value)
                                     .Select(gm => gm.Person)
                                     .Where(p => !p.IsDeceased && p.RecordStatusValueId == activeRecordStatusValueId && p.IsEmailActive && p.Email != null && p.Email != string.Empty && p.EmailPreference == EmailPreference.EmailAllowed)
                                     .Select(p => p.Aliases.FirstOrDefault());

            var groupMemberAliasIds = groupMemberAliases.Select(a => a.Id);

            var previouslySyncedPersonAliasIds = new PersonAliasHistoryService(rockContext).GetPreviouslySyncedPersonAliasIds(groupMemberAliasIds);

            var notYetSynced = SyncHelper.FindNotYetSyncedPersonAlises(rockContext, groupMemberAliasIds, previouslySyncedPersonAliasIds);

            if (notYetSynced.Any())
            {
                SyncHelper.SyncContacts(notYetSynced, apiKey);
            }

            if (groupMemberAliasIds.Any())
            {
                SyncHelper.EnsureValidPeopleOnly(groupMemberAliasIds, listId.Value, apiKey);
                SyncHelper.AddPeopleToList(groupMemberAliases, listId.Value, apiKey);
            }


            context.Result = "Group synced successfully";
        }
        public FinancialStatementGeneratorUploadGivingStatementResult UploadGivingStatementDocument([FromBody] FinancialStatementGeneratorUploadGivingStatementData uploadGivingStatementData)
        {
            var rockContext = new RockContext();

            var saveOptions = uploadGivingStatementData?.FinancialStatementIndividualSaveOptions;

            if (saveOptions == null)
            {
                throw new FinancialGivingStatementArgumentException("FinancialStatementIndividualSaveOptions must be specified");
            }

            if (!saveOptions.SaveStatementsForIndividuals)
            {
                throw new FinancialGivingStatementArgumentException("FinancialStatementIndividualSaveOptions.SaveStatementsForIndividuals is not enabled.");
            }

            var documentTypeId = saveOptions.DocumentTypeId;

            if (!documentTypeId.HasValue)
            {
                throw new FinancialGivingStatementArgumentException("Document Type must be specified");
            }

            var documentType = new DocumentTypeService(rockContext)
                               .Queryable()
                               .AsNoTracking()
                               .Where(dt => dt.Id == documentTypeId.Value)
                               .Select(a => new
            {
                BinaryFileTypeId = ( int? )a.BinaryFileTypeId
            })
                               .FirstOrDefault();

            if (documentType == null)
            {
                throw new FinancialGivingStatementArgumentException("DocumentType must be specified");
            }

            if (documentType.BinaryFileTypeId == null)
            {
                throw new FinancialGivingStatementArgumentException("DocumentType.BinaryFileType must be specified");
            }

            var pdfData = uploadGivingStatementData.PDFData;

            string fileName = saveOptions.DocumentName + ".pdf";

            var financialStatementGeneratorRecipient = uploadGivingStatementData.FinancialStatementGeneratorRecipient;

            if (financialStatementGeneratorRecipient == null)
            {
                throw new FinancialGivingStatementArgumentException("FinancialStatementGeneratorRecipient must be specified");
            }

            var documentName = saveOptions.DocumentName;

            List <int> documentPersonIds;

            if (financialStatementGeneratorRecipient.PersonId.HasValue)
            {
                // If we are saving for a person that gives an individual, just give document to that person (ignore the FinancialStatementIndividualSaveOptionsSaveFor option)
                // only upload the document to the individual person
                documentPersonIds = new List <int>();
                documentPersonIds.Add(financialStatementGeneratorRecipient.PersonId.Value);
            }
            else
            {
                var groupId = financialStatementGeneratorRecipient.GroupId;
                var givingFamilyMembersQuery = new GroupMemberService(rockContext).GetByGroupId(groupId, false);

                // limit to family members within the same giving group
                givingFamilyMembersQuery = givingFamilyMembersQuery.Where(a => a.Person.GivingGroupId.HasValue && a.Person.GivingGroupId == groupId);

                if (saveOptions.DocumentSaveFor == FinancialStatementGeneratorOptions.FinancialStatementIndividualSaveOptions.FinancialStatementIndividualSaveOptionsSaveFor.AllActiveAdultsInGivingGroup)
                {
                    documentPersonIds = givingFamilyMembersQuery
                                        .Where(a => a.Person.AgeClassification == AgeClassification.Adult).Select(a => a.PersonId).ToList();
                }
                else if (saveOptions.DocumentSaveFor == FinancialStatementGeneratorOptions.FinancialStatementIndividualSaveOptions.FinancialStatementIndividualSaveOptionsSaveFor.AllActiveFamilyMembersInGivingGroup)
                {
                    documentPersonIds = givingFamilyMembersQuery
                                        .Select(a => a.PersonId).ToList();
                }
                else if (saveOptions.DocumentSaveFor == FinancialStatementGeneratorOptions.FinancialStatementIndividualSaveOptions.FinancialStatementIndividualSaveOptionsSaveFor.PrimaryGiver)
                {
                    // Set document for PrimaryGiver (aka Head of Household).
                    // Note that HeadOfHouseHold would calculated based on family members within the same giving group
                    var headOfHouseHoldPersonId = givingFamilyMembersQuery.GetHeadOfHousehold(s => ( int? )s.PersonId);
                    documentPersonIds = new List <int>();
                    if (headOfHouseHoldPersonId.HasValue)
                    {
                        documentPersonIds.Add(headOfHouseHoldPersonId.Value);
                    }
                }
                else
                {
                    // shouldn't happen
                    documentPersonIds = new List <int>();
                }
            }

            var today    = RockDateTime.Today;
            var tomorrow = today.AddDays(1);

            foreach (var documentPersonId in documentPersonIds)
            {
                // Create the document, linking the entity and binary file.
                if (saveOptions.OverwriteDocumentsOfThisTypeCreatedOnSameDate == true)
                {
                    using (var deleteDocContext = new RockContext())
                    {
                        var deleteDocumentService = new DocumentService(deleteDocContext);

                        // See if there is an existing one.
                        // Note include BinaryFile in the Get since we'll have to mark it temporary if it exists.
                        var existingDocument = deleteDocumentService.Queryable().Where(
                            a => a.DocumentTypeId == documentTypeId.Value &&
                            a.EntityId == documentPersonId &&
                            a.CreatedDateTime.HasValue &&
                            a.CreatedDateTime >= today && a.CreatedDateTime < tomorrow)
                                               .Include(a => a.BinaryFile).FirstOrDefault();

                        // NOTE: Delete vs update since we normally don't change the contents of documents/binary files once they've been created
                        if (existingDocument != null)
                        {
                            deleteDocumentService.Delete(existingDocument);
                            deleteDocContext.SaveChanges();
                        }
                    }
                }

                // Create the binary file.
                var binaryFile = new BinaryFile
                {
                    BinaryFileTypeId = documentType.BinaryFileTypeId,
                    MimeType         = "application/pdf",
                    FileName         = fileName,
                    FileSize         = pdfData.Length,
                    IsTemporary      = false,
                    ContentStream    = new MemoryStream(pdfData)
                };

                new BinaryFileService(rockContext).Add(binaryFile);
                rockContext.SaveChanges();

                Document document = new Document
                {
                    DocumentTypeId = documentTypeId.Value,
                    EntityId       = documentPersonId,
                    PurposeKey     = saveOptions.DocumentPurposeKey,
                    Name           = saveOptions.DocumentName,
                    Description    = saveOptions.DocumentDescription
                };

                document.SetBinaryFile(binaryFile.Id, rockContext);

                var documentService = new DocumentService(rockContext);

                documentService.Add(document);
            }

            rockContext.SaveChanges();

            return(new FinancialStatementGeneratorUploadGivingStatementResult
            {
                NumberOfIndividuals = documentPersonIds.Count
            });
        }
示例#20
0
        /// <summary>
        /// Updates the note watch notification digest.
        /// </summary>
        /// <param name="personIdNotificationDigestList">The person identifier notification digest list.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="noteId">The note identifier.</param>
        private void UpdateNoteWatchNotificationDigest(Dictionary <int, NoteWatchPersonToNotifyList> personIdNotificationDigestList, RockContext rockContext, int noteId)
        {
            var noteService = new Rock.Model.NoteService(rockContext);

            var note = noteService.Queryable().Include(a => a.EditedByPersonAlias).FirstOrDefault(a => a.Id == noteId);

            if (note == null || !note.EntityId.HasValue)
            {
                // shouldn't' happen
                return;
            }

            var noteType = NoteTypeCache.Get(note.NoteTypeId);

            // make sure the note's notetype has an EntityTypeId (is should, but just in case it doesn't)
            int?noteEntityTypeId = noteType?.EntityTypeId;

            if (!noteEntityTypeId.HasValue)
            {
                return;
            }

            var noteWatchService = new Rock.Model.NoteWatchService(rockContext);

            // narrow it down to NoteWatches for the same EntityType as the Note
            var noteWatchesQuery = noteWatchService.Queryable()
                                   .Where(a =>
                                          (a.EntityTypeId.HasValue && a.EntityTypeId.Value == noteEntityTypeId.Value) ||
                                          (a.NoteTypeId.HasValue && a.NoteType.EntityTypeId == noteEntityTypeId));

            // narrow it down to either note watches on..
            // 1) specific Entity
            // 2) specific Note
            // 3) any note of the NoteType
            // 4) any note on the EntityType

            // specific Entity
            noteWatchesQuery = noteWatchesQuery.Where(a =>
                                                      (a.EntityId == null) ||
                                                      (note.EntityId.HasValue && a.EntityId.Value == note.EntityId.Value));

            // or specifically for this Note's ParentNote (a reply to the Note)
            noteWatchesQuery = noteWatchesQuery.Where(a =>
                                                      (a.NoteId == null) ||
                                                      (note.ParentNoteId.HasValue && a.NoteId.Value == note.ParentNoteId));

            // or specifically for this note's note type
            noteWatchesQuery = noteWatchesQuery.Where(a =>
                                                      (a.NoteTypeId == null) ||
                                                      (a.NoteTypeId.Value == note.NoteTypeId));

            // if there are any NoteWatches that relate to this note, process them
            if (noteWatchesQuery.Any())
            {
                var noteWatchesForNote = noteWatchesQuery.Include(a => a.WatcherPersonAlias.Person).AsNoTracking().ToList();
                List <NoteWatchPersonToNotify> noteWatchPersonToNotifyListAll = new List <NoteWatchPersonToNotify>();

                // loop thru Watches to get a list of people to possibly notify/override
                foreach (var noteWatch in noteWatchesForNote)
                {
                    // if a specific person is the watcher, add them
                    var watcherPerson = noteWatch.WatcherPersonAlias?.Person;
                    if (watcherPerson != null)
                    {
                        noteWatchPersonToNotifyListAll.Add(new NoteWatchPersonToNotify(watcherPerson, note, noteWatch));
                    }

                    if (noteWatch.WatcherGroupId.HasValue)
                    {
                        var watcherPersonsFromGroup = new GroupMemberService(rockContext).Queryable()
                                                      .Where(a => a.GroupMemberStatus == GroupMemberStatus.Active && a.GroupId == noteWatch.WatcherGroupId.Value)
                                                      .Select(a => a.Person).ToList();

                        if (watcherPersonsFromGroup.Any())
                        {
                            noteWatchPersonToNotifyListAll.AddRange(watcherPersonsFromGroup.Select(a => new NoteWatchPersonToNotify(a, note, noteWatch)));
                        }
                    }
                }

                var noteWatchPersonToNotifyList = noteWatchPersonToNotifyListAll.Where(a => a.NoteWatch.IsWatching).ToList();
                var noteWatchPersonToNotifyListWatchDisabled = noteWatchPersonToNotifyListAll.Where(a => !a.NoteWatch.IsWatching).ToList();
                var noteWatchPersonToNotifyListNoOverride    = noteWatchPersonToNotifyList.Where(a => a.NoteWatch.AllowOverride == false).ToList();

                foreach (var noteWatchPersonToNotify in noteWatchPersonToNotifyList)
                {
                    // check if somebody wanted to specifically NOT watch this (and there isn't another watch that prevents overrides)
                    if (noteWatchPersonToNotifyListWatchDisabled.Any(a => a.Person.Id == noteWatchPersonToNotify.Person.Id))
                    {
                        // Person Requested to NOT watch, now make sure that they aren't force to watch based on Override = False
                        if (!noteWatchPersonToNotifyListNoOverride.Any(a => a.Person.Id == noteWatchPersonToNotify.Person.Id))
                        {
                            // person requested to NOT watch, and there aren't any overrides to prevent that, so jump out to the next one
                            continue;
                        }
                    }

                    NoteWatchPersonToNotifyList personToNotifyList;
                    if (personIdNotificationDigestList.ContainsKey(noteWatchPersonToNotify.Person.Id))
                    {
                        personToNotifyList = personIdNotificationDigestList[noteWatchPersonToNotify.Person.Id] ?? new NoteWatchPersonToNotifyList(noteWatchPersonToNotify.Person);
                    }
                    else
                    {
                        personToNotifyList = new NoteWatchPersonToNotifyList(noteWatchPersonToNotify.Person);
                        personIdNotificationDigestList.Add(noteWatchPersonToNotify.Person.Id, personToNotifyList);
                    }

                    // only include the note if the watcher person is authorized to view the note
                    if (noteWatchPersonToNotify.Note.IsAuthorized(Rock.Security.Authorization.VIEW, noteWatchPersonToNotify.Person))
                    {
                        personToNotifyList.Add(noteWatchPersonToNotify);
                    }
                }
            }
        }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();
            // Get the team that should be serving this week
            string weekTeam = "Team " + com.bricksandmortarstudio.TheCrossing.Utils.ServingWeek.GetTeamNumber();

            // Get the group members who should be serving
            var attributeService         = new AttributeService(rockContext);
            var groupMemberEntityType    = EntityTypeCache.Read(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid());
            var assignedTeamAttributeIds =
                attributeService.GetByEntityTypeId(
                    EntityTypeCache.Read(Rock.SystemGuid.EntityType.GROUP_MEMBER.AsGuid()).Id).Where(a => a.Key == "AssignedTeam").Select(a => a.Id);

            var assignedServicesAttributeIds =
                attributeService.GetByEntityTypeId(groupMemberEntityType.Id).Where(a => a.Key == "AssignedServices").Select(a => a.Id);

            var attributeValueService = new AttributeValueService(rockContext);
            var groupMemberIds        = new List <int>();

            foreach (int attributeId in assignedTeamAttributeIds)
            {
                var attributeValues = attributeValueService.GetByAttributeId(attributeId).AsQueryable().AsNoTracking().Where(av => av.Value.Contains(weekTeam));
                groupMemberIds.AddRange(attributeValues.Where(av => av.EntityId != null).Select(av => av.EntityId.Value));
            }

            // Find the group member information to present
            IEnumerable <GroupMember> query = new GroupMemberService(rockContext).GetListByIds(groupMemberIds);


            //Filtering to a specific group branch

            var groupService = new GroupService(rockContext);
            var group        = hfGroupGuid.Value.AsGuidOrNull() != null
                ? groupService.GetByGuid(hfGroupGuid.Value.AsGuid())
                : groupService.Get(gFilter.GetUserPreference("Group").AsInteger());

            if (group != null)
            {
                var validGroupIds = new List <int> {
                    group.Id
                };
                validGroupIds.AddRange(groupService.GetAllDescendents(group.Id).Select(g => g.Id));

                query = query.Where(gm => validGroupIds.Contains(gm.GroupId));
            }


            var allScheduledPeople = query.Select(gm =>
                                                  new GroupAndPerson
            {
                Name         = gm.Person.FullName,
                GroupName    = gm.Group.Name,
                ParentGroup  = gm.Group.ParentGroup,
                ServiceTimes = attributeValueService.Queryable().AsNoTracking().Where(a => a.EntityId == gm.Id && assignedServicesAttributeIds.Contains(a.AttributeId)).FirstOrDefault()
            });

            // Sort and bind
            var sortProperty = gList.SortProperty;

            if (sortProperty == null)
            {
                gList.DataSource = allScheduledPeople.OrderBy(gp => gp.GroupName).ToList();
            }
            else
            {
                gList.DataSource = allScheduledPeople.AsQueryable().Sort(sortProperty).ToList();
            }
            gList.DataBind();
        }
        /// <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>();

            Guid?  groupGuid   = null;
            string filterValue = string.Empty;
            string filterKey   = string.Empty;

            // get the group attribute
            groupGuid = GetAttributeValue(action, "SelectionGroup").AsGuid();

            if (!groupGuid.HasValue)
            {
                errorMessages.Add("The selection group could not be found!");
            }

            // get filter key
            filterKey = GetAttributeValue(action, "GroupMemberAttributeKey");

            // get the filter value
            filterValue = GetAttributeValue(action, "FilterValue");
            Guid?filterValueGuid = filterValue.AsGuidOrNull();

            if (filterValueGuid.HasValue)
            {
                filterValue = action.GetWorklowAttributeValue(filterValueGuid.Value);
            }
            else
            {
                filterValue = filterValue.ResolveMergeFields(GetMergeFields(action));
            }

            // get group members
            var qry = new GroupMemberService(rockContext).Queryable().AsNoTracking()
                      .Where(g => g.Group.Guid == groupGuid);

            if (!string.IsNullOrWhiteSpace(filterKey))
            {
                qry = qry.WhereAttributeValue(rockContext, filterKey, filterValue);
            }

            var groupMembers = qry.Select(g => new {
                g.Person.NickName,
                g.Person.LastName,
                g.Person.SuffixValueId,
                PrimaryAliasGuid = g.Person.Aliases.FirstOrDefault().Guid
            })
                               .ToList();

            if (groupMembers.Count() > 0)
            {
                // get random group member from options
                Random rnd = new Random();
                int    r   = rnd.Next(groupMembers.Count);

                var selectedGroupMember = groupMembers[r];

                // set value
                Guid selectPersonGuid = GetAttributeValue(action, "SelectedPerson").AsGuid();
                if (!selectPersonGuid.IsEmpty())
                {
                    var selectedPersonAttribute = AttributeCache.Read(selectPersonGuid, rockContext);
                    if (selectedPersonAttribute != null)
                    {
                        // If this is a person type attribute
                        if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Read(Rock.SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectPersonGuid, selectedGroupMember.PrimaryAliasGuid.ToString());
                        }
                        else if (selectedPersonAttribute.FieldTypeId == FieldTypeCache.Read(Rock.SystemGuid.FieldType.TEXT.AsGuid(), rockContext).Id)
                        {
                            SetWorkflowAttributeValue(action, selectPersonGuid, Person.FormatFullName(selectedGroupMember.NickName, selectedGroupMember.LastName, selectedGroupMember.SuffixValueId));
                        }
                    }
                }
            }
            else
            {
                errorMessages.Add("No group member for the selected campus could be found.");
            }

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

            return(true);
        }
示例#23
0
文件: Ncoa.cs 项目: kra3889/rockrms
        /// <summary>
        /// Gets the addresses.
        /// </summary>
        /// <param name="dataViewId">The data view identifier.</param>
        /// <returns>Directory of addresses</returns>
        public Dictionary <int, PersonAddressItem> GetAddresses(int?dataViewId)
        {
            if (!dataViewId.HasValue)
            {
                throw new Exception("Get Address: No Person Data View has been set. Please check System Settings > Spark Data Settings.");
            }

            using (RockContext rockContext = new RockContext())
            {
                var familyGroupType = GroupTypeCache.Get(SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid());
                var homeLoc         = DefinedValueCache.Get(SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());
                var inactiveStatus  = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE.AsGuid());

                if (familyGroupType != null && homeLoc != null && inactiveStatus != null)
                {
                    var groupMembers = new GroupMemberService(rockContext)
                                       .Queryable().AsNoTracking()
                                       .Where(m =>
                                              m.Group.GroupTypeId == familyGroupType.Id &&                            // SystemGuid.GroupType.GROUPTYPE_FAMILY
                                              m.Person.RecordStatusValueId != inactiveStatus.Id &&                    // SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE
                                              m.Group.GroupLocations.Any(gl => gl.GroupLocationTypeValueId.HasValue &&
                                                                         gl.GroupLocationTypeValueId == homeLoc.Id)); // DefinedValueCache.Get( SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME

                    var peopleHomelocation = groupMembers.Select(m => new
                    {
                        m.PersonId,
                        m.GroupId,
                        m.Person.FirstName,
                        m.Person.LastName,
                        m.Person.Aliases,
                        HomeLocation = m.Group.GroupLocations
                                       .Where(gl =>
                                              gl.GroupLocationTypeValueId.HasValue &&
                                              gl.GroupLocationTypeValueId == homeLoc.Id) // DefinedValueCache.Get( SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME
                                       .Select(gl => new
                        {
                            gl.LocationId,
                            gl.Location.Street1,
                            gl.Location.Street2,
                            gl.Location.City,
                            gl.Location.State,
                            gl.Location.PostalCode,
                            gl.Location.Country
                        }).FirstOrDefault()
                    }).Where(m => m.HomeLocation != null).DistinctBy(m => m.PersonId);

                    if (dataViewId.HasValue)
                    {
                        var dataViewQuery = DataViewPeopleDirectory(dataViewId.Value, rockContext);
                        peopleHomelocation = peopleHomelocation.Where(p => dataViewQuery.ContainsKey(p.PersonId));
                    }

                    return(peopleHomelocation
                           .Select(g => new
                    {
                        g.PersonId,
                        HomeLocation = new PersonAddressItem()
                        {
                            PersonId = g.PersonId,
                            FamilyId = g.GroupId,
                            LocationId = g.HomeLocation.LocationId,
                            PersonAliasId = g.Aliases.Count == 0 ? 0 : g.Aliases.FirstOrDefault().Id,
                            FirstName = g.FirstName,
                            LastName = g.LastName,
                            Street1 = g.HomeLocation.Street1,
                            Street2 = g.HomeLocation.Street2,
                            City = g.HomeLocation.City,
                            State = g.HomeLocation.State,
                            PostalCode = g.HomeLocation.PostalCode,
                            Country = g.HomeLocation.Country
                        }
                    })
                           .ToDictionary(k => k.PersonId, v => v.HomeLocation));
                }

                throw new Exception("Get Address: Could not find expected constant, type or value");
            }
        }