コード例 #1
0
        public List <TLineEntity> GetLineInfoListByQueryModel(LineQuery lineQuery)
        {
            var mResult = new List <TLineEntity>();

            using (IDbConnection conn = new SqlConnection(GetConnstr))
            {
                StringBuilder strSql = new StringBuilder("Select * from tLine where 1=1 ");

                //if (userQuery.datemin != null && userQuery.datemin != new DateTime(1900, 1, 1))
                //{
                //    strSql.Append(" and  CreateDate>=@datemin ");
                //}
                //if (userQuery.datemax != null && userQuery.datemax != new DateTime(1900, 1, 1))
                //{
                //    strSql.Append(" and  CreateDate<@datemax ");
                //}

                if (!string.IsNullOrWhiteSpace(lineQuery.keyWords))
                {
                    strSql.Append(" and  (LCode=@keyWords or LName=@keyWords or LFullName=@keyWords or LType=@keyWords) ");
                    lineQuery.keyWords = lineQuery.keyWords.Trim();
                }
                var param = new
                {
                    lineQuery.keyWords
                };

                mResult = conn.Query <TLineEntity>(strSql.ToString(), param).ToList();
            }
            return(mResult);
        }
コード例 #2
0
        public List <TTaskEntity> GetTTaskList(LineQuery lineQuery)
        {
            var mResult = new List <TTaskEntity>();

            using (IDbConnection conn = new SqlConnection(GetConnstr))
            {
                StringBuilder strSql = new StringBuilder("Select * from tTask  where 1=1 ");


                if (!string.IsNullOrWhiteSpace(lineQuery.keyWords))
                {
                    strSql.Append(" and  (BillNO=@keyWords or TName=@keyWords or LineCode = @keyWords or ItemCode=@keyWords) ");
                }
                var param = new
                {
                    keyWords = lineQuery.keyWords
                };

                mResult = conn.Query <TTaskEntity>(strSql.ToString(), param).ToList();
            }
            return(mResult);
        }
コード例 #3
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);

            _rockContext = new RockContext();

            int groupId = PageParameter("GroupId").AsInteger();

            _group = new GroupService(_rockContext)
                     .Queryable("GroupLocations").AsNoTracking()
                     .FirstOrDefault(g => g.Id == groupId);

            if (_group != null && (_group.IsAuthorized(Authorization.VIEW, CurrentPerson) || LineQuery.IsGroupInPersonsLine(_group, CurrentPerson)))
            {
                _group.LoadAttributes(_rockContext);
                _canView = true;

                rFilter.ApplyFilterClick      += rFilter_ApplyFilterClick;
                gOccurrences.DataKeyNames      = new string[] { "Date", "ScheduleId", "LocationId" };
                gOccurrences.Actions.AddClick += gOccurrences_Add;
                gOccurrences.GridRebind       += gOccurrences_GridRebind;
                gOccurrences.RowDataBound     += gOccurrences_RowDataBound;

                // make sure they have Auth to edit the block OR edit to the Group
                bool canEditBlock = IsUserAuthorized(Authorization.EDIT) || _group.IsAuthorized(Authorization.EDIT, this.CurrentPerson);
                gOccurrences.Actions.ShowAdd = canEditBlock && GetAttributeValue("AllowAdd").AsBoolean();
                gOccurrences.IsDeleteEnabled = canEditBlock;
            }

            _allowCampusFilter = GetAttributeValue("AllowCampusFilter").AsBoolean();
            bddlCampus.Visible = _allowCampusFilter;
            if (_allowCampusFilter)
            {
                bddlCampus.DataSource = CampusCache.All();
                bddlCampus.DataBind();
                bddlCampus.Items.Insert(0, new ListItem("All Campuses", "0"));
            }
        }
