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

            // Validate the person exists
            var personGuid = GetAttributeValue(action, AttributeKey.Person, true).AsGuidOrNull();

            if (!personGuid.HasValue)
            {
                errorMessages.Add("The person guid is required but was missing");
                return(LogMessagesForExit(action, errorMessages));
            }

            var personService = new PersonService(rockContext);
            var person        = personService.Queryable("Aliases").AsNoTracking()
                                .FirstOrDefault(p => p.Guid == personGuid.Value || p.Aliases.Any(pa => pa.Guid == personGuid.Value));

            if (person == null)
            {
                errorMessages.Add($"The person with the guid '{personGuid.Value}' was not found");
                return(LogMessagesForExit(action, errorMessages));
            }

            if (!person.PrimaryAliasId.HasValue)
            {
                errorMessages.Add($"{person.FullName} does not have a primary alias identifier");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Validate the step type exists. Could be a step type id or a guid
            var stepType = GetStepType(rockContext, action, out var errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
                return(LogMessagesForExit(action, errorMessages));
            }

            if (stepType == null)
            {
                errorMessages.Add("The step type could not be found");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Validate the step status exists and is in the same program as the step type
            var stepStatus = GetStepStatus(stepType, action, out errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
                return(LogMessagesForExit(action, errorMessages));
            }

            if (stepStatus == null)
            {
                errorMessages.Add("The step status could not be found");
                return(LogMessagesForExit(action, errorMessages));
            }

            // Get the start and end dates
            var startDate = GetLavaAttributeValue(action, AttributeKey.StartDate).AsDateTime() ?? RockDateTime.Now;
            var endDate   = GetLavaAttributeValue(action, AttributeKey.EndDate).AsDateTime();

            var campusAttributeValue = GetLavaAttributeValue(action, AttributeKey.Campus);
            var campusId             = campusAttributeValue.AsIntegerOrNull();
            var campusGuid           = campusAttributeValue.AsGuidOrNull();

            if (campusGuid != null)
            {
                var campus = CampusCache.Get(campusGuid.Value);
                if (campus != null)
                {
                    campusId = campus.Id;
                }
            }

            // The completed date is today or the end date if the status is a completed status
            var completedDate = stepStatus.IsCompleteStatus ? (endDate ?? RockDateTime.Now) : ( DateTime? )null;

            // Create the step object
            var step = new Step
            {
                StepTypeId        = stepType.Id,
                PersonAliasId     = person.PrimaryAliasId.Value,
                StartDateTime     = startDate,
                EndDateTime       = endDate,
                CompletedDateTime = completedDate,
                StepStatusId      = stepStatus.Id,
                CampusId          = campusId
            };

            // Validate the step
            if (!step.IsValid)
            {
                errorMessages.AddRange(step.ValidationResults.Select(a => a.ErrorMessage));
                return(LogMessagesForExit(action, errorMessages));
            }

            // Check if the step can be created because of Allow Multiple rules on the step type and also prerequisite requirements
            var stepService = new StepService(rockContext);
            var canAdd      = stepService.CanAdd(step, out errorMessage);

            if (!errorMessage.IsNullOrWhiteSpace())
            {
                errorMessages.Add(errorMessage);
            }
            else if (!canAdd)
            {
                errorMessages.Add("Cannot add the step for an unspecified reason");
            }
            else
            {
                try
                {
                    stepService.Add(step);
                    rockContext.SaveChanges();

                    SetCreatedItemAttribute(action, AttributeKey.StepAttribute, step, rockContext);
                }
                catch (Exception exception)
                {
                    errorMessages.Add($"Exception thrown: {exception.Message}");
                    ExceptionLogService.LogException(exception);
                }
            }

            return(LogMessagesForExit(action, errorMessages));
        }
Ejemplo n.º 2
0
        void gPeople_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                var person = e.Row.DataItem as PersonSearchResult2;
                if (person != null)
                {
                    if (_inactiveStatus != null &&
                        person.RecordStatusValueId.HasValue &&
                        person.RecordStatusValueId.Value == _inactiveStatus.Id)
                    {
                        e.Row.AddCssClass("inactive");
                    }

                    if (person.IsDeceased)
                    {
                        e.Row.AddCssClass("deceased");
                    }

                    string delimitedCampuses = string.Empty;
                    if (person.CampusIds.Any())
                    {
                        var campuses = new List <string>();
                        foreach (var campusId in person.CampusIds)
                        {
                            var campus = CampusCache.Get(campusId);
                            if (campus != null)
                            {
                                campuses.Add(campus.Name);
                            }
                        }
                        if (campuses.Any())
                        {
                            delimitedCampuses = campuses.AsDelimited(", ");
                            var lCampus = e.Row.FindControl("lCampus") as Literal;
                            if (lCampus != null)
                            {
                                lCampus.Text = delimitedCampuses;
                            }
                        }
                    }

                    var lPerson = e.Row.FindControl("lPerson") as Literal;

                    if (!person.IsBusiness)
                    {
                        StringBuilder sbPersonDetails = new StringBuilder();
                        sbPersonDetails.Append(string.Format("<div class=\"photo-round photo-round-sm pull-left\" data-original=\"{0}&w=100\" style=\"background-image: url('{1}');\"></div>", person.PhotoUrl, ResolveUrl("~/Assets/Images/person-no-photo-male.svg")));
                        sbPersonDetails.Append("<div class=\"pull-left margin-l-sm\">");
                        sbPersonDetails.Append(string.Format("<strong>{0}</strong> ", person.FullNameReversed));
                        sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\"><br>{0}</br></small>", delimitedCampuses));
                        sbPersonDetails.Append(string.Format("<small class=\"hidden-sm hidden-md hidden-lg\">{0}</small>", DefinedValueCache.GetName(person.ConnectionStatusValueId)));
                        sbPersonDetails.Append(string.Format(" <small class=\"hidden-md hidden-lg\">{0}</small>", person.AgeFormatted));
                        if (!string.IsNullOrWhiteSpace(person.Email))
                        {
                            sbPersonDetails.Append(string.Format("<br/><small>{0}</small>", person.Email));
                        }

                        // add home addresses
                        foreach (var location in person.HomeAddresses)
                        {
                            if (string.IsNullOrWhiteSpace(location.Street1) &&
                                string.IsNullOrWhiteSpace(location.Street2) &&
                                string.IsNullOrWhiteSpace(location.City))
                            {
                                continue;
                            }

                            string format       = string.Empty;
                            var    countryValue = Rock.Web.Cache.DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.LOCATION_COUNTRIES.AsGuid())
                                                  .DefinedValues
                                                  .Where(v => v.Value.Equals(location.Country, StringComparison.OrdinalIgnoreCase))
                                                  .FirstOrDefault();

                            if (countryValue != null)
                            {
                                format = countryValue.GetAttributeValue("AddressFormat");
                            }

                            if (!string.IsNullOrWhiteSpace(format))
                            {
                                var dict = location.ToDictionary();
                                dict["Country"] = countryValue.Description;
                                sbPersonDetails.Append(string.Format("<small><br>{0}</small>", format.ResolveMergeFields(dict).ConvertCrLfToHtmlBr().Replace("<br/><br/>", "<br/>")));
                            }
                            else
                            {
                                sbPersonDetails.Append(string.Format(string.Format("<small><br>{0}<br>{1} {2}, {3} {4}</small>", location.Street1, location.Street2, location.City, location.State, location.PostalCode)));
                            }
                        }
                        sbPersonDetails.Append("</div>");

                        lPerson.Text = sbPersonDetails.ToString();
                    }
                    else
                    {
                        lPerson.Text = string.Format("{0}", person.LastName);
                    }
                }
            }
        }
        /// <summary>
        /// Shows the financial batch summary.
        /// </summary>
        /// <param name="batch">The financial batch.</param>
        private void ShowReadonlyDetails(FinancialBatch batch)
        {
            SetEditMode(false);

            if (batch != null)
            {
                hfBatchId.SetValue(batch.Id);

                SetHeadingInfo(batch, batch.Name);

                string campusName = string.Empty;
                if (batch.CampusId.HasValue)
                {
                    var campus = CampusCache.Get(batch.CampusId.Value);
                    if (campus != null)
                    {
                        campusName = campus.ToString();
                    }
                }

                var rockContext = new RockContext();
                var financialTransactionService = new FinancialTransactionService(rockContext);
                var batchTransactionsQuery      = financialTransactionService.Queryable().Where(a => a.BatchId.HasValue && a.BatchId.Value == batch.Id);

                var     financialTransactionDetailService = new FinancialTransactionDetailService(rockContext);
                var     qryTransactionDetails             = financialTransactionDetailService.Queryable().Where(a => a.Transaction.BatchId == batch.Id);
                decimal amountTotal = qryTransactionDetails.Select(a => (decimal?)a.Amount).Sum() ?? 0;

                decimal amountVariance     = amountTotal - batch.ControlAmount;
                string  varianceAmountText = string.Format(
                    "{0} / {1} / " + (amountVariance == 0.0M ? "{2}" : "<span class='label label-danger'>{2}</span>"),
                    amountTotal.FormatAsCurrency(),
                    batch.ControlAmount.FormatAsCurrency(),
                    amountVariance.FormatAsCurrency());

                string varianceCountText = null;

                if (batch.ControlItemCount.HasValue)
                {
                    var itemCountTotal    = batchTransactionsQuery.Count();
                    int itemCountVariance = itemCountTotal - batch.ControlItemCount.Value;
                    varianceCountText = string.Format(
                        "{0} / {1} / " + (itemCountVariance == 0 ? "{2}" : "<span class='label label-danger'>{2}</span>"),
                        itemCountTotal,
                        batch.ControlItemCount.Value,
                        itemCountVariance);
                }

                lDetails.Text = new DescriptionList()
                                .Add("Date Range", new DateRange(batch.BatchStartDateTime, batch.BatchEndDateTime).ToString("g"))
                                .Add("Transaction Amount / Control / Variance", varianceAmountText)
                                .Add("Transaction Item Count / Control / Variance", varianceCountText, false)
                                .Add("Accounting Code", batch.AccountingSystemCode)
                                .Add("Notes", batch.Note)
                                .Html;

                batch.LoadAttributes();
                var attributes = batch.Attributes.Select(a => a.Value).OrderBy(a => a.Order).ThenBy(a => a.Name).ToList();

                var attributeCategories = Helper.GetAttributeCategories(attributes);

                Rock.Attribute.Helper.AddDisplayControls(batch, attributeCategories, phReadonlyAttributes, null, false);

                // Account Summary
                gAccounts.DataSource = qryTransactionDetails
                                       .GroupBy(d => new
                {
                    AccountId   = d.AccountId,
                    AccountName = d.Account.Name
                })
                                       .Select(s => new
                {
                    Id     = s.Key.AccountId,
                    Name   = s.Key.AccountName,
                    Amount = s.Sum(a => (decimal?)a.Amount) ?? 0.0M
                })
                                       .OrderBy(s => s.Name)
                                       .ToList();

                gAccounts.DataBind();

                // Currency Summary
                gCurrencyTypes.DataSource = batchTransactionsQuery
                                            .GroupBy(c => new
                {
                    CurrencyTypeValueId = c.FinancialPaymentDetailId.HasValue ? c.FinancialPaymentDetail.CurrencyTypeValueId : 0,
                })
                                            .Select(s => new
                {
                    CurrencyTypeValueId = s.Key.CurrencyTypeValueId,
                    Amount = s.Sum(a => (decimal?)a.TransactionDetails.Sum(t => t.Amount)) ?? 0.0M
                })
                                            .ToList()
                                            .Select(s => new
                {
                    Id     = s.CurrencyTypeValueId,
                    Name   = DefinedValueCache.GetName(s.CurrencyTypeValueId),
                    Amount = s.Amount
                }).OrderBy(a => a.Name).ToList();

                gCurrencyTypes.DataBind();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Loads the drop downs.
        /// </summary>
        private bool SetFilterControls()
        {
            // Get and verify the calendar id
            if (_calendarId <= 0)
            {
                ShowError("Configuration Error", "The 'Event Calendar' setting has not been set correctly.");
                return(false);
            }

            // Get and verify the view mode
            ViewMode = GetAttributeValue("DefaultViewOption");
            if (!GetAttributeValue(string.Format("Show{0}View", ViewMode)).AsBoolean())
            {
                ShowError("Configuration Error", string.Format("The Default View Option setting has been set to '{0}', but the Show {0} View setting has not been enabled.", ViewMode));
                return(false);
            }

            // Show/Hide calendar control
            pnlCalendar.Visible = GetAttributeValue("ShowSmallCalendar").AsBoolean();

            // Get the first/last dates based on today's date and the viewmode setting
            var today = RockDateTime.Today;

            FilterStartDate = today;
            FilterEndDate   = today;
            if (ViewMode == "Week")
            {
                FilterStartDate = today.StartOfWeek(_firstDayOfWeek);
                FilterEndDate   = today.EndOfWeek(_firstDayOfWeek);
            }
            else if (ViewMode == "Month")
            {
                FilterStartDate = new DateTime(today.Year, today.Month, 1);
                FilterEndDate   = FilterStartDate.Value.AddMonths(1).AddDays(-1);
            }
            else if (ViewMode == "Year")
            {
                FilterStartDate = new DateTime(today.Year, today.Month, today.Day);
                FilterEndDate   = new DateTime(today.Year, 12, 31);
            }
            else if (ViewMode == "All")
            {
                FilterStartDate = new DateTime(today.Year, today.Month, today.Day);
                FilterEndDate   = FilterStartDate.Value.AddDays(730);
            }

            // Setup small calendar Filter
            calEventCalendar.FirstDayOfWeek = _firstDayOfWeek.ConvertToInt().ToString().ConvertToEnum <FirstDayOfWeek>();
            calEventCalendar.SelectedDates.Clear();
            calEventCalendar.SelectedDates.SelectRange(FilterStartDate.Value, FilterEndDate.Value);

            // Setup different dates if QueryString is set on load
            var selectedDate = PageParameter(GetAttributeValue("DateParameterName")).AsDateTime();

            if (selectedDate.HasValue)
            {
                if (selectedDate != null)
                {
                    SelectedDate = selectedDate;
                    ResetCalendarSelection();
                }
            }

            // Setup Campus Filter
            var campusGuidList = GetAttributeValue("Campuses").Split(',').AsGuidList();

            rcwCampus.Visible = GetAttributeValue("CampusFilterDisplayMode").AsInteger() > 1;

            if (campusGuidList.Any())
            {
                cblCampus.DataSource = CampusCache.All(false).Where(c => campusGuidList.Contains(c.Guid));
            }
            else
            {
                cblCampus.DataSource = CampusCache.All(false);
            }

            cblCampus.DataBind();

            if (cblCampus.Items.Count == 1)
            {
                CampusPanelClosed = false;
                CampusPanelOpen   = false;
                rcwCampus.Visible = false;
            }

            // Check for Campus Parameter
            var campusId = PageParameter(GetAttributeValue("CampusParameterName")).AsIntegerOrNull();

            if (campusId.HasValue)
            {
                // Check if there's a campus with this id.
                var campus = CampusCache.Get(campusId.Value);
                if (campus != null)
                {
                    cblCampus.SetValue(campusId.Value);
                }
            }
            else
            {
                if (GetAttributeValue("EnableCampusContext").AsBoolean())
                {
                    var contextCampus = RockPage.GetCurrentContext(EntityTypeCache.Get("Rock.Model.Campus")) as Campus;
                    if (contextCampus != null)
                    {
                        cblCampus.SetValue(contextCampus.Id);
                    }
                }
            }

            // Setup Category Filter
            var selectedCategoryGuids = GetAttributeValue("FilterCategories").SplitDelimitedValues(true).AsGuidList();

            rcwCategory.Visible = selectedCategoryGuids.Any() && GetAttributeValue("CategoryFilterDisplayMode").AsInteger() > 1;
            var definedType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.MARKETING_CAMPAIGN_AUDIENCE_TYPE.AsGuid());

            if (definedType != null)
            {
                ddlCategory.DataSource = definedType.DefinedValues.Where(v => selectedCategoryGuids.Contains(v.Guid));
                ddlCategory.DataBind();
                ddlCategory.Items.Insert(0, new ListItem("Category", string.Empty));
            }

            var categoryId = PageParameter(GetAttributeValue("CategoryParameterName")).AsIntegerOrNull();

            if (categoryId.HasValue)
            {
                if (definedType.DefinedValues.Where(v => selectedCategoryGuids.Contains(v.Guid) && v.Id == categoryId.Value).FirstOrDefault() != null)
                {
                    ddlCategory.SetValue(categoryId.Value);
                }
            }

            // Date Range Filter
            drpDateRange.Visible       = GetAttributeValue("ShowDateRangeFilter").AsBoolean();
            lbDateRangeRefresh.Visible = drpDateRange.Visible;
            drpDateRange.LowerValue    = FilterStartDate;
            drpDateRange.UpperValue    = FilterEndDate;

            // Get the View Modes, and only show them if more than one is visible
            var viewsVisible = new List <bool> {
                GetAttributeValue("ShowDayView").AsBoolean(),
                GetAttributeValue("ShowWeekView").AsBoolean(),
                GetAttributeValue("ShowMonthView").AsBoolean(),
                GetAttributeValue("ShowYearView").AsBoolean(),
                GetAttributeValue("ShowAllView").AsBoolean()
            };
            var howManyVisible = viewsVisible.Where(v => v).Count();

            btnDay.Visible   = howManyVisible > 1 && viewsVisible[0];
            btnWeek.Visible  = howManyVisible > 1 && viewsVisible[1];
            btnMonth.Visible = howManyVisible > 1 && viewsVisible[2];
            btnYear.Visible  = howManyVisible > 1 && viewsVisible[3];
            btnAll.Visible   = howManyVisible > 1 && viewsVisible[4];

            // Set filter visibility
            bool showFilter = pnlCalendar.Visible || rcwCampus.Visible || rcwCategory.Visible || drpDateRange.Visible;

            pnlFilters.Visible = showFilter;

            return(true);
        }
Ejemplo n.º 5
0
        public object GetEvents(DateTime beginDate, DateTime endDate)
        {
            using (var rockContext = new RockContext())
            {
                var eventCalendar = new EventCalendarService(rockContext).Get(Calendar ?? Guid.Empty);
                var eventItemOccurrenceService = new EventItemOccurrenceService(rockContext);

                if (eventCalendar == null)
                {
                    return(new List <object>());
                }

                // Grab events
                var qry = eventItemOccurrenceService
                          .Queryable("EventItem, EventItem.EventItemAudiences, Schedule")
                          .Where(m =>
                                 m.EventItem.EventCalendarItems.Any(i => i.EventCalendarId == eventCalendar.Id) &&
                                 m.EventItem.IsActive &&
                                 m.EventItem.IsApproved);

                // Check for Campus Parameter or Campus Context.
                if (EnableCampusFiltering)
                {
                    var campusGuid = RequestContext.GetPageParameter("CampusGuid").AsGuidOrNull();
                    if (campusGuid.HasValue)
                    {
                        // Check if there's a campus with this guid.
                        var campus = CampusCache.Get(campusGuid.Value);
                        if (campus != null)
                        {
                            qry = qry.Where(a => !a.CampusId.HasValue || a.CampusId == campus.Id);
                        }
                    }
                    else
                    {
                        var contextCampus = RequestContext.GetContextEntity <Campus>();
                        if (contextCampus != null)
                        {
                            qry = qry.Where(a => !a.CampusId.HasValue || a.Campus.Id == contextCampus.Id);
                        }
                        else if (RequestContext.CurrentPerson != null && RequestContext.CurrentPerson.PrimaryCampusId.HasValue)
                        {
                            var campusId = RequestContext.CurrentPerson.PrimaryCampusId.Value;

                            qry = qry.Where(a => !a.CampusId.HasValue || a.CampusId == campusId);
                        }
                    }
                }

                // Get the occurrences
                var occurrences = qry.ToList()
                                  .SelectMany(a =>
                {
                    var duration = a.Schedule?.DurationInMinutes ?? 0;

                    return(a.GetStartTimes(beginDate, endDate)
                           .Where(b => b >= beginDate && b < endDate)
                           .Select(b => new
                    {
                        Date = b.ToRockDateTimeOffset(),
                        Duration = duration,
                        AudienceGuids = a.EventItem.EventItemAudiences.Select(c => DefinedValueCache.Get(c.DefinedValueId)?.Guid).Where(c => c.HasValue).Select(c => c.Value).ToList(),
                        EventItemOccurrence = a
                    }));
                })
                                  .Select(a => new
                {
                    a.EventItemOccurrence,
                    a.EventItemOccurrence.Guid,
                    a.EventItemOccurrence.Id,
                    a.EventItemOccurrence.EventItem.Name,
                    DateTime            = a.Date,
                    EndDateTime         = a.Duration > 0 ? ( DateTimeOffset? )a.Date.AddMinutes(a.Duration) : null,
                    Date                = a.Date.ToString("d"), // Short date
                    Time                = a.Date.ToString("t"), // Short time
                    Campus              = a.EventItemOccurrence.Campus != null ? a.EventItemOccurrence.Campus.Name : "All Campuses",
                    Location            = a.EventItemOccurrence.Campus != null ? a.EventItemOccurrence.Campus.Name : "All Campuses",
                    LocationDescription = a.EventItemOccurrence.Location,
                    Audiences           = a.AudienceGuids,
                    a.EventItemOccurrence.EventItem.Description,
                    a.EventItemOccurrence.EventItem.Summary,
                    OccurrenceNote = a.EventItemOccurrence.Note.SanitizeHtml()
                });

                var lavaTemplate = CreateLavaTemplate();

                var commonMergeFields = new CommonMergeFieldsOptions
                {
                    GetLegacyGlobalMergeFields = false
                };

                var mergeFields = RequestContext.GetCommonMergeFields(null, commonMergeFields);
                mergeFields.Add("Items", occurrences.ToList());

                var output = lavaTemplate.ResolveMergeFields(mergeFields);

                return(ActionOk(new StringContent(output, Encoding.UTF8, "application/json")));
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Handles the ItemDataBound event of the rConnectionTypes control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param>
        protected void rConnectionTypes_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var lConnectionOpportunityList = e.Item.FindControl("lConnectionOpportunityList") as Literal;

            if (lConnectionOpportunityList != null)
            {
                var           connectionType = e.Item.DataItem as ConnectionType;
                var           pageGuid       = this.GetAttributeValue(AttributeKey.ConnectionRequestDetail).AsGuidOrNull();
                PageReference connectionRequestDetailPage = null;
                if (pageGuid.HasValue)
                {
                    connectionRequestDetailPage = new PageReference(pageGuid.Value.ToString());
                }

                if (connectionType != null && this.Person != null)
                {
                    using (var rockContext = new RockContext())
                    {
                        string listHtml = string.Empty;

                        int personId = this.Person.Id;
                        var connectionRequestService = new ConnectionRequestService(rockContext);
                        var connectionRequestQuery   = connectionRequestService
                                                       .Queryable()
                                                       .Where(a => a.PersonAlias.PersonId == personId && a.ConnectionOpportunity.ConnectionTypeId == connectionType.Id);

                        var hideInactive = GetAttributeValue(AttributeKey.HideInactiveConnectionRequests).AsBoolean();

                        if (hideInactive)
                        {
                            connectionRequestQuery = connectionRequestQuery
                                                     .Where(r => r.ConnectionState == ConnectionState.Active ||
                                                            (r.ConnectionState == ConnectionState.FutureFollowUp && r.FollowupDate.HasValue && r.FollowupDate.Value <= _midnightTomorrow));
                        }

                        var connectionRequestList = connectionRequestQuery
                                                    .OrderBy(a => a.ConnectionOpportunity.Name)
                                                    .AsNoTracking()
                                                    .ToList();

                        foreach (var connectionRequest in connectionRequestList)
                        {
                            string connectionNameHtml;
                            string connectionName;
                            if (connectionRequest.CampusId.HasValue)
                            {
                                connectionName = string.Format("{0} ({1})", connectionRequest.ConnectionOpportunity, CampusCache.Get(connectionRequest.CampusId.Value));
                            }
                            else
                            {
                                connectionName = string.Format("{0}", connectionRequest.ConnectionOpportunity);
                            }

                            if (connectionRequestDetailPage != null && connectionRequestDetailPage.PageId > 0)
                            {
                                connectionRequestDetailPage.Parameters = new System.Collections.Generic.Dictionary <string, string>();
                                connectionRequestDetailPage.Parameters.Add("ConnectionRequestId", connectionRequest.Id.ToString());
                                connectionRequestDetailPage.Parameters.Add("ConnectionOpportunityId", connectionRequest.ConnectionOpportunityId.ToString());

                                connectionNameHtml = string.Format("<a href='{0}'>{1}</a>", connectionRequestDetailPage.BuildUrl(), connectionName);
                            }
                            else
                            {
                                connectionNameHtml = connectionName;
                            }

                            listHtml += string.Format(
                                "<li {0}>{1} - <small>{2}</small></li>",
                                (connectionRequest.ConnectionState == ConnectionState.Connected || connectionRequest.ConnectionState == ConnectionState.Inactive) ? "class='is-inactive'" : string.Empty,
                                connectionNameHtml,
                                connectionRequest.ConnectionState == ConnectionState.Connected ? "Connected" : connectionRequest.ConnectionStatus.ToString());
                        }

                        lConnectionOpportunityList.Text = listHtml;
                    }
                }
            }
        }
        private void LoadContent()
        {
            var audienceGuid = GetAttributeValue("Audience").AsGuid();

            if (audienceGuid != Guid.Empty)
            {
                lMessages.Text = string.Empty;
                RockContext rockContext = new RockContext();

                // get event occurrences
                var qry = new EventItemOccurrenceService(rockContext).Queryable()
                          .Where(e => e.EventItem.EventItemAudiences.Any(a => a.DefinedValue.Guid == audienceGuid) && e.EventItem.IsActive);

                // filter occurrences for campus (always include the "All Campuses" events)
                if (GetAttributeValue("UseCampusContext").AsBoolean())
                {
                    var campusEntityType = EntityTypeCache.Get("Rock.Model.Campus");
                    var contextCampus    = RockPage.GetCurrentContext(campusEntityType) as Campus;

                    if (contextCampus != null)
                    {
                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == contextCampus.Id || !e.CampusId.HasValue);
                    }
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(GetAttributeValue("Campuses")))
                    {
                        var selectedCampusGuids = GetAttributeValue("Campuses").Split(',').AsGuidList();
                        var selectedCampusIds   = selectedCampusGuids.Select(a => CampusCache.Get(a)).Where(a => a != null).Select(a => a.Id);

                        // If an EventItemOccurrence's CampusId is null, then the occurrence is an 'All Campuses' event occurrence, so include those
                        qry = qry.Where(e => e.CampusId == null || selectedCampusIds.Contains(e.CampusId.Value));
                    }
                }

                // filter by calendar
                var calendarGuid = GetAttributeValue("Calendar").AsGuid();

                if (calendarGuid != Guid.Empty)
                {
                    qry = qry.Where(e => e.EventItem.EventCalendarItems.Any(c => c.EventCalendar.Guid == calendarGuid));
                }

                // retrieve occurrences
                var itemOccurrences = qry.ToList();

                // filter by date range
                var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(GetAttributeValue("DateRange"));
                if (dateRange.Start != null && dateRange.End != null)
                {
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(dateRange.Start.Value, dateRange.End.Value).Count() == 0);
                }
                else
                {
                    // default show all future
                    itemOccurrences.RemoveAll(o => o.GetStartTimes(RockDateTime.Now, RockDateTime.Now.AddDays(365)).Count() == 0);
                }

                // limit results
                int maxItems = GetAttributeValue("MaxOccurrences").AsInteger();
                itemOccurrences = itemOccurrences.OrderBy(i => i.NextStartDateTime).Take(maxItems).ToList();

                // make lava merge fields
                var mergeFields = new Dictionary <string, object>();

                var contextObjects = new Dictionary <string, object>();
                foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                {
                    var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                    if (contextEntity != null && contextEntity is DotLiquid.ILiquidizable)
                    {
                        var type = Type.GetType(contextEntityType.AssemblyName ?? contextEntityType.Name);
                        if (type != null)
                        {
                            contextObjects.Add(type.Name, contextEntity);
                        }
                    }
                }

                if (contextObjects.Any())
                {
                    mergeFields.Add("Context", contextObjects);
                }

                mergeFields.Add("ListTitle", GetAttributeValue("ListTitle"));
                mergeFields.Add("EventDetailPage", LinkedPageRoute("EventDetailPage"));
                mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage"));
                mergeFields.Add("EventItemOccurrences", itemOccurrences);

                lContent.Text = GetAttributeValue("LavaTemplate").ResolveMergeFields(mergeFields);
            }
            else
            {
                lMessages.Text = "<div class='alert alert-warning'>No audience is configured for this block.</div>";
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Handles displaying the stored filter values.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e as DisplayFilterValueArgs (hint: e.Key and e.Value).</param>
        protected void gfFilter_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e)
        {
            if (AvailableAttributes != null)
            {
                var attribute = AvailableAttributes.FirstOrDefault(a => ("Attribute_" + a.Key) == e.Key);
                if (attribute != null)
                {
                    try
                    {
                        var values = JsonConvert.DeserializeObject <List <string> >(e.Value);
                        e.Value = attribute.FieldType.Field.FormatFilterValues(attribute.QualifierValues, values);
                        return;
                    }
                    catch
                    {
                        // intentionally ignore
                    }
                }
            }

            switch (e.Key)
            {
            case "Date Range":
                e.Value = DateRangePicker.FormatDelimitedValues(e.Value);
                break;

            // don't display dead setting
            case "From Date":
                e.Value = string.Empty;
                break;

            // don't display dead setting
            case "To Date":
                e.Value = string.Empty;
                break;

            case "Prayer Category":

                int categoryId = e.Value.AsIntegerOrNull() ?? All.Id;
                if (categoryId == All.Id)
                {
                    e.Value = "All";
                }
                else
                {
                    var category = CategoryCache.Get(categoryId);
                    if (category != null)
                    {
                        e.Value = category.Name;
                    }
                }

                break;

            case "Prayer Campus":

                var campus = CampusCache.Get(e.Value.AsInteger());
                e.Value = campus != null ? campus.Name : string.Empty;

                break;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Saves the prayer request.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns>The response to send back to the client.</returns>
        private CallbackResponse SaveRequest(Dictionary <string, object> parameters)
        {
            using (var rockContext = new RockContext())
            {
                var           prayerRequestService = new PrayerRequestService(rockContext);
                PrayerRequest prayerRequest;
                var           requestGuid = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull();

                if (requestGuid.HasValue)
                {
                    prayerRequest = prayerRequestService.Get(requestGuid.Value);

                    if (prayerRequest == null || !BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson))
                    {
                        return(new CallbackResponse
                        {
                            Error = "You are not authorized to edit prayer requests."
                        });
                    }
                }
                else
                {
                    int?categoryId = null;

                    if (DefaultCategory.HasValue)
                    {
                        categoryId = CategoryCache.Get(DefaultCategory.Value).Id;
                    }

                    prayerRequest = new PrayerRequest
                    {
                        Id              = 0,
                        IsActive        = true,
                        IsApproved      = EnableAutoApprove,
                        AllowComments   = false,
                        EnteredDateTime = RockDateTime.Now,
                        CategoryId      = categoryId
                    };
                    prayerRequestService.Add(prayerRequest);

                    if (EnableAutoApprove)
                    {
                        prayerRequest.ApprovedByPersonAliasId = RequestContext.CurrentPerson?.PrimaryAliasId;
                        prayerRequest.ApprovedOnDateTime      = RockDateTime.Now;
                        prayerRequest.ExpirationDate          = RockDateTime.Now.AddDays(ExpiresAfterDays);
                    }
                }

                prayerRequest.FirstName = ( string )parameters["firstName"];
                prayerRequest.LastName  = ( string )parameters["lastName"];
                prayerRequest.Email     = ( string )parameters["email"];
                prayerRequest.Text      = ( string )parameters["request"];

                if (ShowCampus)
                {
                    if (parameters.ContainsKey("campus"))
                    {
                        var campusGuid = (( string )parameters["campus"]).AsGuidOrNull();

                        if (campusGuid.HasValue)
                        {
                            prayerRequest.CampusId = CampusCache.Get(campusGuid.Value).Id;
                        }
                    }
                    else
                    {
                        prayerRequest.CampusId = CampusCache.All().FirstOrDefault(a => a.IsActive ?? false)?.Id;
                    }
                }

                if (ShowCategory && parameters.ContainsKey("category"))
                {
                    var categoryGuid = (( string )parameters["category"]).AsGuidOrNull();

                    if (categoryGuid.HasValue)
                    {
                        prayerRequest.CategoryId = CategoryCache.Get(categoryGuid.Value).Id;
                    }
                    else if (prayerRequest.Id > 0)
                    {
                        prayerRequest.CategoryId = null;
                    }
                }

                if (ShowPublicDisplayFlag)
                {
                    prayerRequest.IsPublic = ( bool )parameters["allowPublication"];
                }

                if (ShowUrgentFlag)
                {
                    prayerRequest.IsUrgent = ( bool )parameters["urgent"];
                }

                if (RequestContext.CurrentPerson != null)
                {
                    //
                    // If there is a logged in person and the names still match, meaning they are not
                    // entering a prayer request for somebody else, then set the requested by property.
                    //
                    var person = RequestContext.CurrentPerson;
                    if (prayerRequest.FirstName == person.FirstName && prayerRequest.LastName == person.LastName)
                    {
                        prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                    }
                }
                else
                {
                    //
                    // If there is not a logged in person, try to match to an existing person.
                    //
                    var person = MatchPerson(prayerRequest, rockContext);

                    if (person != null)
                    {
                        prayerRequest.RequestedByPersonAliasId = person.PrimaryAliasId;
                    }
                }

                //
                // Save all changes to database.
                //
                rockContext.SaveChanges();

                StartWorkflow(prayerRequest, rockContext);
            }

            if (CompletionAction == 0)
            {
                return(new CallbackResponse
                {
                    Content = CompletionXaml ?? string.Empty
                });
            }
            else if (CompletionAction == 1)
            {
                return(new CallbackResponse
                {
                    Command = "PopPage",
                    CommandParameter = "true"
                });
            }
            else
            {
                return(new CallbackResponse
                {
                    Content = AttributeDefaults.CompletionXaml
                });
            }
        }
        public string GetSeriesPartitionName(int metricId, [FromBody] List <string> metricValuePartitionEntityIdList)
        {
            var entityTypeEntityIdList = metricValuePartitionEntityIdList.Select(a => a.Split('|')).Select(a =>
                                                                                                           new
            {
                EntityTypeId = a[0].AsIntegerOrNull(),
                EntityId     = a[1].AsIntegerOrNull()
            });

            var rockContext = new RockContext();

            List <string> seriesPartitionValues = new List <string>();

            foreach (var entityTypeEntity in entityTypeEntityIdList)
            {
                if (entityTypeEntity.EntityTypeId.HasValue && entityTypeEntity.EntityId.HasValue)
                {
                    var entityTypeCache = EntityTypeCache.Get(entityTypeEntity.EntityTypeId.Value);
                    if (entityTypeCache != null)
                    {
                        if (entityTypeCache.Id == EntityTypeCache.GetId <Campus>())
                        {
                            var campus = CampusCache.Get(entityTypeEntity.EntityId.Value);
                            if (campus != null)
                            {
                                seriesPartitionValues.Add(campus.Name);
                            }
                        }
                        else if (entityTypeCache.Id == EntityTypeCache.GetId <DefinedValue>())
                        {
                            var definedValue = DefinedValueCache.Get(entityTypeEntity.EntityId.Value);
                            if (definedValue != null)
                            {
                                seriesPartitionValues.Add(definedValue.ToString());
                            }
                        }
                        else
                        {
                            Type[]     modelType          = { entityTypeCache.GetEntityType() };
                            Type       genericServiceType = typeof(Rock.Data.Service <>);
                            Type       modelServiceType   = genericServiceType.MakeGenericType(modelType);
                            var        serviceInstance    = Activator.CreateInstance(modelServiceType, new object[] { rockContext }) as IService;
                            MethodInfo getMethod          = serviceInstance.GetType().GetMethod("Get", new Type[] { typeof(int) });
                            var        result             = getMethod.Invoke(serviceInstance, new object[] { entityTypeEntity.EntityId });
                            if (result != null)
                            {
                                seriesPartitionValues.Add(result.ToString());
                            }
                        }
                    }
                }
            }

            if (seriesPartitionValues.Any())
            {
                return(seriesPartitionValues.AsDelimited(","));
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Gets the cache object associated with this Entity
 /// </summary>
 /// <returns></returns>
 public IEntityCache GetCacheObject()
 {
     return(CampusCache.Get(this.Id));
 }
Ejemplo n.º 12
0
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] options = selection.Split('|');
            if (options.Length < 4)
            {
                return(null);
            }

            Guid groupTypeGuid = options[0].AsGuid();

            var        campusGuidList = options[0].Split(',').AsGuidList();
            List <int> campusIds      = new List <int>();

            foreach (var campusGuid in campusGuidList)
            {
                var campus = CampusCache.Get(campusGuid);
                if (campus != null)
                {
                    campusIds.Add(campus.Id);
                }
            }

            if (!campusIds.Any())
            {
                return(null);
            }

            ComparisonType comparisonType = options[1].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo);
            int?           attended       = options[2].AsIntegerOrNull();
            string         slidingDelimitedValues;

            if (options[3].AsIntegerOrNull().HasValue)
            {
                //// selection was from when it just simply a LastXWeeks instead of Sliding Date Range
                // Last X Weeks was treated as "LastXWeeks * 7" days, so we have to convert it to a SlidingDateRange of Days to keep consistent behavior
                int lastXWeeks = options[3].AsIntegerOrNull() ?? 1;
                var fakeSlidingDateRangePicker = new SlidingDateRangePicker();
                fakeSlidingDateRangePicker.SlidingDateRangeMode = SlidingDateRangePicker.SlidingDateRangeType.Last;
                fakeSlidingDateRangePicker.TimeUnit             = SlidingDateRangePicker.TimeUnitType.Day;
                fakeSlidingDateRangePicker.NumberOfTimeUnits    = lastXWeeks * 7;
                slidingDelimitedValues = fakeSlidingDateRangePicker.DelimitedValues;
            }
            else
            {
                slidingDelimitedValues = options[3].Replace(',', '|');
            }

            var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues);

            var rockContext   = serviceInstance.Context as RockContext;
            var attendanceQry = new AttendanceService(rockContext).Queryable().Where(a => a.DidAttend.HasValue && a.DidAttend.Value);

            attendanceQry = attendanceQry.Where(a => a.CampusId.HasValue && campusIds.Contains((int)a.CampusId));

            if (dateRange.Start.HasValue)
            {
                var startDate = dateRange.Start.Value;
                attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate >= startDate);
            }

            if (dateRange.End.HasValue)
            {
                var endDate = dateRange.End.Value;
                attendanceQry = attendanceQry.Where(a => a.Occurrence.OccurrenceDate < endDate);
            }

            var qry = new PersonService(rockContext).Queryable()
                      .Where(p => attendanceQry.Count(xx => xx.PersonAlias.PersonId == p.Id) == attended);

            var compareEqualExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p") as BinaryExpression;
            var result = FilterExpressionExtractor.AlterComparisonType(comparisonType, compareEqualExpression, null);

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

            var attribute = AttributeCache.Get(GetAttributeValue(action, PERSON_ATTRIBUTE_KEY).AsGuid(), rockContext);

            if (attribute != null)
            {
                var    mergeFields  = GetMergeFields(action);
                string firstName    = GetAttributeValue(action, FIRST_NAME_KEY, true).ResolveMergeFields(mergeFields);
                string lastName     = GetAttributeValue(action, LAST_NAME_KEY, true).ResolveMergeFields(mergeFields);
                string email        = GetAttributeValue(action, EMAIL_KEY, true).ResolveMergeFields(mergeFields);
                string mobileNumber = GetAttributeValue(action, MOBILE_NUMBER_KEY, true).ResolveMergeFields(mergeFields) ?? string.Empty;

                int?birthDay   = GetAttributeValue(action, BIRTH_DAY_KEY, true).ResolveMergeFields(mergeFields).AsIntegerOrNull();
                int?birthMonth = GetAttributeValue(action, BIRTH_MONTH_KEY, true).ResolveMergeFields(mergeFields).AsIntegerOrNull();
                int?birthYear  = GetAttributeValue(action, BIRTH_YEAR_KEY, true).ResolveMergeFields(mergeFields).AsIntegerOrNull();

                if (string.IsNullOrWhiteSpace(firstName) ||
                    string.IsNullOrWhiteSpace(lastName) ||
                    (string.IsNullOrWhiteSpace(email) && string.IsNullOrWhiteSpace(mobileNumber)))
                {
                    errorMessages.Add("First Name, Last Name, and either Email or Mobile Number are required. One or more of these values was not provided!");
                }
                else
                {
                    Person      person        = null;
                    PersonAlias personAlias   = null;
                    var         personService = new PersonService(rockContext);

                    var personQuery        = new PersonService.PersonMatchQuery(firstName, lastName, email, mobileNumber, null, birthMonth, birthDay, birthYear);
                    var updatePrimaryEmail = GetAttributeValue(action, UPDATE_PRIMARY_EMAIL).AsBooleanOrNull() ?? true;   // Default "true" to preserve functionality before this setting was added
                    person = personService.FindPerson(personQuery, updatePrimaryEmail);

                    if (person.IsNotNull())
                    {
                        personAlias = person.PrimaryAlias;
                    }
                    else
                    {
                        // Add New Person
                        person                   = new Person();
                        person.FirstName         = firstName.FixCase();
                        person.LastName          = lastName.FixCase();
                        person.IsEmailActive     = true;
                        person.Email             = email;
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        person.BirthMonth        = birthMonth;
                        person.BirthDay          = birthDay;
                        person.BirthYear         = birthYear;

                        UpdatePhoneNumber(person, mobileNumber);

                        var defaultConnectionStatus = DefinedValueCache.Get(GetAttributeValue(action, DEFAULT_CONNECTION_STATUS_KEY).AsGuid());
                        if (defaultConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = defaultConnectionStatus.Id;
                        }

                        var defaultRecordStatus = DefinedValueCache.Get(GetAttributeValue(action, DEFAULT_RECORD_STATUS_KEY).AsGuid());
                        if (defaultRecordStatus != null)
                        {
                            person.RecordStatusValueId = defaultRecordStatus.Id;
                        }

                        var defaultCampusGuid = GetAttributeValue(action, DEFAULT_CAMPUS_KEY, true).AsGuidOrNull();
                        var defaultCampus     = defaultCampusGuid.HasValue ? CampusCache.Get(defaultCampusGuid.Value) : null;
                        var defaultCampusId   = defaultCampus?.Id;

                        var familyGroup = PersonService.SaveNewPerson(person, rockContext, defaultCampusId, false);
                        if (familyGroup != null && familyGroup.Members.Any())
                        {
                            person      = familyGroup.Members.Select(m => m.Person).First();
                            personAlias = person.PrimaryAlias;
                        }
                    }

                    if (person != null && personAlias != null)
                    {
                        SetWorkflowAttributeValue(action, attribute.Guid, personAlias.Guid.ToString());
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName));
                        return(true);
                    }
                    else
                    {
                        errorMessages.Add("Person or Primary Alias could not be determined!");
                    }
                }
            }
            else
            {
                errorMessages.Add("Person Attribute could not be found!");
            }

            if (errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                return(false);
            }

            return(true);
        }
        protected void BindGrid()
        {
            RockContext                   rockContext                   = new RockContext();
            PersonAliasService            personAliasService            = new PersonAliasService(rockContext);
            WorkflowService               workflowTypeService           = new WorkflowService(rockContext);
            WorkflowService               workflowService               = new WorkflowService(rockContext);
            AttributeService              attributeService              = new AttributeService(rockContext);
            AttributeValueService         attributeValueService         = new AttributeValueService(rockContext);
            RegistrationRegistrantService registrationRegistrantService = new RegistrationRegistrantService(rockContext);

            List <string> workflowTypes   = GetAttributeValues("WorkflowTypes");
            List <string> workflowTypeIds = new List <string>();

            foreach (string workflowTypeGuid in workflowTypes)
            {
                workflowTypeIds.Add(WorkflowTypeCache.Get(workflowTypeGuid.AsGuid()).Id.ToString());
            }

            var attributes   = attributeService.Queryable().Where(a => workflowTypeIds.Contains(a.EntityTypeQualifierValue) && a.EntityTypeQualifierColumn == "WorkflowTypeId");
            var attributeIds = attributes.Select(a => a.Id);

            // Get all the family members
            var familyMembers = personAliasService.Get(PageParameter("PersonAliasId").AsInteger()).Person.GetFamilyMembers(true);

            var familyAliasIds = familyMembers.SelectMany(fm => fm.Person.Aliases.Select(pa => pa.Id)).ToList();

            var discountCodes = registrationRegistrantService.Queryable().Where(rr => rr.PersonAliasId.HasValue && familyAliasIds.Contains(rr.PersonAliasId.Value))
                                .Where(rr => rr.Registration.DiscountCode != null && rr.Registration.DiscountCode != "")
                                .ToDictionary(x => x.Registration.DiscountCode.ToUpper(), x => x.Registration.DiscountAmount);

            var qry = workflowService.Queryable().Where(w => workflowTypeIds.Contains(w.WorkflowTypeId.ToString()))
                      .GroupJoin(attributeValueService.Queryable().Where(av => attributeIds.Contains(av.AttributeId)),
                                 w => w.Id,
                                 av => av.EntityId,
                                 (w, av) => new { Workflow = w, AttributeValues = av })
                      .Where(obj => obj.AttributeValues.Any(av => av.Attribute.Key == "DiscountCode" && discountCodes.Keys.Contains(av.Value)))
                      .ToList()
                      .Select(obj => new {
                Id              = obj.Workflow.Id,
                FirstName       = obj.AttributeValues.Where(av => av.Attribute.Key == "StudentFirstName").Select(av => av.Value).DefaultIfEmpty(obj.AttributeValues.Where(av => av.Attribute.Key == "ParentFirstName").Select(av => av.Value).FirstOrDefault()).FirstOrDefault(),
                LastName        = obj.AttributeValues.Where(av => av.Attribute.Key == "StudentLastName").Select(av => av.Value).DefaultIfEmpty(obj.AttributeValues.Where(av => av.Attribute.Key == "ParentLastName").Select(av => av.Value).FirstOrDefault()).FirstOrDefault(),
                Campus          = obj.AttributeValues.Where(av => av.Attribute.Key == "Campus").Select(av => CampusCache.Get(av.Value.AsGuid())).FirstOrDefault(),
                ApplicationYear = obj.AttributeValues.Where(av => av.Attribute.Key == "ApplicationYear").Select(av => av.Value).DefaultIfEmpty(attributes.Where(a => a.Key == "ApplicationYear").Select(a => a.DefaultValue).FirstOrDefault()).FirstOrDefault(),
                DiscountCode    = obj.AttributeValues.Where(av => av.Attribute.Key == "DiscountCode").Select(av => av.Value).FirstOrDefault(),
                DiscountAmount  = discountCodes.ContainsKey(obj.AttributeValues.Where(av => av.Attribute.Key == "DiscountCode").Select(av => av.Value.ToUpper()).FirstOrDefault()) ?discountCodes[obj.AttributeValues.Where(av => av.Attribute.Key == "DiscountCode").Select(av => av.Value.ToUpper()).FirstOrDefault()]:0,
                Event           = obj.AttributeValues.Where(av => av.Attribute.Key == "EventStudentisAttending").Select(av => av.Value).DefaultIfEmpty(obj.AttributeValues.Where(av => av.Attribute.Key == "EventLeaderisAttending").Select(av => av.Value).FirstOrDefault()).FirstOrDefault(),
                Status          = obj.Workflow.Status
            });

            gFamilyProfile.DataSource = qry.ToList();
            gFamilyProfile.DataBind();
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Binds the metrics.
        /// </summary>
        private void BindMetrics()
        {
            var metricCategoryList = new List <MetricCategory>();

            int campusEntityTypeId   = EntityTypeCache.Get(typeof(Rock.Model.Campus)).Id;
            int scheduleEntityTypeId = EntityTypeCache.Get(typeof(Rock.Model.Schedule)).Id;

            int?campusId = bddlCampus.SelectedValueAsInt();
            //int? scheduleId = bddlService.SelectedValueAsInt();
            DateTime?weekend = bddlWeekend.SelectedValue.AsDateTime();

            // If we changed the campus, make sure we reload the services
            if (campusId != _selectedCampusId)
            {
                _selectedCampusId = GetBlockUserPreference("CampusId").AsIntegerOrNull();
                SaveViewState();
                //bddlService.Items.Clear();
                // Load service times
                foreach (var service in GetServices(CampusCache.Get(campusId.Value)))
                {
                    //    bddlService.Items.Add( new ListItem( service.Name, service.Id.ToString() ) );
                }
                //bddlService.SetValue( _selectedServiceId.Value );
            }

            var notes = new List <string>();

            if (campusId.HasValue && weekend.HasValue)
            {
                SetBlockUserPreference("CampusId", campusId.HasValue ? campusId.Value.ToString() : "");

                var metricCategories = MetricCategoriesFieldAttribute.GetValueAsGuidPairs(GetAttributeValue("MetricCategories"));
                var metricGuids      = metricCategories.Select(a => a.MetricGuid).ToList();
                using (var rockContext = new RockContext())
                {
                    var metricValueService = new MetricValueService(rockContext);
                    var metrics            = new MetricService(rockContext)
                                             .GetByGuids(metricGuids)
                                             .Where(m =>
                                                    m.MetricPartitions.Count == 1 &&
                                                    m.MetricPartitions.Any(p => p.EntityTypeId.HasValue && p.EntityTypeId.Value == campusEntityTypeId))
                                             .OrderBy(m => m.Title)
                                             .Select(m => new
                    {
                        m.Id,
                        m.Title,
                        CampusPartitionId   = m.MetricPartitions.Where(p => p.EntityTypeId.HasValue && p.EntityTypeId.Value == campusEntityTypeId).Select(p => p.Id).FirstOrDefault(),
                        SchedulePartitionId = m.MetricPartitions.Where(p => p.EntityTypeId.HasValue && p.EntityTypeId.Value == scheduleEntityTypeId).Select(p => p.Id).FirstOrDefault(),
                        CategoryName        = m.MetricCategories.Select(c => c.Category.Name).FirstOrDefault()
                    });
                    foreach (var metric in metrics.OrderBy(m => m.CategoryName).ThenBy(m => m.Title))
                    {
                        MetricCategory category = null;
                        if (metricCategoryList.Any(mct => mct.CategoryName == metric.CategoryName))
                        {
                            category = metricCategoryList.Where(mct => mct.CategoryName == metric.CategoryName).FirstOrDefault();
                        }
                        else
                        {
                            category = new MetricCategory()
                            {
                                CategoryName = metric.CategoryName, Metrics = new List <Metric>()
                            };
                            metricCategoryList.Add(category);
                        }

                        var metricObj = new Metric(metric.Id, metric.Title);
                        if (campusId.HasValue && weekend.HasValue)
                        {
                            var metricValue = metricValueService
                                              .Queryable().AsNoTracking()
                                              .Where(v =>
                                                     v.MetricId == metric.Id &&
                                                     v.MetricValueDateTime.HasValue && v.MetricValueDateTime.Value == weekend.Value &&
                                                     v.MetricValuePartitions.Count == 1 &&
                                                     v.MetricValuePartitions.Any(p => p.MetricPartitionId == metric.CampusPartitionId && p.EntityId.HasValue && p.EntityId.Value == campusId.Value))
                                              .FirstOrDefault();

                            if (metricValue != null)
                            {
                                metricObj.Value = metricValue.YValue;

                                if (!string.IsNullOrWhiteSpace(metricValue.Note) &&
                                    !notes.Contains(metricValue.Note))
                                {
                                    notes.Add(metricValue.Note);
                                }
                            }
                        }

                        category.Metrics.Add(metricObj);
                    }
                }
            }
            rptrMetricCategory.DataSource = metricCategoryList;
            rptrMetricCategory.DataBind();

            if (campusId.HasValue)
            {
                rptrService.DataSource = GetServices(CampusCache.Get(campusId.Value));
                rptrService.DataBind();
                rptrService.Visible = rptrService.Items.Count > 0;
            }


            tbNote.Text = notes.AsDelimited(Environment.NewLine + Environment.NewLine);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            var groupMemberService            = new GroupMemberService(rockContext);
            var groupService                  = new GroupService(rockContext);
            var groupTypeService              = new GroupTypeService(rockContext);
            var attributeService              = new AttributeService(rockContext);
            var attributeValueService         = new AttributeValueService(rockContext);
            var personService                 = new PersonService(rockContext);
            var personAliasService            = new PersonAliasService(rockContext);
            var entityTypeService             = new EntityTypeService(rockContext);
            var registrationRegistrantService = new RegistrationRegistrantService(rockContext);
            var eiogmService                  = new EventItemOccurrenceGroupMapService(rockContext);
            var groupLocationService          = new GroupLocationService(rockContext);
            var locationService               = new LocationService(rockContext);
            var signatureDocumentServce       = new SignatureDocumentService(rockContext);
            var phoneNumberService            = new PhoneNumberService(rockContext);

            int[] signatureDocumentIds = { };
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates")))
            {
                signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse);
            }

            int[] registrationInstanceIds = { };
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("RegistrationInstances")))
            {
                registrationInstanceIds = Array.ConvertAll(GetAttributeValue("RegistrationInstances").Split(','), int.Parse);
            }

            Guid bbGroup = GetAttributeValue("Group").AsGuid();
            var  group   = new GroupService(rockContext).Get(bbGroup);

            Guid hsmGroupTypeGuid = GetAttributeValue("MSMGroupType").AsGuid();
            int? hsmGroupTypeId   = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault();

            int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id;

            var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList();

            hlGroup.NavigateUrl = "/group/" + group.Id;

            var attributeIds = attributeService.Queryable()
                               .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue)))
                               .Select(a => a.Id).ToList();

            var gmTmpqry = groupMemberService.Queryable()
                           .Where(gm => (gm.GroupId == group.Id));

            var qry = gmTmpqry
                      .Join(personAliasService.Queryable(),
                            obj => obj.PersonId,
                            pa => pa.PersonId,
                            (obj, pa) => new { GroupMember = obj, PersonAlias = pa }
                            )
                      .Join(registrationRegistrantService.Queryable(),
                            obj => obj.PersonAlias.Id,
                            rr => rr.PersonAliasId,
                            (obj, rr) => new { GroupMember = obj.GroupMember, Person = obj.GroupMember.Person, RegistrationRegistrant = rr })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => new { PersonId = (int?)obj.Person.Id, AttributeId = 739 },
                                 av => new { PersonId = av.EntityId, av.AttributeId },
                                 (obj, av) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, School = av.Select(s => s.Value).FirstOrDefault() })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.GroupMember.Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.RegistrationRegistrant.Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ })
                      .Where(obj => registrationInstanceIds.Contains(obj.RegistrationRegistrant.Registration.RegistrationInstanceId));

            var qry2 = gmTmpqry
                       .GroupJoin(
                groupMemberService.Queryable()
                .Join(groupService.Queryable(),
                      gm => new { Id = gm.GroupId, GroupTypeId = 10 },
                      g => new { g.Id, g.GroupTypeId },
                      (gm, g) => new { GroupMember = gm, Group = g })
                .Join(groupLocationService.Queryable(),
                      obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = (int?)19 },
                      gl => new { gl.GroupId, gl.GroupLocationTypeValueId },
                      (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl })
                .Join(locationService.Queryable(),
                      obj => obj.GroupLocation.LocationId,
                      l => l.Id,
                      (obj, l) => new { GroupMember = obj.GroupMember, Location = l }),
                gm => gm.PersonId,
                glgm => glgm.GroupMember.PersonId,
                (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() }
                )
                       .GroupJoin(signatureDocumentServce.Queryable()
                                  .Join(personAliasService.Queryable(),
                                        sd => sd.AppliesToPersonAliasId,
                                        pa => pa.Id,
                                        (sd, pa) => new { SignatureDocument = sd, Alias = pa }),
                                  obj => obj.GroupMember.PersonId,
                                  sd => sd.Alias.PersonId,
                                  (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds })
                       .GroupJoin(phoneNumberService.Queryable(),
                                  obj => obj.GroupMember.PersonId,
                                  p => p.PersonId,
                                  (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn });


            if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix))))
            {
                string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower();
                qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable();
            }
            decimal?lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull();
            decimal?upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull();

            if (lowerVal != null && upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal && q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable();
            }
            else if (lowerVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue >= lowerVal).AsQueryable();
            }
            else if (upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Registration.BalanceDue <= upperVal).AsQueryable();
            }
            else if (!string.IsNullOrEmpty(cmpCampus.SelectedValue))
            {
                CampusCache campus = CampusCache.Get(cmpCampus.SelectedCampusId.Value);
                qry = qry.ToList().Where(q => q.RegistrationAttributeValues.Where(ra => ra.AttributeKey == "Whichcampus" && ra.Value.Contains(campus.Name.Replace(" ", ""))).Any()).AsQueryable();
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var tmp  = qry.ToList();
            var tmp2 = qry2.ToList();

            lStats.Text = "Query Runtime: " + stopwatch.Elapsed;
            stopwatch.Reset();

            stopwatch.Start();

            var newQry = tmp.Select(g => new
            {
                Id                    = g.GroupMember.Id,
                RegisteredBy          = new ModelValue <Person>(g.RegistrationRegistrant.Registration.PersonAlias.Person),
                Registrant            = new ModelValue <Person>(g.Person),
                Age                   = g.Person.Age,
                GraduationYear        = g.Person.GraduationYear,
                RegistrationId        = g.RegistrationRegistrant.RegistrationId,
                Group                 = new ModelValue <Rock.Model.Group>((Rock.Model.Group)g.GroupMember.Group),
                DOB                   = g.Person.BirthDate.HasValue ? g.Person.BirthDate.Value.ToShortDateString() : "",
                Address               = new ModelValue <Rock.Model.Location>((Rock.Model.Location)tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location).FirstOrDefault()),
                Email                 = g.Person.Email,
                Gender                = g.Person.Gender,         // (B & B Registration)
                GraduationYearProfile = g.Person.GraduationYear, // (Person Profile)
                HomePhone             = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(),
                CellPhone             = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(),
                GroupMemberData       = new Func <GroupMemberAttributes>(() =>
                {
                    GroupMemberAttributes gma = new GroupMemberAttributes(g.GroupMember, g.Person, g.GroupMemberAttributeValues);
                    return(gma);
                })(),
                RegistrantData = new Func <RegistrantAttributes>(() =>
                {
                    RegistrantAttributes row = new RegistrantAttributes(g.RegistrationRegistrant, g.RegistrationAttributeValues);
                    return(row);
                })(),
                School              = string.IsNullOrEmpty(g.School)?"":DefinedValueCache.Get(g.School.AsGuid()) != null?DefinedValueCache.Get(g.School.AsGuid()).Value:"",
                LegalRelease        = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.SignatureDocuments).OrderByDescending(sd => sd.SignatureDocument.CreatedDateTime).Where(sd => signatureDocumentIds.Contains(sd.SignatureDocument.SignatureDocumentTemplateId)).Select(sd => sd.SignatureDocument.SignatureDocumentTemplate.Name + " (" + sd.SignatureDocument.Status.ToString() + ")").FirstOrDefault(),
                Departure           = g.GroupMemberAttributeValues.Where(av => av.AttributeKey == "Departure").Select(av => av.Value).FirstOrDefault(),
                Campus              = group.Campus,                                                                                                        //
                Role                = group.ParentGroup.GroupType.Name.Contains("Serving") || group.Name.ToLower().Contains("leader")? "Leader":"Student", //
                MSMGroup            = String.Join(", ", groupMemberService.Queryable().Where(gm => gm.PersonId == g.GroupMember.PersonId && gm.Group.GroupTypeId == hsmGroupTypeId && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.Group.Name).ToList()),
                Person              = g.Person,
                AddressStreet       = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null?gm.Location.Street1:"").FirstOrDefault(),
                AddressCityStateZip = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null ? gm.Location.City + ", " + gm.Location.State + " " + gm.Location.PostalCode : "").FirstOrDefault(),

                RegistrantName = g.Person.FullName,
            }).OrderBy(w => w.Registrant.Model.LastName).ToList().AsQueryable();

            lStats.Text += "<br />Object Build Runtime: " + stopwatch.Elapsed;

            stopwatch.Stop();
            gReport.GetRecipientMergeFields += GReport_GetRecipientMergeFields;
            var mergeFields = new List <String>();

            mergeFields.Add("Id");
            mergeFields.Add("RegisteredBy");
            mergeFields.Add("Group");
            mergeFields.Add("Registrant");
            mergeFields.Add("Age");
            mergeFields.Add("GraduationYear");
            mergeFields.Add("DOB");
            mergeFields.Add("Address");
            mergeFields.Add("Email");
            mergeFields.Add("Gender");
            mergeFields.Add("GraduationYearProfile");
            mergeFields.Add("HomePhone");
            mergeFields.Add("CellPhone");
            mergeFields.Add("GroupMemberData");
            mergeFields.Add("RegistrantData");
            mergeFields.Add("LegalRelease");
            mergeFields.Add("Departure");
            mergeFields.Add("Campus");
            mergeFields.Add("Role");
            mergeFields.Add("MSMGroup");
            gReport.CommunicateMergeFields = mergeFields;

            /*
             * if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}POA", keyPrefix))))
             * {
             *  string poa = GetUserPreference(string.Format("{0}POA", keyPrefix));
             *  if (poa == "[Blank]")
             *  {
             *      poa = "";
             *  }
             *  newQry = newQry.Where(q => q.GroupMemberData.POA == poa);
             * }
             */

            SortProperty sortProperty = gReport.SortProperty;

            if (sortProperty != null)
            {
                gReport.SetLinqDataSource(newQry.Sort(sortProperty));
            }
            else
            {
                gReport.SetLinqDataSource(newQry.OrderBy(p => p.Registrant.Model.LastName));
            }
            gReport.DataBind();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var attribute = AttributeCache.Get(GetAttributeValue(action, "PersonAttribute").AsGuid(), rockContext);

            if (attribute != null)
            {
                var      mergeFields        = GetMergeFields(action);
                string   firstName          = GetAttributeValue(action, "FirstName", true).ResolveMergeFields(mergeFields);
                string   lastName           = GetAttributeValue(action, "LastName", true).ResolveMergeFields(mergeFields);
                string   email              = GetAttributeValue(action, "Email", true).ResolveMergeFields(mergeFields);
                string   phone              = GetAttributeValue(action, "Phone", true).ResolveMergeFields(mergeFields);
                DateTime?dateofBirth        = GetAttributeValue(action, "DOB", true).AsDateTime();
                Guid?    addressGuid        = GetAttributeValue(action, "Address", true).AsGuidOrNull();
                Guid?    familyOrPersonGuid = GetAttributeValue(action, "FamilyAttribute", true).AsGuidOrNull();
                Location address            = null;
                // Set the street and postal code if we have an address
                if (addressGuid.HasValue)
                {
                    LocationService addressService = new LocationService(rockContext);
                    address = addressService.Get(addressGuid.Value);
                }


                if (string.IsNullOrWhiteSpace(firstName) ||
                    string.IsNullOrWhiteSpace(lastName) ||
                    (string.IsNullOrWhiteSpace(email) &&
                     string.IsNullOrWhiteSpace(phone) &&
                     !dateofBirth.HasValue &&
                     (address == null || address != null && string.IsNullOrWhiteSpace(address.Street1)))
                    )
                {
                    errorMessages.Add("First Name, Last Name, and one of Email, Phone, DoB, or Address Street are required. One or more of these values was not provided!");
                }
                else
                {
                    Rock.Model.Person person      = null;
                    PersonAlias       personAlias = null;
                    var personService             = new PersonService(rockContext);
                    var people = personService.GetByMatch(firstName, lastName, dateofBirth, email, phone, address?.Street1, address?.PostalCode).ToList();
                    if (people.Count == 1 &&
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(email) ||
                         (people.First().Email != null &&
                          email.ToLower().Trim() == people.First().Email.ToLower().Trim()))
                        )
                    {
                        person      = people.First();
                        personAlias = person.PrimaryAlias;
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        // Add New Person
                        person               = new Rock.Model.Person();
                        person.FirstName     = firstName;
                        person.LastName      = lastName;
                        person.IsEmailActive = true;
                        person.Email         = email;
                        if (dateofBirth.HasValue)
                        {
                            person.BirthDay   = dateofBirth.Value.Day;
                            person.BirthMonth = dateofBirth.Value.Month;
                            person.BirthYear  = dateofBirth.Value.Year;
                        }
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;

                        var defaultConnectionStatus = DefinedValueCache.Get(GetAttributeValue(action, "DefaultConnectionStatus").AsGuid());
                        if (defaultConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = defaultConnectionStatus.Id;
                        }

                        var defaultRecordStatus = DefinedValueCache.Get(GetAttributeValue(action, "DefaultRecordStatus").AsGuid());
                        if (defaultRecordStatus != null)
                        {
                            person.RecordStatusValueId = defaultRecordStatus.Id;
                        }

                        var defaultCampus = CampusCache.Get(GetAttributeValue(action, "DefaultCampus", true).AsGuid());

                        // Get the default family if applicable
                        Group family = null;
                        if (familyOrPersonGuid.HasValue)
                        {
                            PersonAliasService personAliasService = new PersonAliasService(rockContext);
                            family = personAliasService.Get(familyOrPersonGuid.Value)?.Person?.GetFamily();
                            if (family == null)
                            {
                                GroupService groupService = new GroupService(rockContext);
                                family = groupService.Get(familyOrPersonGuid.Value);
                            }
                        }
                        var familyGroup = SaveNewPerson(person, family, (defaultCampus != null ? defaultCampus.Id : ( int? )null), rockContext);
                        if (familyGroup != null && familyGroup.Members.Any())
                        {
                            personAlias = person.PrimaryAlias;

                            // If we have an address, go ahead and save it here.
                            if (address != null)
                            {
                                GroupLocation location = new GroupLocation();
                                location.GroupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id;
                                location.Location = address;
                                familyGroup.GroupLocations.Add(location);
                            }
                        }
                    }

                    // Save/update the phone number
                    if (!string.IsNullOrWhiteSpace(phone))
                    {
                        List <string> changes    = new List <string>();
                        var           numberType = DefinedValueCache.Get(GetAttributeValue(action, "PhoneNumberType").AsGuid());
                        if (numberType != null)
                        {
                            // gets value indicating if phone number is unlisted
                            string unlistedValue     = GetAttributeValue(action, "Unlisted");
                            Guid?  unlistedValueGuid = unlistedValue.AsGuidOrNull();
                            if (unlistedValueGuid.HasValue)
                            {
                                unlistedValue = action.GetWorklowAttributeValue(unlistedValueGuid.Value);
                            }
                            else
                            {
                                unlistedValue = unlistedValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool unlisted = unlistedValue.AsBoolean();

                            // gets value indicating if messaging should be enabled for phone number
                            string smsEnabledValue     = GetAttributeValue(action, "MessagingEnabled");
                            Guid?  smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull();
                            if (smsEnabledValueGuid.HasValue)
                            {
                                smsEnabledValue = action.GetWorklowAttributeValue(smsEnabledValueGuid.Value);
                            }
                            else
                            {
                                smsEnabledValue = smsEnabledValue.ResolveMergeFields(GetMergeFields(action));
                            }
                            bool smsEnabled = smsEnabledValue.AsBoolean();


                            var    phoneModel     = person.PhoneNumbers.FirstOrDefault(p => p.NumberTypeValueId == numberType.Id);
                            string oldPhoneNumber = phoneModel != null ? phoneModel.NumberFormattedWithCountryCode : string.Empty;
                            string newPhoneNumber = PhoneNumber.CleanNumber(phone);

                            if (newPhoneNumber != string.Empty && newPhoneNumber != oldPhoneNumber)
                            {
                                if (phoneModel == null)
                                {
                                    phoneModel = new PhoneNumber();
                                    person.PhoneNumbers.Add(phoneModel);
                                    phoneModel.NumberTypeValueId = numberType.Id;
                                }
                                else
                                {
                                    oldPhoneNumber = phoneModel.NumberFormattedWithCountryCode;
                                }
                                phoneModel.Number             = newPhoneNumber;
                                phoneModel.IsUnlisted         = unlisted;
                                phoneModel.IsMessagingEnabled = smsEnabled;
                            }
                        }
                    }

                    if (person != null && personAlias != null)
                    {
                        SetWorkflowAttributeValue(action, attribute.Guid, personAlias.Guid.ToString());
                        action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, person.FullName));
                        return(true);
                    }
                    else if (!GetAttributeValue(action, "MatchOnly").AsBoolean())
                    {
                        errorMessages.Add("Person or Primary Alias could not be determined!");
                    }
                }
            }
            else
            {
                errorMessages.Add("Person Attribute could not be found!");
            }

            if (errorMessages.Any())
            {
                errorMessages.ForEach(m => action.AddLogEntry(m, true));
                if (GetAttributeValue(action, "ContinueOnError").AsBoolean())
                {
                    errorMessages.Clear();
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Handles the filter display for each saved user value
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        protected void rFilter_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e)
        {
            switch (e.Key)
            {
            case "Start Date":
            case "End Date":
                var dateTime = e.Value.AsDateTime();
                if (dateTime.HasValue)
                {
                    e.Value = dateTime.Value.ToShortDateString();
                }
                else
                {
                    e.Value = null;
                }

                return;

            case "First Name":
                return;

            case "Last Name":
                return;

            case "Campus":
            {
                int?campusId = e.Value.AsIntegerOrNull();
                if (campusId.HasValue)
                {
                    e.Value = CampusCache.Get(campusId.Value).Name;
                }
                return;
            }

            case "Government ID":
                return;

            case "Case Worker":
                int?personAliasId = e.Value.AsIntegerOrNull();
                if (personAliasId.HasValue)
                {
                    var personAlias = new PersonAliasService(new RockContext()).Get(personAliasId.Value);
                    if (personAlias != null)
                    {
                        e.Value = personAlias.Person.FullName;
                    }
                }

                return;

            case "Result":
            case "Status":
                var definedValueId = e.Value.AsIntegerOrNull();
                if (definedValueId.HasValue)
                {
                    var definedValue = DefinedValueCache.Get(definedValueId.Value);
                    if (definedValue != null)
                    {
                        e.Value = definedValue.Value;
                    }
                }

                return;

            default:
                e.Value = string.Empty;
                return;
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The workflow action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        public override bool Execute(RockContext rockContext, Model.WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            var checkInState = GetCheckInState(entity, out errorMessages);

            if (checkInState != null)
            {
                DateTime preSelectCutoff = RockDateTime.Today.AddDays(0 - checkInState.CheckInType.AutoSelectDaysBack);

                var attendanceService = new AttendanceService(rockContext);

                // Find all the schedules that are used for checkin
                var checkinSchedules = new ScheduleService(rockContext)
                                       .Queryable().AsNoTracking()
                                       .Where(s => s.CheckInStartOffsetMinutes.HasValue)
                                       .ToList();

                DateTime sixMonthsAgo = RockDateTime.Today.AddMonths(-6);

                foreach (var family in checkInState.CheckIn.GetFamilies(true))
                {
                    foreach (var person in family.People)
                    {
                        // Find all of the attendance records for this person for any of the check-in types that are currently available for this kiosk and person
                        var groupTypeIds     = person.GroupTypes.Select(t => t.GroupType.Id).ToList();
                        var personAttendance = attendanceService
                                               .Queryable().AsNoTracking()
                                               .Where(a =>
                                                      a.PersonAlias != null &&
                                                      a.Occurrence.Group != null &&
                                                      a.Occurrence.Schedule != null &&
                                                      a.PersonAlias.PersonId == person.Person.Id &&
                                                      groupTypeIds.Contains(a.Occurrence.Group.GroupTypeId) &&
                                                      a.StartDateTime >= sixMonthsAgo &&
                                                      a.DidAttend.HasValue &&
                                                      a.DidAttend.Value == true)
                                               .Select(a => new
                        {
                            a.Id,
                            a.StartDateTime,
                            a.EndDateTime,
                            PersonId    = a.PersonAlias.PersonId,
                            GroupTypeId = a.Occurrence.Group.GroupTypeId,
                            GroupId     = a.Occurrence.GroupId,
                            LocationId  = a.Occurrence.LocationId,
                            ScheduleId  = a.Occurrence.ScheduleId,
                            Schedule    = a.Occurrence.Schedule
                        })
                                               .ToList();

                        // If there are any previous attendance records start evaluating them for last checkin and if options should be preselected.
                        if (personAttendance.Any())
                        {
                            person.FirstTime = false;

                            // Get the datetime that person last checked in
                            person.LastCheckIn = personAttendance.Max(a => a.StartDateTime);

                            // If the date they last checked in is greater than the PreSelect cutoff date, then get all the group/location/schedules
                            // that the person checked into on that date (if they somehow checked into multiple group/locations during same schedule,
                            // only consider the the most recent group/location per schedule
                            var previousCheckins = new List <CheckinInfo>();
                            if (person.LastCheckIn.HasValue &&
                                preSelectCutoff.CompareTo(RockDateTime.Today) < 0 &&
                                person.LastCheckIn.Value.CompareTo(preSelectCutoff) >= 0)
                            {
                                foreach (var item in personAttendance
                                         .Where(a => a.StartDateTime.Date == person.LastCheckIn.Value.Date)
                                         .OrderBy(a => a.Schedule.StartTimeOfDay)
                                         .ThenByDescending(a => a.StartDateTime))
                                {
                                    if (item.ScheduleId.HasValue && !previousCheckins.Any(i => i.ScheduleId == item.ScheduleId))
                                    {
                                        previousCheckins.Add(new CheckinInfo
                                        {
                                            ScheduleId = item.ScheduleId.Value,
                                            GroupId    = item.GroupId.Value,
                                            LocationId = item.LocationId
                                        });
                                    }
                                }
                            }
                            var selectedSchedules = new List <int>();    // Used to keep track of which schedules have already had options preselected.

                            foreach (var groupType in person.GroupTypes)
                            {
                                // Find the previous attendance for this group type and save the most recent attendance date
                                var groupTypeAttendance = personAttendance.Where(a => a.GroupTypeId == groupType.GroupType.Id).ToList();
                                if (groupTypeAttendance.Any())
                                {
                                    groupType.LastCheckIn = groupTypeAttendance.Max(a => a.StartDateTime);
                                }

                                foreach (var group in groupType.Groups)
                                {
                                    // Find the previous attendance for this group and save the most recent attendance date
                                    var groupAttendance = groupTypeAttendance.Where(a => a.GroupId == group.Group.Id).ToList();
                                    if (groupAttendance.Any())
                                    {
                                        group.LastCheckIn = groupAttendance.Max(a => a.StartDateTime);
                                    }

                                    // If person checked into this group on last visit, preselect it for now
                                    var previousGroupCheckins = previousCheckins.Where(c => c.GroupId == group.Group.Id).ToList();
                                    if (previousGroupCheckins.Any())
                                    {
                                        group.PreSelected = true;
                                    }

                                    foreach (var location in group.Locations)
                                    {
                                        // Find the previous attendance for this location and save the most recent attendance date
                                        var locationAttendance = groupAttendance.Where(a => a.LocationId == location.Location.Id).ToList();
                                        if (locationAttendance.Any())
                                        {
                                            location.LastCheckIn = locationAttendance.Max(a => a.StartDateTime);
                                        }

                                        if (group.PreSelected)
                                        {
                                            var previousLocationCheckins = previousGroupCheckins.Where(c => c.LocationId == location.Location.Id);
                                            if (previousLocationCheckins.Any())
                                            {
                                                // If person checked into this group and location on last visit, preselect the location for now
                                                location.PreSelected = true;

                                                // Try to find a schedule
                                                var availableSchedules = location.Schedules
                                                                         .Where(s => !selectedSchedules.Contains(s.Schedule.Id))
                                                                         .OrderBy(s => s.StartTime);
                                                foreach (var schedule in availableSchedules)
                                                {
                                                    // If person checked into this group/location/schedule on last visit, preselect it for now
                                                    if (previousLocationCheckins.Any(c => c.ScheduleId == schedule.Schedule.Id))
                                                    {
                                                        schedule.PreSelected = true;
                                                        selectedSchedules.Add(schedule.Schedule.Id);
                                                    }
                                                }
                                                if (!location.Schedules.Any(s => s.PreSelected) && availableSchedules.Any())
                                                {
                                                    var schedule = availableSchedules.First();
                                                    schedule.PreSelected = true;;
                                                    selectedSchedules.Add(schedule.Schedule.Id);
                                                }
                                            }
                                        }

                                        // Find the active schedules for this location (campus)
                                        var locationDateTime = RockDateTime.Now;
                                        if (location.CampusId.HasValue)
                                        {
                                            locationDateTime = CampusCache.Get(location.CampusId.Value)?.CurrentDateTime ?? RockDateTime.Now;
                                        }
                                        var activeScheduleIds = new List <int>();
                                        foreach (var schedule in checkinSchedules)
                                        {
                                            if (schedule.WasScheduleOrCheckInActive(locationDateTime))
                                            {
                                                activeScheduleIds.Add(schedule.Id);
                                            }
                                        }

                                        // Check to see if the person is still checked into this grouptype/group/location combination
                                        var activeAttendanceIds = locationAttendance
                                                                  .Where(a =>
                                                                         a.StartDateTime > DateTime.Today &&
                                                                         a.ScheduleId.HasValue &&
                                                                         activeScheduleIds.Contains(a.ScheduleId.Value) &&
                                                                         !a.EndDateTime.HasValue)
                                                                  .Select(a => a.Id)
                                                                  .ToList();

                                        // If so, allow person to check-out.
                                        if (activeAttendanceIds.Any())
                                        {
                                            var checkOutPerson = family.CheckOutPeople.FirstOrDefault(p => p.Person.Id == person.Person.Id);
                                            if (checkOutPerson == null)
                                            {
                                                checkOutPerson        = new Rock.CheckIn.CheckOutPerson();
                                                checkOutPerson.Person = person.Person;
                                                family.CheckOutPeople.Add(checkOutPerson);
                                            }
                                            checkOutPerson.AttendanceIds.AddRange(activeAttendanceIds);
                                        }
                                    }

                                    // If the group was preselected, but could not preselect the location, try to preselect the first location and schedule
                                    if (group.PreSelected && !group.Locations.Any(l => l.PreSelected) && group.Locations.Any())
                                    {
                                        var location = group.Locations.First();
                                        var schedule = location.Schedules
                                                       .Where(s => !selectedSchedules.Contains(s.Schedule.Id))
                                                       .OrderBy(s => s.StartTime)
                                                       .FirstOrDefault();
                                        if (schedule != null)
                                        {
                                            location.PreSelected = true;
                                            schedule.PreSelected = true;
                                            selectedSchedules.Add(schedule.Schedule.Id);
                                        }
                                    }

                                    // If there were still not any location/schedules able to be preselected for this group, unselect the group.
                                    if (group.PreSelected && !group.Locations.Any(l => l.PreSelected))
                                    {
                                        group.PreSelected = false;
                                    }
                                }

                                groupType.PreSelected = groupType.Groups.Any(g => g.PreSelected);
                            }

                            person.PreSelected = person.GroupTypes.Any(t => t.PreSelected);
                        }
                        else
                        {
                            // Person hasn't had any attendance to selected group types in last 6 months, so check to see if this is the
                            // first time that this person has ever checked into anything
                            person.FirstTime = !attendanceService
                                               .Queryable().AsNoTracking()
                                               .Where(a => a.PersonAlias.PersonId == person.Person.Id)
                                               .Any();
                        }
                    }
                }

                return(true);
            }

            return(false);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Creates the person.
        /// </summary>
        /// <param name="account">The account details.</param>
        /// <returns></returns>
        private Person CreatePerson(AccountData account)
        {
            var rockContext = new RockContext();

            DefinedValueCache dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue(AttributeKeys.ConnectionStatus).AsGuid());
            DefinedValueCache dvcRecordStatus     = DefinedValueCache.Get(GetAttributeValue(AttributeKeys.RecordStatus).AsGuid());

            Person person = new Person
            {
                FirstName         = account.FirstName,
                LastName          = account.LastName,
                Email             = account.Email,
                Gender            = ( Gender )account.Gender,
                IsEmailActive     = true,
                EmailPreference   = EmailPreference.EmailAllowed,
                RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id
            };

            if (dvcConnectionStatus != null)
            {
                person.ConnectionStatusValueId = dvcConnectionStatus.Id;
            }

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

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

            if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(account.MobilePhone)))
            {
                int phoneNumberTypeId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Id;

                var phoneNumber = new PhoneNumber
                {
                    NumberTypeValueId = phoneNumberTypeId,
                    Number            = PhoneNumber.CleanNumber(account.MobilePhone)
                };
                person.PhoneNumbers.Add(phoneNumber);

                // TODO: Do we need to deal with this? -dsh
                //phoneNumber.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );

                // TODO: How to deal with SMS enabled option? -dsh
                phoneNumber.IsMessagingEnabled = false;
            }

            int?campusId = null;

            if (account.Campus.HasValue)
            {
                campusId = CampusCache.Get(account.Campus.Value).Id;
            }

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

            return(person);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Handles the DisplayFilterValue event of the gfNcoaFilter control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.GridFilter.DisplayFilterValueArgs"/> instance containing the event data.</param>
        protected void gfNcoaFilter_DisplayFilterValue(object sender, Rock.Web.UI.Controls.GridFilter.DisplayFilterValueArgs e)
        {
            switch (e.Key)
            {
            case "Move Date":
            case "NCOA Processed Date":
            {
                e.Value = DateRangePicker.FormatDelimitedValues(e.Value);
                break;
            }

            case "Processed":
            {
                var processed = e.Value.ConvertToEnumOrNull <Processed>();
                if (processed.HasValue && processed.Value != Processed.All)
                {
                    e.Value = processed.ConvertToString();
                }
                else
                {
                    e.Value = string.Empty;
                }

                break;
            }

            case "Move Type":
            {
                var moveType = e.Value.ConvertToEnumOrNull <MoveType>();
                if (moveType.HasValue)
                {
                    e.Value = moveType.ConvertToString();
                }
                else
                {
                    e.Value = string.Empty;
                }

                break;
            }

            case "Address Status":
            {
                var addressStatus = e.Value.ConvertToEnumOrNull <AddressStatus>();
                if (addressStatus.HasValue)
                {
                    e.Value = addressStatus.ConvertToString();
                }
                else
                {
                    e.Value = string.Empty;
                }

                break;
            }

            case "Invalid Reason":
            {
                var invalidReason = e.Value.ConvertToEnumOrNull <AddressInvalidReason>();
                if (invalidReason.HasValue)
                {
                    e.Value = invalidReason.ConvertToString();
                }
                else
                {
                    e.Value = string.Empty;
                }

                break;
            }

            case "Campus":
            {
                var campus = CampusCache.Get(e.Value.AsInteger());
                if (campus != null)
                {
                    e.Value = campus.Name;
                }
                else
                {
                    e.Value = string.Empty;
                }
                break;
            }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Sends a background request to Protect My Ministry
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="workflow">The Workflow initiating the request.</param>
        /// <param name="personAttribute">The person attribute.</param>
        /// <param name="ssnAttribute">The SSN attribute.</param>
        /// <param name="requestTypeAttribute">The request type attribute.</param>
        /// <param name="billingCodeAttribute">The billing code attribute.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns>
        /// True/False value of whether the request was successfully sent or not
        /// </returns>
        /// <exception cref="System.NotImplementedException"></exception>
        /// <remarks>
        /// Note: If the associated workflow type does not have attributes with the following keys, they
        /// will automatically be added to the workflow type configuration in order to store the results
        /// of the PMM background check request
        ///     RequestStatus:          The request status returned by PMM request
        ///     RequestMessage:         Any error messages returned by PMM request
        ///     ReportStatus:           The report status returned by PMM
        ///     ReportLink:             The location of the background report on PMM server
        ///     ReportRecommendation:   PMM's recommendation
        ///     Report (BinaryFile):    The downloaded background report
        /// </remarks>
        public override bool SendRequest(RockContext rockContext, Model.Workflow workflow,
                                         AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute,
                                         AttributeCache billingCodeAttribute, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            try
            {
                // Check to make sure workflow is not null
                if (workflow == null)
                {
                    errorMessages.Add("The 'Protect My Ministry' background check provider requires a valid workflow.");
                    return(false);
                }

                // Get the person that the request is for
                Person person = null;
                if (personAttribute != null)
                {
                    Guid?personAliasGuid = workflow.GetAttributeValue(personAttribute.Key).AsGuidOrNull();
                    if (personAliasGuid.HasValue)
                    {
                        person = new PersonAliasService(rockContext).Queryable()
                                 .Where(p => p.Guid.Equals(personAliasGuid.Value))
                                 .Select(p => p.Person)
                                 .FirstOrDefault();
                        person.LoadAttributes(rockContext);
                    }
                }

                if (person == null)
                {
                    errorMessages.Add("The 'Protect My Ministry' background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for.");
                    return(false);
                }

                string password = Encryption.DecryptString(GetAttributeValue("Password"));

                XElement rootElement = new XElement("OrderXML",
                                                    new XElement("Method", "SEND ORDER"),
                                                    new XElement("Authentication",
                                                                 new XElement("Username", GetAttributeValue("UserName")),
                                                                 new XElement("Password", password)
                                                                 )
                                                    );

                rootElement.Add(new XElement("ReturnResultURL", GetAttributeValue("ReturnURL")));

                XElement orderElement = new XElement("Order");
                rootElement.Add(orderElement);

                if (billingCodeAttribute != null)
                {
                    string billingCode = workflow.GetAttributeValue(billingCodeAttribute.Key);
                    Guid?  campusGuid  = billingCode.AsGuidOrNull();
                    if (campusGuid.HasValue)
                    {
                        var campus = CampusCache.Get(campusGuid.Value);
                        if (campus != null)
                        {
                            billingCode = campus.Name;
                        }
                    }
                    orderElement.Add(new XElement("BillingReferenceCode", billingCode));
                }

                XElement subjectElement = new XElement("Subject",
                                                       new XElement("FirstName", person.FirstName),
                                                       new XElement("MiddleName", person.MiddleName),
                                                       new XElement("LastName", person.LastName)
                                                       );
                orderElement.Add(subjectElement);

                if (person.SuffixValue != null)
                {
                    subjectElement.Add(new XElement("Generation", person.SuffixValue.Value));
                }
                if (person.BirthDate.HasValue)
                {
                    subjectElement.Add(new XElement("DOB", person.BirthDate.Value.ToString("MM/dd/yyyy")));
                }

                if (ssnAttribute != null)
                {
                    string ssn = Field.Types.SSNFieldType.UnencryptAndClean(workflow.GetAttributeValue(ssnAttribute.Key));
                    if (!string.IsNullOrWhiteSpace(ssn) && ssn.Length == 9)
                    {
                        subjectElement.Add(new XElement("SSN", ssn.Insert(5, "-").Insert(3, "-")));
                    }
                }

                if (person.Gender == Gender.Male)
                {
                    subjectElement.Add(new XElement("Gender", "Male"));
                }
                if (person.Gender == Gender.Female)
                {
                    subjectElement.Add(new XElement("Gender", "Female"));
                }

                string dlNumber = person.GetAttributeValue("com.sparkdevnetwork.DLNumber");
                if (!string.IsNullOrWhiteSpace(dlNumber))
                {
                    subjectElement.Add(new XElement("DLNumber", dlNumber));
                }

                if (!string.IsNullOrWhiteSpace(person.Email))
                {
                    subjectElement.Add(new XElement("EmailAddress", person.Email));
                }

                var homelocation = person.GetHomeLocation();
                if (homelocation != null)
                {
                    subjectElement.Add(new XElement("CurrentAddress",
                                                    new XElement("StreetAddress", homelocation.Street1),
                                                    new XElement("City", homelocation.City),
                                                    new XElement("State", homelocation.State),
                                                    new XElement("Zipcode", homelocation.PostalCode)
                                                    ));
                }

                XElement aliasesElement = new XElement("Aliases");
                if (person.NickName != person.FirstName)
                {
                    aliasesElement.Add(new XElement("Alias", new XElement("FirstName", person.NickName)));
                }

                foreach (var previousName in person.GetPreviousNames())
                {
                    aliasesElement.Add(new XElement("Alias", new XElement("LastName", previousName.LastName)));
                }

                if (aliasesElement.HasElements)
                {
                    subjectElement.Add(aliasesElement);
                }

                DefinedValueCache pkgTypeDefinedValue = null;
                string            packageName         = "BASIC";
                string            county          = string.Empty;
                string            state           = string.Empty;
                string            mvrJurisdiction = string.Empty;
                string            mvrState        = string.Empty;

                if (requestTypeAttribute != null)
                {
                    pkgTypeDefinedValue = DefinedValueCache.Get(workflow.GetAttributeValue(requestTypeAttribute.Key).AsGuid());
                    if (pkgTypeDefinedValue != null)
                    {
                        if (pkgTypeDefinedValue.Attributes == null)
                        {
                            // shouldn't happen since pkgTypeDefinedValue is a ModelCache<,> type
                            return(false);
                        }

                        packageName = pkgTypeDefinedValue.GetAttributeValue("PMMPackageName");
                        county      = pkgTypeDefinedValue.GetAttributeValue("DefaultCounty");
                        state       = pkgTypeDefinedValue.GetAttributeValue("DefaultState");
                        Guid?mvrJurisdictionGuid = pkgTypeDefinedValue.GetAttributeValue("MVRJurisdiction").AsGuidOrNull();
                        if (mvrJurisdictionGuid.HasValue)
                        {
                            var mvrJurisdictionDv = DefinedValueCache.Get(mvrJurisdictionGuid.Value);
                            if (mvrJurisdictionDv != null)
                            {
                                mvrJurisdiction = mvrJurisdictionDv.Value;
                                if (mvrJurisdiction.Length >= 2)
                                {
                                    mvrState = mvrJurisdiction.Left(2);
                                }
                            }
                        }

                        if (homelocation != null)
                        {
                            if (!string.IsNullOrWhiteSpace(homelocation.County) &&
                                pkgTypeDefinedValue.GetAttributeValue("SendHomeCounty").AsBoolean())
                            {
                                county = homelocation.County;
                            }

                            if (!string.IsNullOrWhiteSpace(homelocation.State))
                            {
                                if (pkgTypeDefinedValue.GetAttributeValue("SendHomeState").AsBoolean())
                                {
                                    state = homelocation.State;
                                }
                                if (pkgTypeDefinedValue.GetAttributeValue("SendHomeStateMVR").AsBoolean())
                                {
                                    mvrState = homelocation.State;
                                }
                            }
                        }
                    }
                }

                if (!string.IsNullOrWhiteSpace(packageName))
                {
                    orderElement.Add(new XElement("PackageServiceCode", packageName,
                                                  new XAttribute("OrderId", workflow.Id.ToString())));

                    // Added PLUS MVR to assist NP with their need. This should be moved to a configuration
                    // in the future.
                    if (packageName.Trim().Equals("BASIC", StringComparison.OrdinalIgnoreCase) ||
                        packageName.Trim().Equals("PLUS", StringComparison.OrdinalIgnoreCase) ||
                        packageName.Trim().Equals("PLUS MVR", StringComparison.OrdinalIgnoreCase))
                    {
                        orderElement.Add(new XElement("OrderDetail",
                                                      new XAttribute("OrderId", workflow.Id.ToString()),
                                                      new XAttribute("ServiceCode", "combo")));
                    }
                }

                if (!string.IsNullOrWhiteSpace(county) ||
                    !string.IsNullOrWhiteSpace(state))
                {
                    orderElement.Add(new XElement("OrderDetail",
                                                  new XAttribute("OrderId", workflow.Id.ToString()),
                                                  new XAttribute("ServiceCode", string.IsNullOrWhiteSpace(county) ? "StateCriminal" : "CountyCrim"),
                                                  new XElement("County", county),
                                                  new XElement("State", state),
                                                  new XElement("YearsToSearch", 7),
                                                  new XElement("CourtDocsRequested", "NO"),
                                                  new XElement("RushRequested", "NO"),
                                                  new XElement("SpecialInstructions", ""))
                                     );
                }

                if (!string.IsNullOrWhiteSpace(mvrJurisdiction) && !string.IsNullOrWhiteSpace(mvrState))
                {
                    orderElement.Add(new XElement("OrderDetail",
                                                  new XAttribute("OrderId", workflow.Id.ToString()),
                                                  new XAttribute("ServiceCode", "MVR"),
                                                  new XElement("JurisdictionCode", mvrJurisdiction),
                                                  new XElement("State", mvrState))
                                     );
                }

                XDocument xdoc            = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), rootElement);
                var       requestDateTime = RockDateTime.Now;

                XDocument xResult          = PostToWebService(xdoc, GetAttributeValue("RequestURL"));
                var       responseDateTime = RockDateTime.Now;

                int?personAliasId = person.PrimaryAliasId;
                if (personAliasId.HasValue)
                {
                    // Create a background check file
                    using (var newRockContext = new RockContext())
                    {
                        var backgroundCheckService = new BackgroundCheckService(newRockContext);
                        var backgroundCheck        = backgroundCheckService.Queryable()
                                                     .Where(c =>
                                                            c.WorkflowId.HasValue &&
                                                            c.WorkflowId.Value == workflow.Id)
                                                     .FirstOrDefault();

                        if (backgroundCheck == null)
                        {
                            backgroundCheck = new Rock.Model.BackgroundCheck();
                            backgroundCheck.PersonAliasId = personAliasId.Value;
                            backgroundCheck.WorkflowId    = workflow.Id;
                            backgroundCheck.ForeignId     = 1;
                            backgroundCheckService.Add(backgroundCheck);
                        }

                        backgroundCheck.RequestDate = RockDateTime.Now;

                        // Clear any SSN nodes before saving XML to record
                        foreach (var xSSNElement in xdoc.Descendants("SSN"))
                        {
                            xSSNElement.Value = "XXX-XX-XXXX";
                        }
                        foreach (var xSSNElement in xResult.Descendants("SSN"))
                        {
                            xSSNElement.Value = "XXX-XX-XXXX";
                        }

                        backgroundCheck.ResponseData = string.Format(@"
Request XML ({0}): 
------------------------ 
{1}

Response XML ({2}): 
------------------------ 
{3}

", requestDateTime, xdoc.ToString(), responseDateTime, xResult.ToString());
                        newRockContext.SaveChanges();
                    }
                }

                using (var newRockContext = new RockContext())
                {
                    var handledErrorMessages = new List <string>();

                    if (_httpStatusCode == HttpStatusCode.OK)
                    {
                        var xOrderXML = xResult.Elements("OrderXML").FirstOrDefault();
                        if (xOrderXML != null)
                        {
                            var xStatus = xOrderXML.Elements("Status").FirstOrDefault();
                            if (xStatus != null)
                            {
                                if (SaveAttributeValue(workflow, "RequestStatus", xStatus.Value,
                                                       FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null))
                                {
                                }
                            }

                            handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList());
                            var xErrors = xOrderXML.Elements("Errors").FirstOrDefault();
                            if (xErrors != null)
                            {
                                handledErrorMessages.AddRange(xOrderXML.Elements("Message").Select(x => x.Value).ToList());
                            }

                            if (xResult.Root.Descendants().Count() > 0)
                            {
                                SaveResults(xResult, workflow, rockContext, false);
                            }
                        }
                    }
                    else
                    {
                        handledErrorMessages.Add("Invalid HttpStatusCode: " + _httpStatusCode.ToString());
                    }

                    if (handledErrorMessages.Any())
                    {
                        if (SaveAttributeValue(workflow, "RequestMessage", handledErrorMessages.AsDelimited(Environment.NewLine),
                                               FieldTypeCache.Get(Rock.SystemGuid.FieldType.TEXT.AsGuid()), newRockContext, null))
                        {
                        }
                    }

                    newRockContext.SaveChanges();

                    return(true);
                }
            }

            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, null);
                errorMessages.Add(ex.Message);
                return(false);
            }
        }
        /// <summary>
        /// Handles the filter display for each saved user value
        /// </summary>
        protected void rFilter_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e)
        {
            switch (e.Key)
            {
            case "Start Date":
            case "End Date":
                var dateTime = e.Value.AsDateTime();
                if (dateTime.HasValue)
                {
                    e.Value = dateTime.Value.ToShortDateString();
                }
                else
                {
                    e.Value = null;
                }

                return;

            case "First Name":
                return;

            case "Last Name":
                return;

            case "Campus":
            {
                int?campusId = e.Value.AsIntegerOrNull();
                if (campusId.HasValue)
                {
                    e.Value = CampusCache.Get(campusId.Value).Name;
                }

                return;
            }

            case "Government ID":
                return;

            case "Case Worker":
                int?personAliasId = e.Value.AsIntegerOrNull();
                if (personAliasId.HasValue)
                {
                    var personAlias = new PersonAliasService(new RockContext()).Get(personAliasId.Value);
                    if (personAlias != null)
                    {
                        e.Value = personAlias.Person.FullName;
                    }
                }

                return;

            case "Result":
            case "Status":
                var definedValueId = e.Value.AsIntegerOrNull();
                if (definedValueId.HasValue)
                {
                    var definedValue = DefinedValueCache.Get(definedValueId.Value);
                    if (definedValue != null)
                    {
                        e.Value = definedValue.Value;
                    }
                }

                return;

            case "Benevolence Types":
                var benevolencTypeValueIds = e.Value.SplitDelimitedValues().Select(v => v.ToIntSafe())?.ToList();
                if (benevolencTypeValueIds?.Count() > 0)
                {
                    var benevolenceTypes = new BenevolenceTypeService(new RockContext()).GetByIds(benevolencTypeValueIds);
                    if (benevolenceTypes != null)
                    {
                        e.Value = benevolenceTypes.Select(v => v.Name).ToList().AsDelimited(", ");
                    }
                }

                return;

            default:
                e.Value = string.Empty;
                return;
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Handles the DisplayFilterValue event of the gfBatchFilter control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.GridFilter.DisplayFilterValueArgs"/> instance containing the event data.</param>
        protected void gfBatchFilter_DisplayFilterValue(object sender, Rock.Web.UI.Controls.GridFilter.DisplayFilterValueArgs e)
        {
            if (AvailableAttributes != null)
            {
                var attribute = AvailableAttributes.FirstOrDefault(a => "Attribute_" + a.Key == e.Key);
                if (attribute != null)
                {
                    try
                    {
                        var values = JsonConvert.DeserializeObject <List <string> >(e.Value);
                        e.Value = attribute.FieldType.Field.FormatFilterValues(attribute.QualifierValues, values);
                        return;
                    }
                    catch
                    {
                        // intentionally ignore
                    }
                }
            }

            switch (e.Key)
            {
            case "Row Limit":
            {
                // row limit filter was removed, so hide it just in case
                e.Value = null;
                break;
            }

            case "Date Range":
            {
                e.Value = DateRangePicker.FormatDelimitedValues(e.Value);
                break;
            }

            case "Status":
            {
                var status = e.Value.ConvertToEnumOrNull <BatchStatus>();
                if (status.HasValue)
                {
                    e.Value = status.ConvertToString();
                }
                else
                {
                    e.Value = string.Empty;
                }

                break;
            }

            case "Contains Transaction Type":
            {
                var transactionTypeValueId = e.Value.AsIntegerOrNull();
                if (transactionTypeValueId.HasValue)
                {
                    var transactionTypeValue = DefinedValueCache.Get(transactionTypeValueId.Value);
                    e.Value = transactionTypeValue != null?transactionTypeValue.ToString() : string.Empty;
                }
                else
                {
                    e.Value = string.Empty;
                }

                break;
            }

            case "Campus":
            {
                var campus = CampusCache.Get(e.Value.AsInteger());
                if (campus != null)
                {
                    e.Value = campus.Name;
                }
                else
                {
                    e.Value = string.Empty;
                }

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

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

            var families = person.GetFamilies();

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

            //Evaluate PhoneNumbers
            var  phoneNumberTypeIds = new List <int>();
            bool smsSelected        = false;

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

                if (hfPhoneType != null &&
                    pnbPhone != null &&
                    cbSms != null &&
                    cbUnlisted != null)
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var    phoneNumber    = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                        string oldPhoneNumber = string.Empty;
                        if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                        {
                            phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                            changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNullOrWhiteSpace())   // delete number
                        {
                            var phoneComment = string.Format("{0}: {1}.", phoneNumber.NumberTypeValue.Value, phoneNumber.NumberFormatted);
                            changeRequest.DeleteEntity(phoneNumber, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                        {
                            changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                        }

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

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


            var birthday = bpBirthday.SelectedDate;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);

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

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

            bool autoApply = CanAutoApply(person);


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

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

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

            if (autoApply)
            {
                NavigateToPerson();
            }
            else
            {
                pnlMain.Visible     = false;
                pnlNoPerson.Visible = false;
                pnlDone.Visible     = true;
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Gets the query.  Set the timeout to 90 seconds in case the user
        /// has not set any filters and they've imported N years worth of
        /// batch data into Rock.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private IOrderedQueryable <FinancialBatch> GetQuery(RockContext rockContext)
        {
            var batchService = new FinancialBatchService(rockContext);

            rockContext.Database.CommandTimeout = 90;
            var qry = batchService.Queryable()
                      .Where(b => b.BatchStartDateTime.HasValue);

            // filter by date
            string dateRangeValue = gfBatchFilter.GetUserPreference("Date Range");

            if (!string.IsNullOrWhiteSpace(dateRangeValue))
            {
                var drp = new DateRangePicker();
                drp.DelimitedValues = dateRangeValue;
                if (drp.LowerValue.HasValue)
                {
                    qry = qry.Where(b => b.BatchStartDateTime >= drp.LowerValue.Value);
                }

                if (drp.UpperValue.HasValue)
                {
                    var endOfDay = drp.UpperValue.Value.AddDays(1);
                    qry = qry.Where(b => b.BatchStartDateTime < endOfDay);
                }
            }

            // filter by status
            var status = gfBatchFilter.GetUserPreference("Status").ConvertToEnumOrNull <BatchStatus>();

            if (status.HasValue)
            {
                qry = qry.Where(b => b.Status == status);
            }

            // filter by batches that contain transactions of the specified transaction type
            var transactionTypeValueId = gfBatchFilter.GetUserPreference("Contains Transaction Type").AsIntegerOrNull();

            if (transactionTypeValueId.HasValue)
            {
                qry = qry.Where(a => a.Transactions.Any(t => t.TransactionTypeValueId == transactionTypeValueId.Value));
            }

            // filter by title
            string title = gfBatchFilter.GetUserPreference("Title");

            if (!string.IsNullOrEmpty(title))
            {
                qry = qry.Where(batch => batch.Name.Contains(title));
            }

            // filter by accounting code
            if (tbAccountingCode.Visible)
            {
                string accountingCode = gfBatchFilter.GetUserPreference("Accounting Code");
                if (!string.IsNullOrEmpty(accountingCode))
                {
                    qry = qry.Where(batch => batch.AccountingSystemCode.Contains(accountingCode));
                }
            }

            // filter by campus
            var campus = CampusCache.Get(gfBatchFilter.GetUserPreference("Campus").AsInteger());

            if (campus != null)
            {
                qry = qry.Where(b => b.CampusId == campus.Id);
            }

            // Filter query by any configured attribute filters
            if (AvailableAttributes != null && AvailableAttributes.Any())
            {
                foreach (var attribute in AvailableAttributes)
                {
                    var filterControl = phAttributeFilters.FindControl("filter_" + attribute.Id.ToString());
                    qry = attribute.FieldType.Field.ApplyAttributeQueryFilter(qry, filterControl, attribute, batchService, Rock.Reporting.FilterMode.SimpleFilter);
                }
            }

            IOrderedQueryable <FinancialBatch> sortedQry = null;

            SortProperty sortProperty = gBatchList.SortProperty;

            if (sortProperty != null)
            {
                switch (sortProperty.Property)
                {
                case "TransactionCount":
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        sortedQry = qry.OrderBy(b => b.Transactions.Count());
                    }
                    else
                    {
                        sortedQry = qry.OrderByDescending(b => b.Transactions.Count());
                    }

                    break;
                }

                case "TransactionAmount":
                {
                    if (sortProperty.Direction == SortDirection.Ascending)
                    {
                        sortedQry = qry.OrderBy(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M);
                    }
                    else
                    {
                        sortedQry = qry.OrderByDescending(b => b.Transactions.Sum(t => (decimal?)(t.TransactionDetails.Sum(d => (decimal?)d.Amount) ?? 0.0M)) ?? 0.0M);
                    }

                    break;
                }

                default:
                {
                    sortedQry = qry.Sort(sortProperty);
                    break;
                }
                }
            }
            else
            {
                sortedQry = qry
                            .OrderByDescending(b => b.BatchStartDateTime)
                            .ThenBy(b => b.Name);
            }

            return(sortedQry);
        }
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            var            rockContext  = new RockContext();
            var            batchService = new FinancialBatchService(rockContext);
            FinancialBatch batch        = null;

            var changes = new History.HistoryChangeList();

            int batchId = hfBatchId.Value.AsInteger();

            if (batchId == 0)
            {
                batch = new FinancialBatch();
                batchService.Add(batch);
                changes.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Batch");
            }
            else
            {
                batch = batchService.Get(batchId);
            }

            if (batch != null)
            {
                if (dvpBatchName.Visible)
                {
                    History.EvaluateChange(changes, "Batch Name", batch.Name, dvpBatchName.SelectedItem.Text);
                    batch.Name = dvpBatchName.SelectedItem.Text;
                }
                else
                {
                    History.EvaluateChange(changes, "Batch Name", batch.Name, tbName.Text);
                    batch.Name = tbName.Text;
                }

                BatchStatus batchStatus = (BatchStatus)ddlStatus.SelectedIndex;

                string errorMessage;
                if (!batch.IsValidBatchStatusChange(batch.Status, batchStatus, this.CurrentPerson, out errorMessage))
                {
                    cvBatch.IsValid      = false;
                    cvBatch.ErrorMessage = errorMessage;
                    return;
                }

                History.EvaluateChange(changes, "Status", batch.Status, batchStatus);
                batch.Status = batchStatus;

                CampusCache oldCampus = null;
                if (batch.CampusId.HasValue)
                {
                    oldCampus = CampusCache.Get(batch.CampusId.Value);
                }

                CampusCache newCampus = null;
                if (campCampus.SelectedCampusId.HasValue)
                {
                    newCampus = CampusCache.Get(campCampus.SelectedCampusId.Value);
                }

                History.EvaluateChange(changes, "Campus", oldCampus != null ? oldCampus.Name : "None", newCampus != null ? newCampus.Name : "None");
                batch.CampusId = campCampus.SelectedCampusId;

                DateTime?startDateTime = dtpStart.SelectedDateTimeIsBlank ? null : dtpStart.SelectedDateTime;
                History.EvaluateChange(changes, "Start Date/Time", batch.BatchStartDateTime, startDateTime);
                batch.BatchStartDateTime = startDateTime;

                DateTime?endDateTime;
                if (dtpEnd.SelectedDateTimeIsBlank && batch.BatchStartDateTime.HasValue)
                {
                    endDateTime = batch.BatchStartDateTime.Value.AddDays(1);
                }
                else
                {
                    endDateTime = dtpEnd.SelectedDateTimeIsBlank ? null : dtpEnd.SelectedDateTime;
                }

                History.EvaluateChange(changes, "End Date/Time", batch.BatchEndDateTime, endDateTime);
                batch.BatchEndDateTime = endDateTime;

                decimal controlAmount = tbControlAmount.Text.AsDecimal();
                History.EvaluateChange(changes, "Control Amount", batch.ControlAmount.FormatAsCurrency(), controlAmount.FormatAsCurrency());
                batch.ControlAmount = controlAmount;

                int?controlItemCount = nbControlItemCount.Text.AsIntegerOrNull();
                History.EvaluateChange(changes, "Control Item Count", batch.ControlItemCount.FormatAsCurrency(), controlItemCount.FormatAsCurrency());
                batch.ControlItemCount = controlItemCount;

                History.EvaluateChange(changes, "Accounting System Code", batch.AccountingSystemCode, tbAccountingCode.Text);
                batch.AccountingSystemCode = tbAccountingCode.Text;

                History.EvaluateChange(changes, "Notes", batch.Note, tbNote.Text);
                batch.Note = tbNote.Text;

                cvBatch.IsValid = batch.IsValid;
                if (!Page.IsValid || !batch.IsValid)
                {
                    cvBatch.ErrorMessage = batch.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                    return;
                }

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

                rockContext.WrapTransaction(() =>
                {
                    if (rockContext.SaveChanges() > 0)
                    {
                        if (changes.Any())
                        {
                            pdAuditDetails.SetEntity(batch, ResolveRockUrl("~"));
                            HistoryService.SaveChanges(
                                rockContext,
                                typeof(FinancialBatch),
                                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                                batch.Id,
                                changes);
                        }
                    }
                });

                batch.SaveAttributeValues(rockContext);

                if (batchId == 0)
                {
                    // If created a new batch, navigate to same page so that transaction list displays correctly
                    var pageReference = CurrentPageReference;
                    pageReference.Parameters.AddOrReplace("batchId", batch.Id.ToString());
                    NavigateToPage(pageReference);
                }
                else
                {
                    hfBatchId.SetValue(batch.Id);

                    // Requery the batch to support EF navigation properties
                    var savedBatch = GetBatch(batch.Id);
                    ShowReadonlyDetails(savedBatch);

                    // If there is a batch context item, update the context's properties with new values
                    var contextObjects = new Dictionary <string, object>();
                    foreach (var contextEntityType in RockPage.GetContextEntityTypes())
                    {
                        var contextEntity = RockPage.GetCurrentContext(contextEntityType);
                        if (contextEntity is FinancialBatch)
                        {
                            var contextBatch = contextEntity as FinancialBatch;
                            contextBatch.CopyPropertiesFrom(batch);
                        }
                    }

                    // Then refresh transaction list
                    RockPage.UpdateBlocks("~/Blocks/Finance/TransactionList.ascx");
                }
            }
        }
        /// <summary>
        /// Method to save attendance for use in two separate areas.
        /// </summary>
        protected bool SaveAttendance()
        {
            using (var rockContext = new RockContext())
            {
                var occurrenceService  = new AttendanceOccurrenceService(rockContext);
                var attendanceService  = new AttendanceService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var locationService    = new LocationService(rockContext);

                AttendanceOccurrence occurrence = null;

                if (_occurrence.Id != 0)
                {
                    occurrence = occurrenceService.Get(_occurrence.Id);
                }

                if (occurrence == null)
                {
                    var existingOccurrence = occurrenceService.Get(_occurrence.OccurrenceDate, _group.Id, _occurrence.LocationId, _occurrence.ScheduleId);
                    if (existingOccurrence != null)
                    {
                        nbNotice.Heading             = "Occurrence Already Exists";
                        nbNotice.Text                = "<p>An occurrence already exists for this group for the selected date, location, and schedule that you've selected. Please return to the list and select that occurrence to update it's attendance.</p>";
                        nbNotice.NotificationBoxType = NotificationBoxType.Danger;
                        nbNotice.Visible             = true;

                        return(false);
                    }
                    else
                    {
                        occurrence                = new AttendanceOccurrence();
                        occurrence.GroupId        = _occurrence.GroupId;
                        occurrence.LocationId     = _occurrence.LocationId;
                        occurrence.ScheduleId     = _occurrence.ScheduleId;
                        occurrence.OccurrenceDate = _occurrence.OccurrenceDate;
                        occurrenceService.Add(occurrence);
                    }
                }

                occurrence.Notes       = GetAttributeValue("ShowNotes").AsBoolean() ? dtNotes.Text : string.Empty;
                occurrence.DidNotOccur = cbDidNotMeet.Checked;

                var existingAttendees = occurrence.Attendees.ToList();

                // If did not meet was selected and this was a manually entered occurrence (not based on a schedule/location)
                // then just delete all the attendance records instead of tracking a 'did not meet' value
                if (cbDidNotMeet.Checked && !_occurrence.ScheduleId.HasValue)
                {
                    foreach (var attendance in existingAttendees)
                    {
                        attendanceService.Delete(attendance);
                    }
                }
                else
                {
                    int?campusId = locationService.GetCampusIdForLocation(_occurrence.LocationId) ?? _group.CampusId;
                    if (!campusId.HasValue && _allowCampusFilter)
                    {
                        var campus = CampusCache.Get(bddlCampus.SelectedValueAsInt() ?? 0);
                        if (campus != null)
                        {
                            campusId = campus.Id;
                        }
                    }

                    if (cbDidNotMeet.Checked)
                    {
                        // If the occurrence is based on a schedule, set the did not meet flags
                        foreach (var attendance in existingAttendees)
                        {
                            attendance.DidAttend = null;
                        }
                    }
                    else
                    {
                        foreach (var attendee in _attendees)
                        {
                            var attendance = existingAttendees
                                             .Where(a => a.PersonAlias.PersonId == attendee.PersonId)
                                             .FirstOrDefault();

                            if (attendance == null)
                            {
                                int?personAliasId = personAliasService.GetPrimaryAliasId(attendee.PersonId);
                                if (personAliasId.HasValue)
                                {
                                    attendance = new Attendance();
                                    attendance.PersonAliasId = personAliasId;
                                    attendance.CampusId      = campusId;
                                    attendance.StartDateTime = _occurrence.OccurrenceDate;

                                    // check that the attendance record is valid
                                    cvAttendance.IsValid = attendance.IsValid;
                                    if (!cvAttendance.IsValid)
                                    {
                                        cvAttendance.ErrorMessage = attendance.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                                        return(false);
                                    }

                                    occurrence.Attendees.Add(attendance);
                                }
                            }

                            if (attendance != null)
                            {
                                attendance.DidAttend = attendee.Attended;
                            }
                        }
                    }
                }

                rockContext.SaveChanges();

                if (occurrence.LocationId.HasValue)
                {
                    Rock.CheckIn.KioskLocationAttendance.Remove(occurrence.LocationId.Value);
                }


                Guid?workflowTypeGuid = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    var workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);
                    if (workflowType != null && (workflowType.IsActive ?? true))
                    {
                        try
                        {
                            var workflow = Workflow.Activate(workflowType, _group.Name);

                            workflow.SetAttributeValue("StartDateTime", _occurrence.OccurrenceDate.ToString("o"));
                            workflow.SetAttributeValue("Schedule", _group.Schedule.Guid.ToString());

                            List <string> workflowErrors;
                            new WorkflowService(rockContext).Process(workflow, _group, out workflowErrors);
                        }
                        catch (Exception ex)
                        {
                            ExceptionLogService.LogException(ex, this.Context);
                        }
                    }
                }
            }

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

            // Get the person
            PersonAlias personAlias     = null;
            Guid        personAliasGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "PersonAttribute").AsGuid()).AsGuid();

            personAlias = new PersonAliasService(rockContext).Get(personAliasGuid);
            if (personAlias == null)
            {
                errorMessages.Add("Invalid Person Attribute or Value!");
                return(false);
            }

            // Get the opportunity
            ConnectionOpportunity opportunity = null;
            Guid opportunityTypeGuid          = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionOpportunityAttribute").AsGuid()).AsGuid();

            opportunity = new ConnectionOpportunityService(rockContext).Get(opportunityTypeGuid);
            if (opportunity == null)
            {
                errorMessages.Add("Invalid Connection Opportunity Attribute or Value!");
                return(false);
            }

            // Get connection status
            ConnectionStatus status = null;
            Guid?            connectionStatusGuid          = null;
            Guid?            connectionStatusAttributeGuid = GetAttributeValue(action, "ConnectionStatusAttribute").AsGuidOrNull();

            if (connectionStatusAttributeGuid.HasValue)
            {
                connectionStatusGuid = action.GetWorklowAttributeValue(connectionStatusAttributeGuid.Value).AsGuidOrNull();
                if (connectionStatusGuid.HasValue)
                {
                    status = opportunity.ConnectionType.ConnectionStatuses
                             .Where(s => s.Guid.Equals(connectionStatusGuid.Value))
                             .FirstOrDefault();
                }
            }
            if (status == null)
            {
                connectionStatusGuid = GetAttributeValue(action, "ConnectionStatus").AsGuidOrNull();
                if (connectionStatusGuid.HasValue)
                {
                    status = opportunity.ConnectionType.ConnectionStatuses
                             .Where(s => s.Guid.Equals(connectionStatusGuid.Value))
                             .FirstOrDefault();
                }
            }
            if (status == null)
            {
                status = opportunity.ConnectionType.ConnectionStatuses
                         .Where(s => s.IsDefault)
                         .FirstOrDefault();
            }

            // Get Campus
            int? campusId            = null;
            Guid?campusAttributeGuid = GetAttributeValue(action, "CampusAttribute").AsGuidOrNull();

            if (campusAttributeGuid.HasValue)
            {
                Guid?campusGuid = action.GetWorklowAttributeValue(campusAttributeGuid.Value).AsGuidOrNull();
                if (campusGuid.HasValue)
                {
                    var campus = CampusCache.Get(campusGuid.Value);
                    if (campus != null)
                    {
                        campusId = campus.Id;
                    }
                }
            }

            // Get the Comment
            String comment = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionCommentAttribute").AsGuid());

            var connectionRequestService = new ConnectionRequestService(rockContext);

            var connectionRequest = new ConnectionRequest();

            connectionRequest.PersonAliasId           = personAlias.Id;
            connectionRequest.ConnectionOpportunityId = opportunity.Id;
            connectionRequest.ConnectionState         = ConnectionState.Active;
            connectionRequest.ConnectionStatusId      = status.Id;
            connectionRequest.CampusId = campusId;
            connectionRequest.ConnectorPersonAliasId = opportunity.GetDefaultConnectorPersonAliasId(campusId);
            connectionRequest.Comments = comment;

            connectionRequestService.Add(connectionRequest);
            rockContext.SaveChanges();

            // If request attribute was specified, requery the request and set the attribute's value
            Guid?connectionRequestAttributeGuid = GetAttributeValue(action, "ConnectionRequestAttribute").AsGuidOrNull();

            if (connectionRequestAttributeGuid.HasValue)
            {
                connectionRequest = connectionRequestService.Get(connectionRequest.Id);
                if (connectionRequest != null)
                {
                    SetWorkflowAttributeValue(action, connectionRequestAttributeGuid.Value, connectionRequest.Guid.ToString());
                }
            }

            return(true);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Saves the group.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns>The response to send back to the client.</returns>
        private CallbackResponse SaveGroup(Dictionary <string, object> parameters)
        {
            using (var rockContext = new RockContext())
            {
                var groupGuid = RequestContext.GetPageParameter(PageParameterKeys.GroupGuid).AsGuid();
                var group     = new GroupService(rockContext).Get(groupGuid);

                if (group == null || !group.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson))
                {
                    return(new CallbackResponse
                    {
                        Error = "You are not authorized to edit this group."
                    });
                }

                group.LoadAttributes(rockContext);

                //
                // Verify and save all the property values.
                //
                if (ShowGroupName && EnableGroupNameEdit)
                {
                    group.Name = ( string )parameters["name"];
                }

                if (ShowDescription && EnableDescriptionEdit)
                {
                    group.Description = ( string )parameters["description"];
                }

                if (ShowCampus && EnableCampusEdit)
                {
                    group.CampusId = CampusCache.Get((( string )parameters["campus"]).AsGuid())?.Id;
                }

                if (ShowGroupCapacity && EnableGroupCapacityEdit && group.GroupType.GroupCapacityRule != GroupCapacityRule.None)
                {
                    group.GroupCapacity = (( string )parameters["capacity"]).AsIntegerOrNull();
                }

                if (ShowActiveStatus && EnableActiveStatusEdit)
                {
                    group.IsActive = ( bool )parameters["active"];
                }

                if (ShowPublicStatus && EnablePublicStatusEdit)
                {
                    group.IsPublic = ( bool )parameters["public"];
                }

                //
                // Save all the attribute values.
                //
                MobileHelper.UpdateEditAttributeValues(group, parameters, GetEditableAttributes(group));

                //
                // Save all changes to database.
                //
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();
                    group.SaveAttributeValues(rockContext);
                });
            }

            if (GroupDetailPage.HasValue)
            {
                return(new CallbackResponse
                {
                    Command = "ReplacePage",
                    CommandParameter = $"{GroupDetailPage}?GroupGuid={RequestContext.GetPageParameter( PageParameterKeys.GroupGuid )}"
                });
            }
            else
            {
                return(new CallbackResponse
                {
                    Command = "PopPage",
                    CommandParameter = "true"
                });
            }
        }