コード例 #4
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);

            RegisterScript();

            _rockContext = new RockContext();

            int groupId = PageParameter("GroupId").AsInteger();

            _group = new GroupService(_rockContext)
                     .Queryable("GroupType,Schedule").AsNoTracking()
                     .FirstOrDefault(g => g.Id == groupId);

            if (_group != null && CurrentPerson != null && (_group.IsAuthorized(Authorization.EDIT, CurrentPerson) || LineQuery.IsGroupInPersonsLine(_group, CurrentPerson)))
            {
                lHeading.Text = " Attendance: " + _group.Name;
                _canEdit      = true;
            }

            _allowAdd = GetAttributeValue("AllowAdd").AsBoolean();

            _allowCampusFilter = GetAttributeValue("AllowCampusFilter").AsBoolean();
            bddlCampus.Visible = _allowCampusFilter;
            if (_allowCampusFilter)
            {
                bddlCampus.DataSource = CampusCache.All();
                bddlCampus.DataBind();
                bddlCampus.Items.Insert(0, new ListItem("All Campuses", "0"));
            }
        }
コード例 #5
0
        private void ListGroups()
        {
            var rockContext = new RockContext();

            var cellGroupsInLine    = LineQuery.GetCellGroupsInLine(CurrentPerson, rockContext, false).ToList();
            int responsibilityCount = cellGroupsInLine.Count;
            var cellGroupdTypeGuid  = org.kcionline.bricksandmortarstudio.SystemGuid.GroupType.CELL_GROUP.AsGuid();

            var cellMemberGroups =
                new GroupMemberService(rockContext).Queryable()
                .Where(
                    gm =>
                    gm.PersonId == CurrentPersonId &&
                    gm.Group.GroupType.Guid == cellGroupdTypeGuid).Select(gm => gm.Group).ToList();

            var allCellGroups = cellGroupsInLine.Union(cellMemberGroups);

            var groups = new List <GroupInvolvementSummary>();

            int totalCount             = 0;
            int amLeaderOfMembersCount = 0;
            int amLeaderOfGroupCount   = 0;

            foreach (var group in allCellGroups)
            {
                bool isLeader = group.Members.Any(gm => gm.GroupRole.IsLeader && gm.PersonId == CurrentPersonId);
                if (isLeader)
                {
                    amLeaderOfMembersCount += group.Members.Count;
                    amLeaderOfGroupCount++;
                }
                bool isMember = group.Members.Any(p => p.Person == CurrentPerson);
                totalCount += group.Members.Count;
                groups.Add(new GroupInvolvementSummary
                {
                    Group       = group,
                    IsLeader    = isLeader,
                    MemberCount = group.Members.Count,
                    IsMember    = isMember
                });
            }

            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            mergeFields.Add("Groups", groups.OrderBy(gis => gis.Group.Name));
            mergeFields.Add("TotalCount", totalCount);
            mergeFields.Add("ResponsibilityCount", responsibilityCount);
            mergeFields.Add("LeaderOfMemberCount", amLeaderOfMembersCount);
            mergeFields.Add("LeaderOfGroupCount", amLeaderOfGroupCount);
            var linkedPages = new Dictionary <string, object>();

            linkedPages.Add("DetailPage", LinkedPageRoute("DetailPage"));
            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);
        }
コード例 #6
0
        public ActionResult TaskListResult(LineQuery lineQuery)
        {
            var taskList = tTaskRepository.GetTTaskList(lineQuery);

            return(View(taskList));
        }
コード例 #7
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            nbBox.Visible = false;
            var personId = Request.QueryString["personId"].AsIntegerOrNull();

            if (!Request.QueryString["success"].IsNullOrWhiteSpace() && !Request.QueryString["type"].IsNullOrWhiteSpace() && personId != null && LineQuery.IsPersonInLeadersLine(personId.Value, CurrentPerson))
            {
                var person = new PersonService(new RockContext()).Get(personId.Value);

                switch (Request.QueryString["type"])
                {
                case "transfer":
                    nbBox.Title = person.FullName;
                    nbBox.Text  = " has been transferred successfully";
                    break;

                case "place":
                    nbBox.Title = person.FullName;
                    nbBox.Text  = " has been placed into their group successfully";
                    break;
                }
                nbBox.Visible     = true;
                nbBox.Dismissable = true;
            }
            if (!Page.IsPostBack)
            {
                SetFilter();
                BindGrid();
            }
        }
コード例 #8
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext        = new RockContext();
            var groupMemberService = new GroupMemberService(rockContext);
            var searchPerson       = CurrentPerson;

            // If the person is a group leader, get their coordinator so they can view as them
            var consolidatorCoordinatorGuid =
                org.kcionline.bricksandmortarstudio.SystemGuid.GroupTypeRole.CONSOLIDATION_COORDINATOR.AsGuid();
            var cellGroupType =
                GroupTypeCache.Read(org.kcionline.bricksandmortarstudio.SystemGuid.GroupType.CELL_GROUP.AsGuid());

            if (
                groupMemberService.Queryable()
                .Any(gm => gm.GroupRole.IsLeader && gm.Group.GroupTypeId == cellGroupType.Id))
            {
                var baseGroup =
                    // ReSharper disable once PossibleNullReferenceException
                    groupMemberService.Queryable()
                    .FirstOrDefault(
                        gm => gm.GroupRole.IsLeader && gm.Group.GroupTypeId == cellGroupType.Id)
                    .Group;
                while (baseGroup != null)
                {
                    var coordinator =
                        baseGroup.Members.FirstOrDefault(gm => gm.GroupRole.Guid == consolidatorCoordinatorGuid);
                    if (coordinator != null)
                    {
                        searchPerson = coordinator.Person;
                        break;
                    }
                    baseGroup = baseGroup.ParentGroup;
                }
            }

            // filtering
            var connectionRequests = LineQuery.GetPeopleInLineFollowUpRequests(searchPerson);

            if (drpDates.LowerValue.HasValue)
            {
                connectionRequests = connectionRequests.Where(a => a.CreatedDateTime >= drpDates.LowerValue.Value);
            }

            if (drpDates.UpperValue.HasValue)
            {
                DateTime upperDate = drpDates.UpperValue.Value.Date.AddDays(1);
                connectionRequests = connectionRequests.Where(a => a.CreatedDateTime < upperDate);
            }

            if (!String.IsNullOrEmpty(ddlStatus.SelectedValue))
            {
                connectionRequests = connectionRequests.Where(cr => cr.ConnectionStatus.Name == ddlStatus.SelectedValue);
            }

            if (ppConsolidator.SelectedValue.HasValue)
            {
                connectionRequests =
                    connectionRequests.Where(
                        cr => cr.ConnectorPersonAlias.PersonId == ppConsolidator.SelectedValue.Value);
            }

            // end filtering

            var groupTypeRoleService = new GroupTypeRoleService(rockContext);
            var groupTypeRole        =
                groupTypeRoleService.Get(
                    org.kcionline.bricksandmortarstudio.SystemGuid.GroupTypeRole.CONSOLIDATED_BY.AsGuid());

            var followUps = new List <FollowUp>(connectionRequests.Count());

            foreach (var request in connectionRequests)
            {
                var firstOrDefault =
                    groupMemberService.GetKnownRelationship(request.PersonAlias.PersonId, groupTypeRole.Id)
                    .FirstOrDefault();
                if (firstOrDefault != null)
                {
                    var consolidator = firstOrDefault.Person;
                    followUps.Add(new FollowUp(request, consolidator));
                }
            }

            gList.DataSource = followUps;
            gList.DataBind();
        }
コード例 #9
0
        /// <summary>
        /// Displays the edit group panel.
        /// </summary>
        private void DisplayEditGroup()
        {
            IsEditingGroup = true;

            if (_groupId != -1)
            {
                RockContext  rockContext  = new RockContext();
                GroupService groupService = new GroupService(rockContext);

                var qry = groupService
                          .Queryable("GroupLocations,GroupType,Schedule")
                          .Where(g => g.Id == _groupId);

                var group = qry.FirstOrDefault();

                if (group.IsAuthorized(Authorization.EDIT, CurrentPerson) || LineQuery.IsGroupInPersonsLine(group, CurrentPerson))
                {
                    tbName.Text        = group.Name;
                    tbDescription.Text = group.Description;
                    cbIsActive.Checked = group.IsActive;

                    timeWeekly.Visible = GetAttributeValue("ShowTimeField").AsBoolean();

                    if ((group.GroupType.AllowedScheduleTypes & ScheduleType.Weekly) == ScheduleType.Weekly)
                    {
                        pnlSchedule.Visible = group.Schedule == null || group.Schedule.ScheduleType == ScheduleType.Weekly;
                        if (group.Schedule != null)
                        {
                            dowWeekly.SelectedDayOfWeek = group.Schedule.WeeklyDayOfWeek;
                            timeWeekly.SelectedTime     = group.Schedule.WeeklyTimeOfDay;
                        }
                        else
                        {
                            dowWeekly.SelectedDayOfWeek = null;
                            timeWeekly.SelectedTime     = null;
                        }
                    }
                    else
                    {
                        pnlSchedule.Visible = false;
                    }

                    group.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Helper.AddEditControls(group, phAttributes, true, BlockValidationGroup);

                    // enable editing location
                    pnlGroupEditLocations.Visible = GetAttributeValue("EnableLocationEdit").AsBoolean();
                    if (GetAttributeValue("EnableLocationEdit").AsBoolean())
                    {
                        ConfigureGroupLocationControls(group);

                        // set location tabs
                        rptLocationTypes.DataSource = _tabs;
                        rptLocationTypes.DataBind();
                    }
                }
                else
                {
                    lContent.Text = "<div class='alert alert-warning'>You do not have permission to edit this group.</div>";
                }
            }
            else
            {
                lContent.Text = "<div class='alert alert-warning'>No group was available from the querystring.</div>";
            }
        }
コード例 #10
0
        ////
        //// Group Methods

        /// <summary>
        /// Displays the view group  using a lava template
        /// </summary>
        private void DisplayViewGroup()
        {
            if (_groupId > 0)
            {
                RockContext  rockContext  = new RockContext();
                GroupService groupService = new GroupService(rockContext);

                bool enableDebug = GetAttributeValue("EnableDebug").AsBoolean();

                var qry = groupService
                          .Queryable("GroupLocations,Members,Members.Person,Members.Person.PhoneNumbers,GroupType")
                          .Where(g => g.Id == _groupId);

                if (!enableDebug)
                {
                    qry = qry.AsNoTracking();
                }

                var group = qry.FirstOrDefault();

                // order group members by name
                if (group != null)
                {
                    group.Members = group.Members.OrderBy(m => m.Person.LastName).ThenBy(m => m.Person.FirstName).ToList();
                }

                var mergeFields = LavaHelper.GetCommonMergeFields(RockPage, CurrentPerson);
                mergeFields.Add("Group", group);

                // add linked pages
                Dictionary <string, object> linkedPages = new Dictionary <string, object>();
                linkedPages.Add("PersonDetailPage", LinkedPageRoute("PersonDetailPage"));
                linkedPages.Add("RosterPage", LinkedPageRoute("RosterPage"));
                linkedPages.Add("AttendancePage", LinkedPageRoute("AttendancePage"));
                linkedPages.Add("CommunicationPage", LinkedPageRoute("CommunicationPage"));
                mergeFields.Add("LinkedPages", linkedPages);

                // add collection of allowed security actions
                Dictionary <string, object> securityActions = new Dictionary <string, object>();
                securityActions.Add("View", group != null && group.IsAuthorized(Authorization.VIEW, CurrentPerson));
                securityActions.Add("Edit", group != null && (group.IsAuthorized(Authorization.EDIT, CurrentPerson) || LineQuery.IsGroupInPersonsLine(group, CurrentPerson)));
                securityActions.Add("Administrate", group != null && group.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson));
                mergeFields.Add("AllowedActions", securityActions);
                mergeFields.Add("Groups", string.Join(",", LineQuery.GetCellGroupsInLine(CurrentPerson, new RockContext(), false).Select(g => g.Name).ToList()));

                mergeFields.Add("LinePermission", LineQuery.IsGroupInPersonsLine(group, CurrentPerson));

                Dictionary <string, object> currentPageProperties = new Dictionary <string, object>();
                currentPageProperties.Add("Id", RockPage.PageId);
                currentPageProperties.Add("Path", Request.Path);
                mergeFields.Add("CurrentPage", currentPageProperties);

                string template = GetAttributeValue("LavaTemplate");

                // show debug info
                if (enableDebug && IsUserAuthorized(Authorization.EDIT))
                {
                    string postbackCommands = @"<h5>Available Postback Commands</h5>
                                                <ul>
                                                    <li><strong>EditGroup:</strong> Shows a panel for modifing group info. Expects a group id. <code>{{ Group.Id | Postback:'EditGroup' }}</code></li>
                                                    <li><strong>AddGroupMember:</strong> Shows a panel for adding group info. Does not require input. <code>{{ '' | Postback:'AddGroupMember' }}</code></li>
                                                    <li><strong>EditGroupMember:</strong> Shows a panel for modifing group info. Expects a group member id. <code>{{ member.Id | Postback:'EditGroupMember' }}</code></li>
                                                    <li><strong>DeleteGroupMember:</strong> Deletes a group member. Expects a group member id. <code>{{ member.Id | Postback:'DeleteGroupMember' }}</code></li>
                                                    <li><strong>SendCommunication:</strong> Sends a communication to all group members on behalf of the Current User. This will redirect them to the communication page where they can author their email. <code>{{ '' | Postback:'SendCommunication' }}</code></li>
                                                </ul>";

                    lDebug.Visible = true;
                    lDebug.Text    = mergeFields.lavaDebugInfo(null, string.Empty, postbackCommands);
                }

                lContent.Text = template.ResolveMergeFields(mergeFields).ResolveClientIds(upnlContent.ClientID);
            }
            else
            {
                lContent.Text = "<div class='alert alert-warning'>No group was available from the querystring.</div>";
            }
        }
コード例 #11
0
        /// <summary>
        /// Handles the Click event of the btnSaveGroup 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 btnSaveGroup_Click(object sender, EventArgs e)
        {
            var          rockContext  = new RockContext();
            GroupService groupService = new GroupService(rockContext);

            Group group = groupService.Get(_groupId);

            if (group != null && (group.IsAuthorized(Authorization.EDIT, CurrentPerson) || LineQuery.IsGroupInPersonsLine(group, CurrentPerson)))
            {
                group.Name        = tbName.Text;
                group.Description = tbDescription.Text;
                group.IsActive    = cbIsActive.Checked;

                if (pnlSchedule.Visible)
                {
                    if (group.Schedule == null)
                    {
                        group.Schedule = new Schedule();
                        group.Schedule.iCalendarContent = null;
                    }

                    group.Schedule.WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek;
                    group.Schedule.WeeklyTimeOfDay = timeWeekly.SelectedTime;
                }

                // set attributes
                group.LoadAttributes(rockContext);
                Helper.GetEditValues(phAttributes, group);

                // configure locations
                if (GetAttributeValue("EnableLocationEdit").AsBoolean())
                {
                    // get selected location
                    Location location            = null;
                    int?     memberPersonAliasId = null;

                    if (LocationTypeTab.Equals(MEMBER_LOCATION_TAB_TITLE))
                    {
                        if (ddlMember.SelectedValue != null)
                        {
                            var ids = ddlMember.SelectedValue.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                            if (ids.Length == 2)
                            {
                                var dbLocation = new LocationService(rockContext).Get(int.Parse(ids[0]));
                                if (dbLocation != null)
                                {
                                    location = dbLocation;
                                }

                                memberPersonAliasId = new PersonAliasService(rockContext).GetPrimaryAliasId(int.Parse(ids[1]));
                            }
                        }
                    }
                    else
                    {
                        if (locpGroupLocation.Location != null)
                        {
                            location = new LocationService(rockContext).Get(locpGroupLocation.Location.Id);
                        }
                    }

                    if (location != null)
                    {
                        GroupLocation groupLocation = group.GroupLocations.FirstOrDefault();

                        if (groupLocation == null)
                        {
                            groupLocation = new GroupLocation();
                            group.GroupLocations.Add(groupLocation);
                        }

                        groupLocation.GroupMemberPersonAliasId = memberPersonAliasId;
                        groupLocation.Location   = location;
                        groupLocation.LocationId = groupLocation.Location.Id;
                        groupLocation.GroupLocationTypeValueId = ddlLocationType.SelectedValueAsId();
                    }
                }

                rockContext.SaveChanges();
                group.SaveAttributeValues(rockContext);
            }

            IsEditingGroup = false;

            // reload the group info
            pnlGroupEdit.Visible = false;
            pnlGroupView.Visible = true;
            DisplayViewGroup();
        }
コード例 #12
0
        public ActionResult LineListResult(LineQuery lineQuery)
        {
            var lineList = tLineRepository.GetLineInfoListByQueryModel(lineQuery);

            return(View(lineList));
        }
コード例 #13
0
        private void GetFollowUps()
        {
            if (!CurrentPerson.HasALine())
            {
                leaderControlRow.Visible = false;
            }

            var rockContext = new RockContext();
            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);

            IQueryable <Person> people;
            bool isMyLine = tViewLineType.Checked;

            if (isMyLine)
            {
                people = CurrentPerson.GetPersonsLine(rockContext);
            }
            else // My Line's Follow Ups
            {
                people = LineQuery.GetLineMembersAndFollowUps(new PersonService(rockContext), CurrentPerson,
                                                              rockContext, false);
            }

            var option = GetOption();

            switch (option)
            {
            case ViewOption.All:
                break;

            case ViewOption.New:
                people = people.Where(
                    f => f.ConnectionStatusValueId == org.kcionline.bricksandmortarstudio.Constants.DefinedValue.GET_CONNECTED);
                break;

            case ViewOption.Ready:
                break;

            case ViewOption.InGroup:
                people = people.ToList().Where(f => f.InAGroup(rockContext)).AsQueryable();
                break;

            case ViewOption.NotInGroup:
                people = people.ToList().Where(f => !f.InAGroup(rockContext)).AsQueryable();
                break;

            case ViewOption.Ongoing:
                people = people.Where(
                    f => f.ConnectionStatusValueId == org.kcionline.bricksandmortarstudio.Constants.DefinedValue.CONNECTED);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            IQueryable <FollowUpSummary> followUpSummaries;

            if (isMyLine)
            {
                followUpSummaries =
                    people.ToList().Select(f => new FollowUpSummary()
                {
                    Person = f, Consolidator = CurrentPerson
                })
                    .AsQueryable();
            }
            else
            {
                followUpSummaries =
                    people.ToList().Select(f => new FollowUpSummary()
                {
                    Person = f, Consolidator = f.GetConsolidator()
                })
                    .AsQueryable();
            }

            if (ppFilter.SelectedValue.HasValue)
            {
                if (option.IsGuaranteedToHaveConsolidator())
                {
                    followUpSummaries = followUpSummaries.Where(f => f.Consolidator != null && f.Consolidator.Id == ppFilter.SelectedValue);

                    followUpSummaries = followUpSummaries
                                        .OrderByDescending(f => f.Person.ConnectionStatusValue.Value == "GetConnected")
                                        .ThenBy(f => f.Consolidator.Id);
                }
                else
                {
                    // Defer this work in order to avoid hammering queries unless we need to
                    foreach (var followUpSummary in followUpSummaries)
                    {
                        followUpSummary.Group = followUpSummary.Person.GetPersonsPrimaryKciGroup(rockContext);
                    }
                    var person = new PersonService(rockContext).Get(ppFilter.SelectedValue.Value);
                    var groups = person.GetGroupsLead(rockContext);
                    followUpSummaries = followUpSummaries
                                        .Where(f => f.Group != null && groups.Select(g => g.Id).Contains(f.Group.Id));

                    followUpSummaries = followUpSummaries
                                        .OrderByDescending(f => f.Group.Id)
                                        .ThenBy(f => f.Consolidator.Id);

                    if (option == ViewOption.All)
                    {
                        followUpSummaries = followUpSummaries
                                            .OrderBy(p => p.Person.FirstName);
                    }
                    else
                    {
                        followUpSummaries = followUpSummaries
                                            .OrderByDescending(f => f.Group.Id)
                                            .ThenBy(f => f.Consolidator.Id);
                    }
                }
            }

            mergeFields["FollowUps"] = followUpSummaries.ToList();
            mergeFields["MyLine"]    = isMyLine;
            mergeFields["View"]      = ViewOptionText[option];

            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);
        }
コード例 #14
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            bool wasSecurityRole = false;
            bool triggersUpdated = false;

            RockContext rockContext = new RockContext();

            GroupService    groupService    = new GroupService(rockContext);
            ScheduleService scheduleService = new ScheduleService(rockContext);

            var roleGroupType   = GroupTypeCache.Read(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid());
            int roleGroupTypeId = roleGroupType != null ? roleGroupType.Id : int.MinValue;

            int?parentGroupId = hfParentGroupId.Value.AsIntegerOrNull();

            if (parentGroupId != null)
            {
                var allowedGroupIds = LineQuery.GetCellGroupIdsInLine(CurrentPerson, rockContext);
                if (!allowedGroupIds.Contains(parentGroupId.Value))
                {
                    nbMessage.Text         = "You are not allowed to add a group to this parent group.";
                    nbMessage.Visible      = true;
                    pnlEditDetails.Visible = false;
                    btnSave.Enabled        = false;
                    return;
                }
                var parentGroup = groupService.Get(parentGroupId.Value);
                if (parentGroup != null)
                {
                    CurrentGroupTypeId = parentGroup.GroupTypeId;

                    if (!lppLeader.PersonId.HasValue)
                    {
                        nbMessage.Text    = "A Leader is required.";
                        nbMessage.Visible = true;
                        return;
                    }

                    if (!GroupLocationsState.Any())
                    {
                        nbMessage.Text    = "A location is required.";
                        nbMessage.Visible = true;
                        return;
                    }

                    if (CurrentGroupTypeId == 0)
                    {
                        return;
                    }

                    Group group = new Group();
                    group.IsSystem = false;
                    group.Name     = string.Empty;



                    // add/update any group locations that were added or changed in the UI (we already removed the ones that were removed above)
                    foreach (var groupLocationState in GroupLocationsState)
                    {
                        GroupLocation groupLocation = group.GroupLocations.Where(l => l.Guid == groupLocationState.Guid).FirstOrDefault();
                        if (groupLocation == null)
                        {
                            groupLocation = new GroupLocation();
                            group.GroupLocations.Add(groupLocation);
                        }
                        else
                        {
                            groupLocationState.Id   = groupLocation.Id;
                            groupLocationState.Guid = groupLocation.Guid;

                            var selectedSchedules = groupLocationState.Schedules.Select(s => s.Guid).ToList();
                            foreach (var schedule in groupLocation.Schedules.Where(s => !selectedSchedules.Contains(s.Guid)).ToList())
                            {
                                groupLocation.Schedules.Remove(schedule);
                            }
                        }

                        groupLocation.CopyPropertiesFrom(groupLocationState);

                        var existingSchedules = groupLocation.Schedules.Select(s => s.Guid).ToList();
                        foreach (var scheduleState in groupLocationState.Schedules.Where(s => !existingSchedules.Contains(s.Guid)).ToList())
                        {
                            var schedule = scheduleService.Get(scheduleState.Guid);
                            if (schedule != null)
                            {
                                groupLocation.Schedules.Add(schedule);
                            }
                        }
                    }

                    GroupMember leader = new GroupMember();
                    leader.GroupMemberStatus = GroupMemberStatus.Active;
                    leader.PersonId          = lppLeader.PersonId.Value;
                    leader.Person            = new PersonService(rockContext).Get(lppLeader.PersonId.Value);
                    leader.GroupRole         = parentGroup.GroupType.Roles.Where(r => r.IsLeader).FirstOrDefault() ?? parentGroup.GroupType.DefaultGroupRole;

                    group.Name           = String.Format("{0}, {1}", leader.Person.NickName, leader.Person.LastName);
                    group.Description    = tbDescription.Text;
                    group.CampusId       = parentGroup.CampusId;
                    group.GroupTypeId    = CurrentGroupTypeId;
                    group.ParentGroupId  = parentGroupId;
                    group.IsSecurityRole = false;
                    group.IsActive       = true;
                    group.IsPublic       = true;

                    if (dpStartDate.SelectedDate.HasValue)
                    {
                        group.CreatedDateTime = dpStartDate.SelectedDate.Value;
                    }

                    group.Members.Add(leader);

                    string iCalendarContent = string.Empty;

                    // If unique schedule option was selected, but a schedule was not defined, set option to 'None'
                    var scheduleType = rblScheduleSelect.SelectedValueAsEnum <ScheduleType>(ScheduleType.None);
                    if (scheduleType == ScheduleType.Custom)
                    {
                        iCalendarContent = sbSchedule.iCalendarContent;
                        var calEvent = ScheduleICalHelper.GetCalenderEvent(iCalendarContent);
                        if (calEvent == null || calEvent.DTStart == null)
                        {
                            scheduleType = ScheduleType.None;
                        }
                    }

                    if (scheduleType == ScheduleType.Weekly)
                    {
                        if (!dowWeekly.SelectedDayOfWeek.HasValue)
                        {
                            scheduleType = ScheduleType.None;
                        }
                    }

                    int?oldScheduleId = hfUniqueScheduleId.Value.AsIntegerOrNull();
                    if (scheduleType == ScheduleType.Custom || scheduleType == ScheduleType.Weekly)
                    {
                        if (!oldScheduleId.HasValue || group.Schedule == null)
                        {
                            group.Schedule = new Schedule();
                        }

                        if (scheduleType == ScheduleType.Custom)
                        {
                            group.Schedule.iCalendarContent = iCalendarContent;
                            group.Schedule.WeeklyDayOfWeek  = null;
                            group.Schedule.WeeklyTimeOfDay  = null;
                        }
                        else
                        {
                            group.Schedule.iCalendarContent = null;
                            group.Schedule.WeeklyDayOfWeek  = dowWeekly.SelectedDayOfWeek;
                            group.Schedule.WeeklyTimeOfDay  = timeWeekly.SelectedTime;
                        }
                    }
                    else
                    {
                        // If group did have a unique schedule, delete that schedule
                        if (oldScheduleId.HasValue)
                        {
                            var schedule = scheduleService.Get(oldScheduleId.Value);
                            if (schedule != null && string.IsNullOrEmpty(schedule.Name))
                            {
                                scheduleService.Delete(schedule);
                            }
                        }

                        if (scheduleType == ScheduleType.Named)
                        {
                            group.ScheduleId = spSchedule.SelectedValueAsId();
                        }
                        else
                        {
                            group.ScheduleId = null;
                        }
                    }

                    group.LoadAttributes();
                    Rock.Attribute.Helper.GetEditValues(phGroupAttributes, group);

                    group.GroupType = new GroupTypeService(rockContext).Get(group.GroupTypeId);
                    if (group.ParentGroupId.HasValue)
                    {
                        group.ParentGroup = groupService.Get(group.ParentGroupId.Value);
                    }

                    if (!Page.IsValid)
                    {
                        return;
                    }

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

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

                    // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                    rockContext.WrapTransaction(() =>
                    {
                        var adding = group.Id.Equals(0);
                        if (adding)
                        {
                            groupService.Add(group);
                        }

                        rockContext.SaveChanges();

                        if (adding)
                        {
                            // add ADMINISTRATE to the person who added the group
                            Rock.Security.Authorization.AllowPerson(group, Authorization.ADMINISTRATE, this.CurrentPerson, rockContext);
                        }

                        group.SaveAttributeValues(rockContext);
                    });

                    bool isNowSecurityRole = group.IsActive && (group.GroupTypeId == roleGroupTypeId);


                    if (isNowSecurityRole)
                    {
                        // new security role, flush
                        Rock.Security.Authorization.Flush();
                    }

                    AttributeCache.FlushEntityAttributes();

                    pnlDetails.Visible = false;
                    pnlSuccess.Visible = true;
                    nbSuccess.Text     = string.Format("Your group ({0}) has been created", group.Name);
                    string linkedPage            = LinkedPageRoute("RedirectPage");
                    int    secondsBeforeRedirect = GetAttributeValue("SecondsBeforeRedirect").AsInteger() * 1000;
                    ScriptManager.RegisterClientScriptBlock(upnlGroupDetail, typeof(UpdatePanel), "Redirect", string.Format("console.log('{0}'); setTimeout(function() {{ window.location.replace('{0}?GroupId={2}') }}, {1});", linkedPage, secondsBeforeRedirect, group.Id), true);
                }
            }
        }