Ejemplo n.º 1
0
        /// <summary>
        /// Show the details for the given person.
        /// </summary>
        /// <param name="personGuid"></param>
        private void ShowDetail(Guid personGuid)
        {
            btnReprintLabels.Visible = GetAttributeValue(AttributeKey.AllowLabelReprinting).AsBoolean();

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

                var person = personService.Queryable("PhoneNumbers.NumberTypeValue,RecordTypeValue", true, true)
                             .FirstOrDefault(a => a.Guid == personGuid);

                if (person == null)
                {
                    return;
                }

                lName.Text = person.FullName;

                string photoTag = Rock.Model.Person.GetPersonPhotoImageTag(person, 200, 200);
                if (person.PhotoId.HasValue)
                {
                    lPhoto.Text = string.Format("<div class='photo'><a href='{0}'>{1}</a></div>", person.PhotoUrl, photoTag);
                }
                else
                {
                    lPhoto.Text = photoTag;
                }

                var campus = person.GetCampus();
                if (campus != null)
                {
                    hlCampus.Visible = true;
                    hlCampus.Text    = campus.Name;
                }
                else
                {
                    hlCampus.Visible = false;
                }

                lGender.Text = person.Gender != Gender.Unknown ? person.Gender.ConvertToString() : "";

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

                lGrade.Text = person.GradeFormatted;

                lEmail.Visible = !string.IsNullOrWhiteSpace(person.Email);
                lEmail.Text    = person.GetEmailTag(ResolveRockUrl("/"), "btn btn-default", "<i class='fa fa-envelope'></i>");

                BindAttribute(person);
                // Text Message
                var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.IsMessagingEnabled && n.Number.IsNotNullOrWhiteSpace());
                if (GetAttributeValue(AttributeKey.SMSFrom).IsNotNullOrWhiteSpace() && phoneNumber != null)
                {
                    btnSms.Text          = string.Format("<i class='fa fa-mobile'></i> {0} <small>({1})</small>", phoneNumber.NumberFormatted, phoneNumber.NumberTypeValue);
                    btnSms.Visible       = true;
                    rcwTextMessage.Label = "Text Message";
                }
                else
                {
                    btnSms.Visible       = false;
                    rcwTextMessage.Label = string.Empty;
                }

                // Get all family member from all families ( including self )
                var allFamilyMembers = personService.GetFamilyMembers(person.Id, true).ToList();

                // Add flag for this person in each family indicating if they are a child in family.
                var childGuid     = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid();
                var isFamilyChild = new Dictionary <int, bool>();
                foreach (var thisPerson in allFamilyMembers.Where(m => m.PersonId == person.Id))
                {
                    isFamilyChild.Add(thisPerson.GroupId, thisPerson.GroupRole.Guid.Equals(childGuid));
                }

                // Get the current url's root (without the person's guid)
                string urlRoot = Request.Url.ToString().ReplaceCaseInsensitive(personGuid.ToString(), "");

                // Get the other family members and the info needed for rendering
                var familyMembers = allFamilyMembers.Where(m => m.PersonId != person.Id)
                                    .OrderBy(m => m.GroupId)
                                    .ThenBy(m => m.Person.BirthDate)
                                    .Select(m => new
                {
                    Url        = urlRoot + m.Person.Guid.ToString(),
                    FullName   = m.Person.FullName,
                    Gender     = m.Person.Gender,
                    FamilyRole = m.GroupRole,
                    Note       = isFamilyChild[m.GroupId] ?
                                 (m.GroupRole.Guid.Equals(childGuid) ? " (Sibling)" : "(Parent)") :
                                 (m.GroupRole.Guid.Equals(childGuid) ? " (Child)" : "")
                })
                                    .ToList();

                rcwFamily.Visible     = familyMembers.Any();
                rptrFamily.DataSource = familyMembers;
                rptrFamily.DataBind();

                rcwRelationships.Visible = false;
                if (GetAttributeValue(AttributeKey.ShowRelatedPeople).AsBoolean())
                {
                    var roles   = new List <int>();
                    var krRoles = new GroupTypeRoleService(rockContext)
                                  .Queryable().AsNoTracking()
                                  .Where(r => r.GroupType.Guid.Equals(new Guid(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS)))
                                  .ToList();

                    foreach (var role in krRoles)
                    {
                        role.LoadAttributes(rockContext);
                        if (role.GetAttributeValue("CanCheckin").AsBoolean() &&
                            role.Attributes.ContainsKey("InverseRelationship"))
                        {
                            var inverseRoleGuid = role.GetAttributeValue("InverseRelationship").AsGuidOrNull();
                            if (inverseRoleGuid.HasValue)
                            {
                                var inverseRole = krRoles.FirstOrDefault(r => r.Guid == inverseRoleGuid.Value);
                                if (inverseRole != null)
                                {
                                    roles.Add(inverseRole.Id);
                                }
                            }
                        }
                    }

                    if (roles.Any())
                    {
                        var relatedMembers = personService.GetRelatedPeople(new List <int> {
                            person.Id
                        }, roles)
                                             .OrderBy(m => m.Person.LastName)
                                             .ThenBy(m => m.Person.NickName)
                                             .Select(m => new
                        {
                            Url      = urlRoot + m.Person.Guid.ToString(),
                            FullName = m.Person.FullName,
                            Gender   = m.Person.Gender,
                            Note     = " (" + m.GroupRole.Name + ")"
                        })
                                             .ToList();

                        rcwRelationships.Visible     = relatedMembers.Any();
                        rptrRelationships.DataSource = relatedMembers;
                        rptrRelationships.DataBind();
                    }
                }

                var phoneNumbers = person.PhoneNumbers.Where(p => !p.IsUnlisted).ToList();
                rptrPhones.DataSource = phoneNumbers;
                rptrPhones.DataBind();
                rcwPhone.Visible = phoneNumbers.Any();

                var schedules = new ScheduleService(rockContext)
                                .Queryable().AsNoTracking()
                                .Where(s => s.CheckInStartOffsetMinutes.HasValue)
                                .ToList();

                var scheduleIds = schedules.Select(s => s.Id).ToList();

                int?personAliasId = person.PrimaryAliasId;

                PersonAliasService personAliasService = new PersonAliasService(rockContext);
                if (!personAliasId.HasValue)
                {
                    personAliasId = personAliasService.GetPrimaryAliasId(person.Id);
                }

                var attendances = new AttendanceService(rockContext)
                                  .Queryable("Occurrence.Schedule,Occurrence.Group,Occurrence.Location,AttendanceCode")
                                  .Where(a =>
                                         a.PersonAliasId.HasValue &&
                                         a.PersonAliasId == personAliasId &&
                                         a.Occurrence.ScheduleId.HasValue &&
                                         a.Occurrence.GroupId.HasValue &&
                                         a.Occurrence.LocationId.HasValue &&
                                         a.DidAttend.HasValue &&
                                         a.DidAttend.Value &&
                                         scheduleIds.Contains(a.Occurrence.ScheduleId.Value))
                                  .OrderByDescending(a => a.StartDateTime)
                                  .Take(20)
                                  .ToList()                                               // Run query to get recent most 20 checkins
                                  .OrderByDescending(a => a.Occurrence.OccurrenceDate)    // Then sort again by start datetime and schedule start (which is not avail to sql query )
                                  .ThenByDescending(a => a.Occurrence.Schedule.StartTimeOfDay)
                                  .ToList()
                                  .Select(a =>
                {
                    var checkedInByPerson = a.CheckedInByPersonAliasId.HasValue ? personAliasService.GetPerson(a.CheckedInByPersonAliasId.Value) : null;

                    return(new AttendanceInfo
                    {
                        Id = a.Id,
                        Date = a.StartDateTime,
                        GroupId = a.Occurrence.Group.Id,
                        Group = a.Occurrence.Group.Name,
                        LocationId = a.Occurrence.LocationId.Value,
                        Location = a.Occurrence.Location.Name,
                        Schedule = a.Occurrence.Schedule.Name,
                        IsActive = a.IsCurrentlyCheckedIn,
                        Code = a.AttendanceCode != null ? a.AttendanceCode.Code : "",
                        CheckInByPersonName = checkedInByPerson != null ? checkedInByPerson.FullName : string.Empty,
                        CheckInByPersonGuid = checkedInByPerson != null ? checkedInByPerson.Guid : ( Guid? )null
                    });
                }
                                          ).ToList();

                // Set active locations to be a link to the room in manager page
                var qryParam = new Dictionary <string, string>();
                qryParam.Add("Group", "");
                qryParam.Add("Location", "");
                foreach (var attendance in attendances.Where(a => a.IsActive))
                {
                    qryParam["Group"]    = attendance.GroupId.ToString();
                    qryParam["Location"] = attendance.LocationId.ToString();
                    attendance.Location  = string.Format("<a href='{0}'>{1}</a>",
                                                         LinkedPageUrl(AttributeKey.ManagerPage, qryParam), attendance.Location);
                }

                rcwCheckinHistory.Visible = attendances.Any();

                // Get the index of the delete column
                var deleteField = gHistory.Columns.OfType <Rock.Web.UI.Controls.DeleteField>().First();
                _deleteFieldIndex = gHistory.Columns.IndexOf(deleteField);

                gHistory.DataSource = attendances;
                gHistory.DataBind();
            }
        }
        private void BindGrid()
        {
            var changeId = hfChangeId.ValueAsInt();

            if (changeId == 0)
            {
                changeId = PageParameter("ChangeRequest").AsInteger();
                hfChangeId.SetValue(changeId);
            }
            RockContext          rockContext          = new RockContext();
            ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
            ChangeRequest        changeRequest        = changeRequestService.Get(changeId);

            if (changeRequest == null)
            {
                return;
            }

            if (!IsUserAuthorized(Rock.Security.Authorization.EDIT) &&
                (CurrentPerson == null || !CurrentPerson.Aliases.Select(a => a.Id).Contains(changeRequest.RequestorAliasId)))
            {
                this.Visible = false;
                return;
            }

            CheckForBlacklist(changeRequest);

            var link = "";

            if (changeRequest.EntityTypeId == EntityTypeCache.Get(typeof(PersonAlias)).Id)
            {
                PersonAliasService personAliasService = new PersonAliasService(rockContext);
                var personAlias = personAliasService.Get(changeRequest.EntityId);
                if (personAlias != null)
                {
                    link = string.Format("<a href='/Person/{0}' target='_blank' class='btn btn-default btn-sm'><i class='fa fa-user'></i></a>", personAlias.Person.Id);
                }
            }

            lName.Text = string.Format(@"
<h1 class='panel-title'>{0} {1}</h1>
<div class='panel-labels'>
    <span class='label label-default'>
        Requested by: <a href='/Person/{2}' target='_blank'>{3}</a>
    </span>
    <span class='label label-{4}'>
        {5}
    </span>
</div>",
                                       link,
                                       changeRequest.Name,
                                       changeRequest.RequestorAlias.PersonId,
                                       changeRequest.RequestorAlias.Person.FullName,
                                       changeRequest.IsComplete ? "primary" : "success",
                                       changeRequest.IsComplete ? "Complete" : "Active");

            var changeRecords = changeRequest.ChangeRecords.ToList();

            var errors = new List <string>();
            var entity = ChangeRequest.GetEntity(changeRequest.EntityTypeId, changeRequest.EntityId, rockContext, errors);

            foreach (var changeRecord in changeRecords)
            {
                FormatValues(changeRequest.EntityTypeId, entity, changeRecord, rockContext);
            }

            if (changeRecords.Any())
            {
                gRecords.DataSource = changeRecords;
                gRecords.DataBind();
            }
            else
            {
                gRecords.Visible = false;
            }

            if (changeRequest.RequestorComment.IsNotNullOrWhiteSpace())
            {
                ltRequestComments.Visible = true;
                ltRequestComments.Text    = changeRequest.RequestorComment;
            }

            ltApproverComment.Text = changeRequest.ApproverComment;
            tbApproverComment.Text = changeRequest.ApproverComment;

            if (!IsUserAuthorized(Rock.Security.Authorization.EDIT))
            {
                btnComplete.Visible       = false;
                tbApproverComment.Visible = false;
                ltApproverComment.Visible = true;
                (( DataControlField )gRecords.Columns
                 .Cast <DataControlField>()
                 .Where(fld => (fld.HeaderText == "Is Rejected"))
                 .SingleOrDefault()).Visible = false;
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Handles the Click event of the btnSaveGroup control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSaveGroup_Click(object sender, EventArgs e)
        {
            var          rockContext  = new RockContext();
            GroupService groupService = new GroupService(rockContext);

            Group group = groupService.Get(_groupId);

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

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

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

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

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

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

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

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

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

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

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

            this.IsEditingGroup = false;

            // reload the group info
            pnlGroupEdit.Visible = false;
            pnlGroupView.Visible = true;
            DisplayViewGroup();
        }
        private void ShowReadonlyDetails()
        {
            hfMode.Value = "View";

            if (Workflow != null)
            {
                if (Workflow.IsAuthorized(Authorization.VIEW, CurrentPerson))
                {
                    tdName.Description   = Workflow.Name;
                    tdStatus.Description = Workflow.Status;

                    if (Workflow.InitiatorPersonAlias != null && Workflow.InitiatorPersonAlias.Person != null)
                    {
                        var person = Workflow.InitiatorPersonAlias.Person;
                        tdInitiator.Description = string.Format("<a href='{0}{1}'>{2}</a>", ResolveRockUrl("~/Person/"), person.Id, person.FullName);
                    }
                    else
                    {
                        tdInitiator.Description = string.Empty;
                    }

                    if (Workflow.ActivatedDateTime.HasValue)
                    {
                        tdActivatedWhen.Description = string.Format("{0} {1} ({2})",
                                                                    Workflow.ActivatedDateTime.Value.ToShortDateString(),
                                                                    Workflow.ActivatedDateTime.Value.ToShortTimeString(),
                                                                    Workflow.ActivatedDateTime.Value.ToRelativeDateString());
                    }

                    if (Workflow.LastProcessedDateTime.HasValue)
                    {
                        tdLastProcessed.Description = string.Format("{0} {1} ({2})",
                                                                    Workflow.LastProcessedDateTime.Value.ToShortDateString(),
                                                                    Workflow.LastProcessedDateTime.Value.ToShortTimeString(),
                                                                    Workflow.LastProcessedDateTime.Value.ToRelativeDateString());
                    }

                    if (Workflow.CompletedDateTime.HasValue)
                    {
                        tdCompletedWhen.Description = string.Format("{0} {1} ({2})",
                                                                    Workflow.CompletedDateTime.Value.ToShortDateString(),
                                                                    Workflow.CompletedDateTime.Value.ToShortTimeString(),
                                                                    Workflow.CompletedDateTime.Value.ToRelativeDateString());
                    }

                    ShowAttributeValues();

                    var rockContext = new RockContext();
                    _personAliasService       = new PersonAliasService(rockContext);
                    _groupService             = new GroupService(rockContext);
                    rptrActivities.DataSource = Workflow.Activities.OrderBy(a => a.ActivatedDateTime).ToList();
                    rptrActivities.DataBind();

                    BindLog();
                }
                else
                {
                    nbNotAuthorized.Visible = true;
                    pnlContent.Visible      = false;
                }
            }

            HideSecondaryBlocks(false);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Handles the Click event of the lbSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void lbSave_Click(object sender, EventArgs e)
        {
            if (_group != null && _occurrence != null)
            {
                var rockContext        = new RockContext();
                var attendanceService  = new AttendanceService(rockContext);
                var personAliasService = new PersonAliasService(rockContext);
                var locationService    = new LocationService(rockContext);

                bool dateAdjusted = false;

                DateTime startDate = _occurrence.Date;

                // If this is a manuall entered occurrence, check to see if date was changed
                if (!_occurrence.ScheduleId.HasValue)
                {
                    DateTime?originalDate = PageParameter("Date").AsDateTime();
                    if (originalDate.HasValue && originalDate.Value.Date != startDate.Date)
                    {
                        startDate    = originalDate.Value.Date;
                        dateAdjusted = true;
                    }
                }
                DateTime endDate = startDate.AddDays(1);

                var existingAttendees = attendanceService
                                        .Queryable("PersonAlias")
                                        .Where(a =>
                                               a.GroupId == _group.Id &&
                                               a.LocationId == _occurrence.LocationId &&
                                               a.ScheduleId == _occurrence.ScheduleId &&
                                               a.StartDateTime >= startDate &&
                                               a.StartDateTime < endDate);

                if (dateAdjusted)
                {
                    foreach (var attendee in existingAttendees)
                    {
                        attendee.StartDateTime = _occurrence.Date;
                    }
                }

                // 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);
                    if (!campusId.HasValue)
                    {
                        campusId = _group.CampusId;
                    }
                    if (!campusId.HasValue && _allowCampusFilter)
                    {
                        var campus = CampusCache.Read(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;
                            attendance.DidNotOccur = true;
                        }
                    }

                    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.GroupId       = _group.Id;
                                attendance.ScheduleId    = _group.ScheduleId;
                                attendance.PersonAliasId = personAliasId;
                                attendance.StartDateTime = _occurrence.Date.Date.Add(_occurrence.StartTime);
                                attendance.LocationId    = _occurrence.LocationId;
                                attendance.CampusId      = campusId;
                                attendance.ScheduleId    = _occurrence.ScheduleId;

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

                                attendanceService.Add(attendance);
                            }
                        }

                        if (attendance != null)
                        {
                            if (cbDidNotMeet.Checked)
                            {
                                attendance.DidAttend   = null;
                                attendance.DidNotOccur = true;
                            }
                            else
                            {
                                attendance.DidAttend   = attendee.Attended;
                                attendance.DidNotOccur = null;
                            }
                        }
                    }
                }

                if (_occurrence.LocationId.HasValue)
                {
                    Rock.CheckIn.KioskLocationAttendance.Flush(_occurrence.LocationId.Value);
                }

                rockContext.SaveChanges();

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

                            workflow.SetAttributeValue("StartDateTime", _occurrence.Date.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);
                        }
                    }
                }

                var qryParams = new Dictionary <string, string> {
                    { "GroupId", _group.Id.ToString() }
                };

                var groupTypeIds = PageParameter("GroupTypeIds");
                if (!string.IsNullOrWhiteSpace(groupTypeIds))
                {
                    qryParams.Add("GroupTypeIds", groupTypeIds);
                }

                NavigateToParentPage(qryParams);
            }
        }
Ejemplo n.º 6
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);

            string to                  = GetAttributeValue(action, AttributeKey.To);
            string fromValue           = GetAttributeValue(action, AttributeKey.From);
            string replyTo             = GetAttributeValue(action, AttributeKey.ReplyTo);
            string subject             = GetAttributeValue(action, AttributeKey.Subject);
            string body                = GetAttributeValue(action, AttributeKey.Body);
            string cc                  = GetActionAttributeValue(action, AttributeKey.Cc);
            string bcc                 = GetActionAttributeValue(action, AttributeKey.Bcc);
            var    attachmentOneGuid   = GetAttributeValue(action, AttributeKey.AttachmentOne, true).AsGuid();
            var    attachmentTwoGuid   = GetAttributeValue(action, AttributeKey.AttachmentTwo, true).AsGuid();
            var    attachmentThreeGuid = GetAttributeValue(action, AttributeKey.AttachmentThree, true).AsGuid();

            var attachmentList = new List <BinaryFile>();

            if (!attachmentOneGuid.IsEmpty())
            {
                attachmentList.Add(new BinaryFileService(rockContext).Get(attachmentOneGuid));
            }

            if (!attachmentTwoGuid.IsEmpty())
            {
                attachmentList.Add(new BinaryFileService(rockContext).Get(attachmentTwoGuid));
            }

            if (!attachmentThreeGuid.IsEmpty())
            {
                attachmentList.Add(new BinaryFileService(rockContext).Get(attachmentThreeGuid));
            }

            var attachments = attachmentList.ToArray();

            bool createCommunicationRecord = GetAttributeValue(action, AttributeKey.SaveCommunicationHistory).AsBoolean();

            string fromEmailAddress = string.Empty;
            string fromName         = string.Empty;
            Guid?  fromGuid         = fromValue.AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var attribute = AttributeCache.Get(fromGuid.Value, rockContext);
                if (attribute != null)
                {
                    string fromAttributeValue = action.GetWorkflowAttributeValue(fromGuid.Value);
                    if (!string.IsNullOrWhiteSpace(fromAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = fromAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person != null && !string.IsNullOrWhiteSpace(person.Email))
                                {
                                    fromEmailAddress = person.Email;
                                    fromName         = person.FullName;
                                }
                            }
                        }
                        else
                        {
                            fromEmailAddress = fromAttributeValue;
                        }
                    }
                }
            }
            else
            {
                fromEmailAddress = fromValue.ResolveMergeFields(mergeFields);
            }

            string replyToEmailAddress = string.Empty;
            Guid?  replyToGuid         = replyTo.AsGuidOrNull();

            // If there is a "Reply To" value for the attribute, use that to get the "Reply To" email.
            if (replyToGuid.HasValue)
            {
                var attribute = AttributeCache.Get(replyToGuid.Value, rockContext);
                if (attribute != null)
                {
                    string replyToAttributeValue = action.GetWorkflowAttributeValue(replyToGuid.Value);
                    if (!string.IsNullOrWhiteSpace(replyToAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                        {
                            Guid personAliasGuid = replyToAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var personEmail = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .Select(a => a.Person.Email)
                                                  .FirstOrDefault();
                                if (personEmail.IsNotNullOrWhiteSpace())
                                {
                                    replyToEmailAddress = personEmail;
                                }
                            }
                        }
                        else
                        {
                            replyToEmailAddress = replyToAttributeValue;
                        }
                    }
                }
            }
            else
            {
                replyToEmailAddress = replyTo.ResolveMergeFields(mergeFields);
            }

            // To Email recipients list.
            if (GetEmailsFromAttributeValue(RecipientType.SendTo, to, action, mergeFields, rockContext, out string toDelimitedEmails, out List <RockEmailMessageRecipient> toRecipients))
            {
                // CC emails recipients list.
                GetEmailsFromAttributeValue(RecipientType.CC, cc, action, mergeFields, rockContext, out string ccDelimitedEmails, out List <RockEmailMessageRecipient> ccRecipients);
                List <string> ccEmails = BuildEmailList(ccDelimitedEmails, mergeFields, ccRecipients);

                // BCC emails recipients list.
                GetEmailsFromAttributeValue(RecipientType.BCC, bcc, action, mergeFields, rockContext, out string bccDelimitedEmails, out List <RockEmailMessageRecipient> bccRecipients);
                List <string> bccEmails = BuildEmailList(bccDelimitedEmails, mergeFields, bccRecipients);

                if (!string.IsNullOrWhiteSpace(toDelimitedEmails))
                {
                    Send(toDelimitedEmails, fromEmailAddress, fromName, replyToEmailAddress, subject, body, ccEmails, bccEmails, mergeFields, createCommunicationRecord, attachments, out errorMessages);
                }
                else if (toRecipients != null)
                {
                    Send(toRecipients, fromEmailAddress, fromName, replyToEmailAddress, subject, body, ccEmails, bccEmails, createCommunicationRecord, attachments, out errorMessages);
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));
            return(true);
        }
Ejemplo n.º 7
0
        private IQueryable <CommunionData> getQuery <T>()
        {
            using (var rockContext = new RockContext())
            {
                var workflowService       = new WorkflowService(rockContext);
                var attributeService      = new AttributeService(rockContext);
                var attributeValueService = new AttributeValueService(rockContext);
                var personAliasService    = new PersonAliasService(rockContext);
                var personService         = new PersonService(rockContext);
                var definedValueService   = new DefinedValueService(rockContext);

                Guid hospitalWorkflow             = GetAttributeValue("HospitalAdmissionWorkflow").AsGuid();
                Guid nursingHomeAdmissionWorkflow = GetAttributeValue("NursingHomeResidentWorkflow").AsGuid();
                Guid homeBoundPersonWorkflow      = GetAttributeValue("HomeboundPersonWorkflow").AsGuid();
                Guid hospitalList    = GetAttributeValue("HospitalList").AsGuid();
                Guid nursingHomeList = GetAttributeValue("NursingHomeList").AsGuid();

                var workflowTypesIdAsStrings = new WorkflowTypeService(rockContext).Queryable()
                                               .Where(wt =>
                                                      wt.Guid == hospitalWorkflow ||
                                                      wt.Guid == nursingHomeAdmissionWorkflow ||
                                                      wt.Guid == homeBoundPersonWorkflow
                                                      )
                                               .ToList()
                                               .Select(wf => wf.Id.ToString())
                                               .ToList();

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

                var wfTmpqry = workflowService.Queryable().AsNoTracking()
                               .Where(w => (
                                          w.WorkflowType.Guid == hospitalWorkflow ||
                                          w.WorkflowType.Guid == nursingHomeAdmissionWorkflow ||
                                          w.WorkflowType.Guid == homeBoundPersonWorkflow
                                          ) && (w.Status == "Active"));

                var tqry = wfTmpqry.Join(attributeValueService.Queryable(),
                                         obj => obj.Id,
                                         av => av.EntityId.Value,
                                         (obj, av) => new { Workflow = obj, AttributeValue = av })
                           .Where(a => attributeIds.Contains(a.AttributeValue.AttributeId))
                           .GroupBy(obj => obj.Workflow)
                           .Select(obj => new { Workflow = obj.Key, AttributeValues = obj.Select(a => a.AttributeValue) });
                var qry = tqry.ToList();


                List <DefinedValueCache> facilities = DefinedTypeCache.All().Where(dv => dv.Guid == hospitalList || dv.Guid == nursingHomeList).SelectMany(dv => dv.DefinedValues).ToList();

                var newQry = qry.Select(w => new CommunionData
                {
                    Campus = new Func <Campus>(() =>
                    {
                        Campus campus = null;
                        AttributeValue personAliasAV = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "PersonToVisit" || av.AttributeKey == "HomeboundPerson").FirstOrDefault();
                        if (personAliasAV != null)
                        {
                            PersonAlias pa = personAliasService.Get(personAliasAV.Value.AsGuid());
                            if (pa != null)
                            {
                                campus = pa.Person.GetCampus();
                            }
                        }
                        if (campus == null)
                        {
                            campus = new Campus()
                            {
                                Name = "Unknown"
                            };
                        }
                        return(campus);
                    })(),
                    Person      = GetPerson(personAliasService, w.AttributeValues),
                    Age         = GetPerson(personAliasService, w.AttributeValues).Age,
                    Description = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "VisitationRequestDescription" || av.AttributeKey == "HomeboundResidentDescription").Select(av => av.ValueFormatted).FirstOrDefault(),
                    Location    = new Func <string>(() =>
                    {
                        return(w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "NursingHome" || av.AttributeKey == "Hospital").Select(av => av.ValueFormatted).DefaultIfEmpty("Home").FirstOrDefault());
                    })(),
                    Address        = GetLocation(personService, w.AttributeValues, facilities).Street1 + " " + GetLocation(personService, w.AttributeValues, facilities).Street2,
                    City           = GetLocation(personService, w.AttributeValues, facilities).City,
                    State          = GetLocation(personService, w.AttributeValues, facilities).State,
                    PostalCode     = GetLocation(personService, w.AttributeValues, facilities).PostalCode,
                    FacilityNumber = GetFacilityNumber(personService, w.AttributeValues, facilities),
                    Room           = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "Room").Select(av => av.ValueFormatted).FirstOrDefault(),
                    AdmitDate      = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "AdmitDate" || av.AttributeKey == "StartDate").Select(av => av.ValueFormatted).FirstOrDefault(),
                    Status         = w.Workflow.Status,
                    Communion      = w.AttributeValues.AsQueryable().Where(av => av.AttributeKey == "Communion").FirstOrDefault().ValueFormatted
                })
                             .Where(o => o.Communion.AsBoolean() && !o.Person.IsDeceased)
                             .OrderBy(a => a.PostalCode)
                             .ThenBy(a => a.Address)
                             .ToList()
                             .AsQueryable();


                List <COMMUNION_STATES> states = cblState.Items.Cast <ListItem>().Where(i => i.Selected).Select(i => ( COMMUNION_STATES )int.Parse(i.Value)).ToList();

                if (states.Count > 0)
                {
                    newQry = newQry.Where(o => (states.Contains(COMMUNION_STATES.KY) && o.State == "KY") ||
                                          (states.Contains(COMMUNION_STATES.IN) && o.State == "IN") ||
                                          ((states.Contains(COMMUNION_STATES.Other) && o.State != "IN" && o.State != "KY")));
                }
                List <int> campuses = cpCampus.Items.Cast <ListItem>().Where(i => i.Selected).Select(i => int.Parse(i.Value)).ToList();

                if (campuses.Count > 0)
                {
                    newQry = newQry.Where(o => campuses.Contains(o.Campus.Id));
                }


                //AddGridColumns( newQry.FirstOrDefault() );

                SortProperty sortProperty = gReport.SortProperty;
                if (sortProperty != null)
                {
                    newQry = newQry.Sort(sortProperty);
                }

                return(newQry);
            }
        }
Ejemplo n.º 8
0
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Check to see if the action's activity does not yet have the the 'InviteLink' attribute.
            string signNowDocumentId = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "SignNowDocumentId").AsGuid());

            if (string.IsNullOrEmpty(signNowDocumentId))
            {
                errorMessages.Add("A sign now document is required to complete this action");
                return(false);
            }

            Guid documentGuid = action.GetWorklowAttributeValue(GetActionAttributeValue(action, "Document").AsGuid()).AsGuid();


            PersonAliasService personAliasService = new PersonAliasService(rockContext);
            BinaryFileService  binaryfileService  = new BinaryFileService(rockContext);


            SignNow signNow        = new SignNow();
            string  snErrorMessage = "";
            string  token          = signNow.GetAccessToken(false, out snErrorMessage);

            if (!string.IsNullOrEmpty(snErrorMessage))
            {
                errorMessages.Add(snErrorMessage);
                return(false);
            }

            //Check if document is signed.
            JObject document = SignNowSDK.Document.Get(token, signNowDocumentId);

            if ((( JArray )document["signatures"]).Count() > 0)
            {
                // Download the file
                string tempPath     = Path.GetTempPath();
                string tempFileName = (String)document["document_name"];
                var    result       = SignNowSDK.Document.Download(token, signNowDocumentId, tempPath, tempFileName);

                // Put it into the workflow attribute
                BinaryFile signedPDF = binaryfileService.Get(documentGuid);
                if (signedPDF == null)
                {
                    signedPDF = new BinaryFile();
                    // TODO: This probably shouldn't be hardcoded
                    signedPDF.MimeType    = "application/pdf";
                    signedPDF.FileName    = tempFileName;
                    signedPDF.IsTemporary = false;
                    binaryfileService.Add(signedPDF);

                    // Update the file type if necessary
                    Guid binaryFileTypeGuid = Guid.Empty;

                    var destinationAttribute    = AttributeCache.Get(GetActionAttributeValue(action, "Document").AsGuid(), rockContext);
                    var binaryFileTypeQualifier = destinationAttribute.QualifierValues["binaryFileType"];
                    if (!String.IsNullOrWhiteSpace(binaryFileTypeQualifier.Value))
                    {
                        if (binaryFileTypeQualifier.Value != null)
                        {
                            binaryFileTypeGuid = binaryFileTypeQualifier.Value.AsGuid();

                            signedPDF.BinaryFileTypeId = new BinaryFileTypeService(rockContext).Get(binaryFileTypeGuid).Id;
                        }
                    }
                    signedPDF.DatabaseData         = new BinaryFileData();
                    signedPDF.DatabaseData.Content = File.ReadAllBytes(tempPath + tempFileName + ".pdf");

                    rockContext.SaveChanges();

                    // Now store the attribute
                    if (destinationAttribute.EntityTypeId == new Workflow().TypeId)
                    {
                        action.Activity.Workflow.SetAttributeValue(destinationAttribute.Key, signedPDF.Guid.ToString());
                    }
                    else if (destinationAttribute.EntityTypeId == new WorkflowActivity().TypeId)
                    {
                        action.Activity.SetAttributeValue(destinationAttribute.Key, signedPDF.Guid.ToString());
                    }
                }
                else
                {
                    signedPDF.FileName             = tempFileName;
                    signedPDF.DatabaseData.Content = File.ReadAllBytes(tempPath + tempFileName + ".pdf");
                }

                // Delete the file when we are done:
                File.Delete(tempPath + tempFileName);

                // We have a signed copy
                SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "PDFSigned").AsGuid(), "True");
            }
            else
            {
                // Not signed yet.
                SetWorkflowAttributeValue(action, GetActionAttributeValue(action, "PDFSigned").AsGuid(), "False");
            }
            return(true);
        }
        private void DisplayResults()
        {
            RockContext rockContext = new RockContext();

            var statementYear = RockDateTime.Now.Year;

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

            FinancialTransactionDetailService financialTransactionDetailService = new FinancialTransactionDetailService(rockContext);

            Person targetPerson = CurrentPerson;

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

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

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

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

            // fetch all the possible PersonAliasIds that have this GivingID to help optimize the SQL
            var personAliasIds = new PersonAliasService(rockContext).Queryable().Where(a => a.Person.GivingId == targetPerson.GivingId).Select(a => a.Id).ToList();

            // get the transactions for the person or all the members in the person's giving group (Family)
            var qry = financialTransactionDetailService.Queryable().AsNoTracking()
                      .Where(t => t.Transaction.AuthorizedPersonAliasId.HasValue && personAliasIds.Contains(t.Transaction.AuthorizedPersonAliasId.Value));

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

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

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

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

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

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

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

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

            string salutation = string.Empty;

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

            var homeAddress = targetPerson.GetHomeLocation();

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

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

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

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

            // add detailed pledge information
            foreach (var pledge in pledges)
            {
                var adjustedPedgeEndDate = pledge.PledgeEndDate.Value.Date.AddDays(1);
                pledge.AmountGiven = new FinancialTransactionDetailService(rockContext).Queryable()
                                     .Where(t =>
                                            t.AccountId == pledge.AccountId &&
                                            t.Transaction.AuthorizedPersonAliasId.HasValue && personAliasIds.Contains(t.Transaction.AuthorizedPersonAliasId.Value) &&
                                            t.Transaction.TransactionDateTime >= pledge.PledgeStartDate &&
                                            t.Transaction.TransactionDateTime < adjustedPedgeEndDate)
                                     .Sum(t => ( decimal? )t.Amount) ?? 0;

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

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

            mergeFields.Add("Pledges", pledges);

            var template = GetAttributeValue("LavaTemplate");

            lResults.Text = template.ResolveMergeFields(mergeFields);

            // show debug info
            if (GetAttributeValue("EnableDebug").AsBoolean() && IsUserAuthorized(Authorization.EDIT))
            {
                lDebug.Visible = true;
                lDebug.Text    = mergeFields.lavaDebugInfo();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Processes the giving journeys.
        /// </summary>
        internal void UpdateGivingJourneyStages()
        {
            var givingAnalyticsSetting = GivingAutomationSettings.LoadGivingAutomationSettings();

            var rockContext = new RockContext();

            rockContext.Database.CommandTimeout = this.SqlCommandTimeout;
            var personService = new PersonService(rockContext);

            // Limit to only Business and Person type records.
            // Include deceased to cover transactions that could have occurred when they were not deceased
            // or transactions that are dated after they were marked deceased.
            var personQuery = personService.Queryable(new PersonService.PersonQueryOptions
            {
                IncludeDeceased   = true,
                IncludeBusinesses = true,
                IncludePersons    = true,
                IncludeNameless   = false,
                IncludeRestUsers  = false
            });

            var personAliasService          = new PersonAliasService(rockContext);
            var personAliasQuery            = personAliasService.Queryable();
            var financialTransactionService = new FinancialTransactionService(rockContext);
            var financialTransactionGivingAnalyticsQuery = financialTransactionService.GetGivingAutomationSourceTransactionQuery();

            if (OnProgress != null)
            {
                string progressMessage = "Calculating journey classifications...";
                OnProgress.Invoke(this, new ProgressEventArgs(progressMessage));
            }

            /* Get Non-Giver GivingIds */
            var nonGiverGivingIdsQuery = personQuery.Where(p =>
                                                           !financialTransactionGivingAnalyticsQuery.Any(ft => personAliasQuery.Any(pa => pa.Id == ft.AuthorizedPersonAliasId && pa.Person.GivingId == p.GivingId)));

            var nonGiverGivingIdsList = nonGiverGivingIdsQuery.Select(a => a.GivingId).Distinct().ToList();

            /* Get TransactionDateList for each GivingId in the system */
            var transactionDateTimes = financialTransactionGivingAnalyticsQuery.Select(a => new
            {
                GivingId = personAliasQuery.Where(pa => pa.Id == a.AuthorizedPersonAliasId).Select(pa => pa.Person.GivingId).FirstOrDefault(),
                a.TransactionDateTime
            }).Where(a => a.GivingId != null).ToList();

            var transactionDateTimesByGivingId = transactionDateTimes
                                                 .GroupBy(g => g.GivingId)
                                                 .Select(s => new
            {
                GivingId = s.Key,
                TransactionDateTimeList = s.Select(x => x.TransactionDateTime).ToList()
            }).ToDictionary(k => k.GivingId, v => v.TransactionDateTimeList);

            List <AttributeCache> journeyStageAttributesList = new List <AttributeCache> {
                _currentJourneyStageAttribute, _previousJourneyStageAttribute, _journeyStageChangeDateAttribute
            };

            if (journeyStageAttributesList.Any(a => a == null))
            {
                throw new Exception("Journey Stage Attributes are not installed correctly.");
            }

            var journeyStageAttributeIds = journeyStageAttributesList.Where(a => a != null).Select(a => a.Id).ToList();

            var personCurrentJourneyAttributeValues = new AttributeValueService(rockContext).Queryable()
                                                      .WhereAttributeIds(journeyStageAttributeIds)
                                                      .Where(av => av.EntityId.HasValue)
                                                      .Join(
                personQuery.Where(x => !string.IsNullOrEmpty(x.GivingId)),
                av => av.EntityId.Value,
                p => p.Id,
                (av, p) => new
            {
                AttributeId    = av.AttributeId,
                AttributeValue = av.Value,
                PersonGivingId = p.GivingId,
                PersonId       = p.Id
            })
                                                      .GroupBy(a => a.PersonGivingId)
                                                      .Select(a => new
            {
                GivingId        = a.Key,
                AttributeValues = a.ToList()
            }).ToDictionary(k => k.GivingId, v => v.AttributeValues);

            var givingJourneySettings = givingAnalyticsSetting.GivingJourneySettings;
            var currentDate           = RockDateTime.Today;

            var formerGiverGivingIds     = new List <string>();
            var lapsedGiverGivingIds     = new List <string>();
            var newGiverGivingIds        = new List <string>();
            var occasionalGiverGivingIds = new List <string>();
            var consistentGiverGivingIds = new List <string>();

            var noneOfTheAboveGiverGivingIds = new List <string>();

            foreach (var givingIdTransactions in transactionDateTimesByGivingId)
            {
                var givingId            = givingIdTransactions.Key;
                var transactionDateList = givingIdTransactions.Value.Where(a => a.HasValue).Select(a => a.Value).ToList();

                GivingJourneyStage?givingIdGivingJourneyStage = GetGivingJourneyStage(givingJourneySettings, currentDate, transactionDateList);

                switch (givingIdGivingJourneyStage)
                {
                case GivingJourneyStage.Former:
                    formerGiverGivingIds.Add(givingId);
                    break;

                case GivingJourneyStage.Lapsed:
                    lapsedGiverGivingIds.Add(givingId);
                    break;

                case GivingJourneyStage.New:
                    newGiverGivingIds.Add(givingId);
                    break;

                case GivingJourneyStage.Occasional:
                    occasionalGiverGivingIds.Add(givingId);
                    break;

                case GivingJourneyStage.Consistent:
                    consistentGiverGivingIds.Add(givingId);
                    break;

                case GivingJourneyStage.None:
                    // Shouldn't happen since we are only looking at people with transactions, and we have already
                    // figured out the non-givers
                    break;

                default:
                    // if they are non of the above, then add them to the "none of the above" list
                    noneOfTheAboveGiverGivingIds.Add(givingId);
                    break;
                }
            }

            Debug.WriteLine($@"
FormerGiverCount: {formerGiverGivingIds.Count}
LapsedGiverCount: {lapsedGiverGivingIds.Count}
NewGiverCount: {newGiverGivingIds.Count}
OccasionalGiverCount: {occasionalGiverGivingIds.Count}
ConsistentGiverCount: {consistentGiverGivingIds.Count}
NonGiverCount: {nonGiverGivingIdsList.Count}
NoneOfTheAboveCount: {noneOfTheAboveGiverGivingIds.Count}
");

            _attributeValuesByGivingIdAndPersonId = personCurrentJourneyAttributeValues
                                                    .ToDictionary(
                k => k.Key,
                v =>
            {
                var lookupByPersonId = v.Value
                                       .Select(s => new AttributeValueCache(s.AttributeId, s.PersonId, s.AttributeValue))
                                       .GroupBy(g => g.EntityId.Value)
                                       .ToDictionary(k => k.Key, vv => vv.ToList());
                return(lookupByPersonId);
            });

            _personIdsByGivingId = personQuery.Where(x => !string.IsNullOrEmpty(x.GivingId))
                                   .Select(a => new { a.GivingId, PersonId = a.Id })
                                   .GroupBy(a => a.GivingId)
                                   .ToDictionary(
                k => k.Key,
                v => v.Select(p => p.PersonId).ToList());

            UpdateJourneyStageAttributeValuesForGivingId(formerGiverGivingIds, GivingJourneyStage.Former);
            UpdateJourneyStageAttributeValuesForGivingId(lapsedGiverGivingIds, GivingJourneyStage.Lapsed);
            UpdateJourneyStageAttributeValuesForGivingId(newGiverGivingIds, GivingJourneyStage.New);
            UpdateJourneyStageAttributeValuesForGivingId(occasionalGiverGivingIds, GivingJourneyStage.Occasional);
            UpdateJourneyStageAttributeValuesForGivingId(consistentGiverGivingIds, GivingJourneyStage.Consistent);
            UpdateJourneyStageAttributeValuesForGivingId(nonGiverGivingIdsList, GivingJourneyStage.None);
            UpdateJourneyStageAttributeValuesForGivingId(noneOfTheAboveGiverGivingIds, null);
        }
Ejemplo n.º 11
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)
        {
            var rockContext = (RockContext)serviceInstance.Context;

            SelectionConfig selectionConfig = SelectionConfig.Parse(selection);

            if (selectionConfig == null)
            {
                return(null);
            }

            DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(selectionConfig.DelimitedValues);

            int transactionTypeContributionId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid()).Id;
            var financialTransactionBaseQry   = new FinancialTransactionService(rockContext)
                                                .Queryable()
                                                .Where(xx => xx.TransactionTypeValueId == transactionTypeContributionId);

            var accountIdList = new FinancialAccountService(( RockContext )serviceInstance.Context).GetByGuids(selectionConfig.AccountGuids).Select(a => a.Id).ToList();

            if (accountIdList.Any())
            {
                if (accountIdList.Count == 1)
                {
                    int accountId = accountIdList.First();
                    financialTransactionBaseQry = financialTransactionBaseQry.Where(xx => xx.TransactionDetails.Any(a => a.AccountId == accountId));
                }
                else
                {
                    financialTransactionBaseQry = financialTransactionBaseQry.Where(xx => xx.TransactionDetails.Any(a => accountIdList.Contains(a.AccountId)));
                }
            }

            var personAliasQry   = new PersonAliasService(rockContext).Queryable();
            var personQryForJoin = new PersonService(rockContext).Queryable();

            // Create explicit joins to person alias and person tables so that rendered SQL has an INNER Joins vs OUTER joins on PersonAlias
            var financialTransactionsQry = financialTransactionBaseQry
                                           .Join(personAliasQry, t => t.AuthorizedPersonAliasId, pa => pa.Id, (t, pa) => new
            {
                txn      = t,
                PersonId = pa.PersonId
            });

            var firstContributionDateQry = financialTransactionsQry
                                           .GroupBy(xx => xx.PersonId)
                                           .Select(ss => new
            {
                PersonId             = ss.Key,
                FirstTransactionDate = ss.Min(a => selectionConfig.UseSundayDate == true ? a.txn.SundayDate : a.txn.TransactionDateTime)
            });

            if (dateRange.Start.HasValue)
            {
                firstContributionDateQry = firstContributionDateQry.Where(xx => xx.FirstTransactionDate >= dateRange.Start.Value);
            }

            if (dateRange.End.HasValue)
            {
                firstContributionDateQry = firstContributionDateQry.Where(xx => xx.FirstTransactionDate < dateRange.End.Value);
            }

            var innerQry = firstContributionDateQry.Select(xx => xx.PersonId).AsQueryable();
            var qry      = new PersonService(rockContext).Queryable().Where(p => innerQry.Any(xx => xx == p.Id));

            return(FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"));
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            RockContext rockContext = new RockContext();
            FinancialTransactionService transService = new FinancialTransactionService(rockContext);
            var qry = transService.Queryable("TransactionDetails.Account,FinancialPaymentDetail");

            List <int> personAliasIds;

            if (TargetPerson != null)
            {
                personAliasIds = new PersonAliasService(rockContext).Queryable().Where(a => a.Person.GivingId == TargetPerson.GivingId).Select(a => a.Id).ToList();
            }
            else
            {
                personAliasIds = new List <int>();
            }

            qry = qry.Where(t => t.AuthorizedPersonAliasId.HasValue && personAliasIds.Contains(t.AuthorizedPersonAliasId.Value));


            // if the Account Checkboxlist is visible, filter to what was selected.  Otherwise, show all the accounts that the person contributed to
            if (cblAccounts.Visible)
            {
                // get list of selected accounts
                List <int> selectedAccountIds = cblAccounts.Items.Cast <ListItem>()
                                                .Where(i => i.Selected == true)
                                                .Select(i => int.Parse(i.Value)).ToList();
                qry = qry.Where(t => t.TransactionDetails.Any(d => selectedAccountIds.Contains(d.AccountId)));
            }

            if (drpFilterDates.LowerValue.HasValue)
            {
                qry = qry.Where(t => t.TransactionDateTime.Value >= drpFilterDates.LowerValue.Value);
            }

            if (drpFilterDates.UpperValue.HasValue)
            {
                var lastDate = drpFilterDates.UpperValue.Value.AddDays(1);   // add one day to ensure we get all transactions till midnight
                qry = qry.Where(t => t.TransactionDateTime.Value < lastDate);
            }

            // Transaction Types
            var transactionTypeValueIdList = GetAttributeValue("TransactionTypes").SplitDelimitedValues().AsGuidList().Select(a => DefinedValueCache.Get(a)).Where(a => a != null).Select(a => a.Id).ToList();

            if (transactionTypeValueIdList.Any())
            {
                qry = qry.Where(t => transactionTypeValueIdList.Contains(t.TransactionTypeValueId));
            }

            qry = qry.OrderByDescending(a => a.TransactionDateTime);

            var txns = qry.ToList();

            // get account totals
            Dictionary <string, decimal> accountTotals = new Dictionary <string, decimal>();

            foreach (var transaction in txns)
            {
                foreach (var transactionDetail in transaction.TransactionDetails)
                {
                    if (accountTotals.Keys.Contains(transactionDetail.Account.PublicName))
                    {
                        accountTotals[transactionDetail.Account.PublicName] += transactionDetail.Amount;
                    }
                    else
                    {
                        accountTotals.Add(transactionDetail.Account.PublicName, transactionDetail.Amount);
                    }
                }
            }

            lAccountSummary.Text = string.Empty;
            if (accountTotals.Count > 0)
            {
                pnlSummary.Visible = true;
                foreach (var key in accountTotals.Keys)
                {
                    lAccountSummary.Text += string.Format("<li>{0}: {1}</li>", key, accountTotals[key].FormatAsCurrency());
                }
            }
            else
            {
                pnlSummary.Visible = false;
            }

            gTransactions.EntityTypeId = EntityTypeCache.Get <FinancialTransaction>().Id;
            gTransactions.DataSource   = txns.Select(t => new
            {
                t.Id,
                t.TransactionDateTime,
                CurrencyType = FormatCurrencyType(t),
                t.TransactionCode,
                t.ForeignKey,
                Summary = FormatSummary(t),
                t.TotalAmount
            }).ToList();

            gTransactions.ColumnsOfType <Rock.Web.UI.Controls.RockBoundField>().First(c => c.HeaderText == "Transaction Code").Visible =
                GetAttributeValue("ShowTransactionCode").AsBoolean();

            gTransactions.ColumnsOfType <Rock.Web.UI.Controls.RockBoundField>().First(c => c.HeaderText == "Foreign Key").Visible =
                GetAttributeValue("ShowForeignKey").AsBoolean();

            gTransactions.DataBind();
        }
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>();

            Guid?    groupGuid          = null;
            Person   person             = null;
            DateTime attendanceDateTime = DateTime.MinValue;
            bool     addToGroup         = true;

            // get the group attribute
            Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid();

            if (!groupAttributeGuid.IsEmpty())
            {
                groupGuid = action.GetWorklowAttributeValue(groupAttributeGuid).AsGuidOrNull();

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

            // get person alias guid
            Guid   personAliasGuid = Guid.Empty;
            string personAttribute = GetAttributeValue(action, "Person");

            Guid guid = personAttribute.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string value = action.GetWorklowAttributeValue(guid);
                    personAliasGuid = value.AsGuid();
                }

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable().AsNoTracking()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();
                }
                else
                {
                    errorMessages.Add("The person could not be found in the attribute!");
                }
            }

            // get attendance date
            Guid dateTimeAttributeGuid = GetAttributeValue(action, "AttendanceDatetime").AsGuid();

            if (!dateTimeAttributeGuid.IsEmpty())
            {
                string attributeDatetime = action.GetWorklowAttributeValue(dateTimeAttributeGuid);

                if (string.IsNullOrWhiteSpace(attributeDatetime))
                {
                    attendanceDateTime = RockDateTime.Now;
                }
                else
                {
                    if (!DateTime.TryParse(attributeDatetime, out attendanceDateTime))
                    {
                        errorMessages.Add(string.Format("Could not parse the date provided {0}.", attributeDatetime));
                    }
                }
            }

            // get add to group
            addToGroup = GetAttributeValue(action, "AddToGroup").AsBoolean();

            // get campus
            Guid campusGuid          = Guid.Empty;
            Guid campusAttributeGuid = GetAttributeValue(action, "Campus").AsGuid();

            if (!campusAttributeGuid.IsEmpty())
            {
                var campusAttribute = AttributeCache.Read(campusAttributeGuid, rockContext);

                if (campusAttribute != null)
                {
                    campusGuid = action.GetWorklowAttributeValue(campusAttributeGuid).AsGuid();
                }
            }

            // set attribute
            if (groupGuid.HasValue && person != null && attendanceDateTime != DateTime.MinValue)
            {
                var group = new GroupService(rockContext).Queryable("GroupType.DefaultGroupRole")
                            .Where(g => g.Guid == groupGuid)
                            .FirstOrDefault();
                if (group != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);

                    // get group member
                    var groupMember = groupMemberService.Queryable()
                                      .Where(m => m.Group.Guid == groupGuid &&
                                             m.PersonId == person.Id)
                                      .FirstOrDefault();
                    if (groupMember == null)
                    {
                        if (addToGroup)
                        {
                            if (group != null)
                            {
                                groupMember                   = new GroupMember();
                                groupMember.GroupId           = group.Id;
                                groupMember.PersonId          = person.Id;
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                groupMember.GroupRole         = group.GroupType.DefaultGroupRole;
                                groupMemberService.Add(groupMember);
                                rockContext.SaveChanges();
                            }
                        }
                        else
                        {
                            action.AddLogEntry(string.Format("{0} was not a member of the group {1} and the action was not configured to add them.", person.FullName, group.Name));
                            return(true);
                        }
                    }

                    AttendanceService attendanceService = new AttendanceService(rockContext);

                    Attendance attendance = new Attendance();
                    attendance.GroupId       = group.Id;
                    attendance.PersonAliasId = person.PrimaryAliasId;
                    attendance.StartDateTime = attendanceDateTime;
                    attendance.DidAttend     = true;

                    if (campusGuid != Guid.Empty)
                    {
                        var campus = new CampusService(rockContext).Queryable().AsNoTracking()
                                     .Where(l => l.Guid == campusGuid)
                                     .FirstOrDefault();

                        if (campus != null)
                        {
                            attendance.CampusId = campus.Id;
                        }
                    }

                    attendanceService.Add(attendance);
                    rockContext.SaveChanges();
                }
                else
                {
                    errorMessages.Add(string.Format("Could not find group matching the guid '{0}'.", groupGuid));
                }
            }

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

            return(true);
        }
Ejemplo n.º 14
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)
        {
            var rockContext = (RockContext)serviceInstance.Context;

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length < 4)
            {
                return(null);
            }

            ComparisonType comparisonType = selectionValues[0].ConvertToEnum <ComparisonType>(ComparisonType.GreaterThanOrEqualTo);
            decimal        amount         = selectionValues[1].AsDecimalOrNull() ?? 0.00M;
            DateTime?      startDate      = selectionValues[2].AsDateTime();
            DateTime?      endDate        = selectionValues[3].AsDateTime();
            var            accountIdList  = new List <int>();

            if (selectionValues.Length >= 5)
            {
                var accountGuids = selectionValues[4].Split(',').Select(a => a.AsGuid()).ToList();
                accountIdList = new FinancialAccountService((RockContext)serviceInstance.Context).GetByGuids(accountGuids).Select(a => a.Id).ToList();
            }

            bool combineGiving = false;

            if (selectionValues.Length >= 6)
            {
                combineGiving = selectionValues[5].AsBooleanOrNull() ?? false;
            }

            int transactionTypeContributionId = Rock.Web.Cache.DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid()).Id;

            var financialTransactionQry = new FinancialTransactionService(rockContext).Queryable()
                                          .Where(xx => xx.AuthorizedPersonAliasId.HasValue)
                                          .Where(xx => xx.TransactionTypeValueId == transactionTypeContributionId);

            if (startDate.HasValue)
            {
                financialTransactionQry = financialTransactionQry.Where(xx => xx.TransactionDateTime >= startDate.Value);
            }

            if (endDate.HasValue)
            {
                financialTransactionQry = financialTransactionQry.Where(xx => xx.TransactionDateTime < endDate.Value);
            }

            bool limitToAccounts = accountIdList.Any();

            // Create an explicit join to person alias so that rendered SQL is an INNER Join vs OUTER join
            var personAliasQry = new PersonAliasService(rockContext).Queryable();
            var financialTransactionGivingGroupQry = financialTransactionQry
                                                     .Join(personAliasQry, t => t.AuthorizedPersonAliasId, p => p.Id, (t, p) => new
            {
                Txn           = t,
                GivingGroupId = p.Person.GivingGroupId
            });

            // query transactions for individuals.
            // If CombineGiving, exclude people that are Giving Group, and we'll get those when we union with CombineGiving
            var financialTransactionDetailsIndividualQry = financialTransactionGivingGroupQry.Where(a => !combineGiving || !a.GivingGroupId.HasValue).Select(a => a.Txn)
                                                           .GroupBy(xx => xx.AuthorizedPersonAlias.PersonId
                                                                    ).Select(xx =>
                                                                             new
            {
                PersonId    = xx.Key,
                TotalAmount = xx.Sum(ss => ss.TransactionDetails.Where(td => !limitToAccounts || accountIdList.Contains(td.AccountId)).Sum(td => td.Amount))
            });

            if (comparisonType == ComparisonType.LessThan)
            {
                financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.TotalAmount < amount);
            }
            else if (comparisonType == ComparisonType.EqualTo)
            {
                financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.TotalAmount == amount);
            }
            else if (comparisonType == ComparisonType.GreaterThanOrEqualTo)
            {
                financialTransactionDetailsIndividualQry = financialTransactionDetailsIndividualQry.Where(xx => xx.TotalAmount >= amount);
            }

            var innerQryIndividual = financialTransactionDetailsIndividualQry.Select(xx => xx.PersonId).AsQueryable();

            IQueryable <int> qryTransactionPersonIds;

            if (combineGiving)
            {
                // if CombineGiving=true, do another query to total by GivingGroupId for people with GivingGroupId specified
                var financialTransactionDetailsGivingGroupQry = financialTransactionGivingGroupQry.Where(a => a.GivingGroupId.HasValue)
                                                                .GroupBy(xx => new
                {
                    xx.GivingGroupId
                }).Select(xx =>
                          new
                {
                    GivingGroupId = xx.Key,
                    TotalAmount   = xx.Sum(ss => ss.Txn.TransactionDetails.Where(td => !limitToAccounts || accountIdList.Contains(td.AccountId)).Sum(td => td.Amount))
                });

                if (comparisonType == ComparisonType.LessThan)
                {
                    financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.TotalAmount < amount);
                }
                else if (comparisonType == ComparisonType.EqualTo)
                {
                    financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.TotalAmount == amount);
                }
                else if (comparisonType == ComparisonType.GreaterThanOrEqualTo)
                {
                    financialTransactionDetailsGivingGroupQry = financialTransactionDetailsGivingGroupQry.Where(xx => xx.TotalAmount >= amount);
                }

                var groupMemberService = new GroupMemberService(rockContext);
                IQueryable <int> innerQryGivingGroupPersons = groupMemberService.Queryable()
                                                              .Where(a => financialTransactionDetailsGivingGroupQry.Select(xx => xx.GivingGroupId).AsQueryable().Any(gg => gg.GivingGroupId == a.GroupId))
                                                              .Select(s => s.PersonId);

                // include people that either give as individuals or are members of a giving group
                qryTransactionPersonIds = innerQryIndividual.Union(innerQryGivingGroupPersons);
            }
            else
            {
                // don't factor in GivingGroupId.  Only include people that are directly associated with the transaction
                qryTransactionPersonIds = innerQryIndividual;
            }

            var qry = new PersonService(rockContext).Queryable()
                      .Where(p => qryTransactionPersonIds.Any(xx => xx == p.Id));

            Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p");

            return(extractedFilterExpression);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Process inbound messages that are sent to a SMS number.
        /// </summary>
        /// <param name="toPhone">The phone number a message is sent to.</param>
        /// <param name="fromPhone">The phone number a message is sent from.</param>
        /// <param name="message">The message that was sent.</param>
        /// <param name="errorMessage">The error message.</param>
        public void ProcessResponse(string toPhone, string fromPhone, string message, out string errorMessage)
        {
            errorMessage = string.Empty;

            string transportPhone = string.Empty;

            using (var rockContext = new RockContext())
            {
                Person toPerson = null;

                var mobilePhoneNumberValueId = DefinedValueCache.Get(SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE).Id;
                var cleanFromPhone           = fromPhone.Replace("+", "");

                //
                // Get the person who sent the message. Filter to any matching phone number, regardless
                // of type. Then order by those with a matching number and SMS enabled; then further order
                // by matching number with type == mobile; finally order by person Id to get the oldest
                // person to get the oldest person in the case of duplicate records.
                //
                var fromPerson = new PersonService(rockContext).Queryable()
                                 .Where(p => p.PhoneNumbers.Any(n => (n.CountryCode + n.Number) == cleanFromPhone))
                                 .OrderByDescending(p => p.PhoneNumbers.Any(n => (n.CountryCode + n.Number) == cleanFromPhone && n.IsMessagingEnabled))
                                 .ThenByDescending(p => p.PhoneNumbers.Any(n => (n.CountryCode + n.Number) == cleanFromPhone && n.NumberTypeValueId == mobilePhoneNumberValueId))
                                 .ThenBy(p => p.Id)
                                 .FirstOrDefault();

                // get recipient from defined value
                var fromPhoneDv = FindFromPhoneDefinedValue(toPhone);
                if (fromPhoneDv != null)
                {
                    var toPersonAliasGuid = fromPhoneDv.GetAttributeValue("ResponseRecipient").AsGuidOrNull();
                    if (toPersonAliasGuid.HasValue)
                    {
                        toPerson = new PersonAliasService(rockContext)
                                   .Queryable().Where(p => p.Guid.Equals(toPersonAliasGuid.Value))
                                   .Select(p => p.Person)
                                   .FirstOrDefault();
                    }
                }

                if (fromPerson != null && toPerson != null && fromPerson.PrimaryAliasId.HasValue && toPerson.PrimaryAliasId.HasValue)
                {
                    if (toPerson.Id == fromPerson.Id)   // message from the medium recipient
                    {
                        // look for response code in the message
                        Match match = Regex.Match(message, @"@\d{3,5}");
                        if (match.Success)
                        {
                            string responseCode = match.ToString();

                            var recipient = new CommunicationRecipientService(rockContext).Queryable("Communication")
                                            .Where(r => r.ResponseCode == responseCode)
                                            .OrderByDescending(r => r.CreatedDateTime).FirstOrDefault();

                            if (recipient != null && recipient.Communication.SenderPersonAliasId.HasValue)
                            {
                                CreateCommunication(fromPerson.PrimaryAliasId.Value, fromPerson.FullName, recipient.Communication.SenderPersonAliasId.Value, message.Replace(responseCode, ""), fromPhoneDv, "", rockContext);
                            }
                            else // send a warning message back to the medium recipient
                            {
                                string warningMessage = string.Format("A conversation could not be found with the response token {0}.", responseCode);
                                CreateCommunication(fromPerson.PrimaryAliasId.Value, fromPerson.FullName, fromPerson.PrimaryAliasId.Value, warningMessage, fromPhoneDv, "", rockContext);
                            }
                        }
                    }
                    else // response from someone other than the medium recipient
                    {
                        string messageId = GenerateResponseCode(rockContext);
                        message = string.Format("-{0}-\n{1}\n( {2} )", fromPerson.FullName, message, messageId);
                        CreateCommunication(fromPerson.PrimaryAliasId.Value, fromPerson.FullName, toPerson.PrimaryAliasId.Value, message, fromPhoneDv, messageId, rockContext);
                    }
                }
                else
                {
                    var    globalAttributes = GlobalAttributesCache.Get();
                    string organizationName = globalAttributes.GetValue("OrganizationName");

                    errorMessage = string.Format("Could not deliver message. This phone number is not registered in the {0} database.", organizationName);
                }
            }
        }
Ejemplo n.º 16
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>
        public override bool Execute(RockContext rockContext, WorkflowAction action, object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var actionType = action.ActionTypeCache;

            if (!action.LastProcessedDateTime.HasValue &&
                actionType != null &&
                actionType.WorkflowForm != null &&
                actionType.WorkflowForm.NotificationSystemEmailId.HasValue)
            {
                if (action.Activity != null && (action.Activity.AssignedPersonAliasId.HasValue || action.Activity.AssignedGroupId.HasValue))
                {
                    var recipients          = new List <RecipientData>();
                    var workflowMergeFields = GetMergeFields(action);

                    if (action.Activity.AssignedPersonAliasId.HasValue)
                    {
                        var person = new PersonAliasService(rockContext).Queryable()
                                     .Where(a => a.Id == action.Activity.AssignedPersonAliasId.Value)
                                     .Select(a => a.Person)
                                     .FirstOrDefault();

                        if (person != null && !string.IsNullOrWhiteSpace(person.Email))
                        {
                            recipients.Add(new RecipientData(person.Email, CombinePersonMergeFields(person, workflowMergeFields)));
                            action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName));
                        }
                    }

                    if (action.Activity.AssignedGroupId.HasValue)
                    {
                        var personList = new GroupMemberService(rockContext).GetByGroupId(action.Activity.AssignedGroupId.Value)
                                         .Where(m =>
                                                m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                m.Person.Email != "")
                                         .Select(m => m.Person)
                                         .ToList();

                        foreach (var person in personList)
                        {
                            recipients.Add(new RecipientData(person.Email, CombinePersonMergeFields(person, workflowMergeFields)));
                            action.AddLogEntry(string.Format("Form notification sent to '{0}'", person.FullName));
                        }
                    }

                    if (recipients.Count > 0)
                    {
                        // The email may need to reference activity Id, so we need to save here.
                        WorkflowService workflowService = new WorkflowService(rockContext);
                        workflowService.PersistImmediately(action);

                        var systemEmail = new SystemEmailService(rockContext).Get(action.ActionTypeCache.WorkflowForm.NotificationSystemEmailId.Value);
                        if (systemEmail != null)
                        {
                            var emailMessage = new RockEmailMessage(systemEmail);
                            emailMessage.SetRecipients(recipients);
                            emailMessage.CreateCommunicationRecord = false;
                            emailMessage.AppRoot = GlobalAttributesCache.Get().GetValue("InternalApplicationRoot") ?? string.Empty;
                            emailMessage.Send();
                        }
                        else
                        {
                            action.AddLogEntry("Could not find the selected notification system email", true);
                        }
                    }
                    else
                    {
                        action.AddLogEntry("Could not send form notification due to no assigned person or group member not having email address", true);
                    }
                }
                else
                {
                    action.AddLogEntry("Could not send form notification due to no assigned person or group", true);
                }
            }

            return(false);
        }
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>();

            // get person
            int?personId = null;

            string personAttributeValue = GetAttributeValue(action, "Person");
            Guid?  guidPersonAttribute  = personAttributeValue.AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Get(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null && attributePerson.FieldType.Class == "Rock.Field.Types.PersonFieldType")
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        Guid personAliasGuid = attributePersonValue.AsGuid();
                        if (!personAliasGuid.IsEmpty())
                        {
                            personId = new PersonAliasService(rockContext).Queryable()
                                       .Where(a => a.Guid.Equals(personAliasGuid))
                                       .Select(a => a.PersonId)
                                       .FirstOrDefault();
                            if (personId == null)
                            {
                                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
                                return(false);
                            }
                        }
                    }
                }
            }

            if (personId == null)
            {
                errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'.");
                return(false);
            }

            // determine the phone type to edit
            DefinedValueCache phoneType = null;
            var phoneTypeAttributeValue = action.GetWorklowAttributeValue(GetAttributeValue(action, "PhoneTypeAttribute").AsGuid());

            if (phoneTypeAttributeValue != null)
            {
                phoneType = DefinedValueCache.Get(phoneTypeAttributeValue.AsGuid());
            }
            if (phoneType == null)
            {
                phoneType = DefinedValueCache.Get(GetAttributeValue(action, "PhoneType").AsGuid());
            }
            if (phoneType == null)
            {
                errorMessages.Add("The phone type to be updated was not selected.");
                return(false);
            }

            // get the ignore blank setting
            var ignoreBlanks = GetActionAttributeValue(action, "IgnoreBlankValues").AsBoolean(true);

            // get the new phone number value
            string phoneNumberValue     = GetAttributeValue(action, "PhoneNumber");
            Guid?  phoneNumberValueGuid = phoneNumberValue.AsGuidOrNull();

            if (phoneNumberValueGuid.HasValue)
            {
                phoneNumberValue = action.GetWorklowAttributeValue(phoneNumberValueGuid.Value);
            }
            else
            {
                phoneNumberValue = phoneNumberValue.ResolveMergeFields(GetMergeFields(action));
            }
            phoneNumberValue = PhoneNumber.CleanNumber(phoneNumberValue);

            // 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.AsBooleanOrNull();

            // 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.AsBooleanOrNull();

            bool updated            = false;
            bool newPhoneNumber     = false;
            var  phoneNumberService = new PhoneNumberService(rockContext);
            var  phoneNumber        = phoneNumberService.Queryable()
                                      .Where(n =>
                                             n.PersonId == personId.Value &&
                                             n.NumberTypeValueId == phoneType.Id)
                                      .FirstOrDefault();
            string oldValue = string.Empty;

            if (phoneNumber == null)
            {
                phoneNumber = new PhoneNumber {
                    NumberTypeValueId = phoneType.Id, PersonId = personId.Value
                };
                newPhoneNumber = true;
                updated        = true;
            }
            else
            {
                oldValue = phoneNumber.NumberFormattedWithCountryCode;
            }

            if (!string.IsNullOrWhiteSpace(phoneNumberValue) || !ignoreBlanks)
            {
                updated            = updated || phoneNumber.Number != phoneNumberValue;
                phoneNumber.Number = phoneNumberValue;
            }
            if (unlisted.HasValue)
            {
                updated = updated || phoneNumber.IsUnlisted != unlisted.Value;
                phoneNumber.IsUnlisted = unlisted.Value;
            }
            if (smsEnabled.HasValue)
            {
                updated = updated || phoneNumber.IsMessagingEnabled != smsEnabled.Value;
                phoneNumber.IsMessagingEnabled = smsEnabled.Value;
            }

            if (updated)
            {
                if (oldValue != phoneNumber.NumberFormattedWithCountryCode)
                {
                    var changes = new History.HistoryChangeList();
                    changes.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, "Phone").SetSourceOfChange($"{action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow");
                    HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), personId.Value, changes, false);
                }

                if (phoneNumber.Number.IsNullOrWhiteSpace())
                {
                    if (!newPhoneNumber)
                    {
                        phoneNumberService.Delete(phoneNumber);
                    }
                }
                else
                {
                    if (newPhoneNumber)
                    {
                        phoneNumberService.Add(phoneNumber);
                    }
                }

                rockContext.SaveChanges();

                if (action.Activity != null && action.Activity.Workflow != null)
                {
                    var workflowType = action.Activity.Workflow.WorkflowTypeCache;
                    if (workflowType != null && workflowType.LoggingLevel == WorkflowLoggingLevel.Action)
                    {
                        var person = new PersonService(rockContext).Get(personId.Value);
                        action.AddLogEntry(string.Format("Updated {0} phone for {1} to {2}.", phoneType.Value, person.FullName, phoneNumber.NumberFormattedWithCountryCode));
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 18
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);

            int? fromId   = null;
            Guid?fromGuid = GetAttributeValue(action, "From").AsGuidOrNull();

            if (fromGuid.HasValue)
            {
                var fromValue = DefinedValueCache.Read(fromGuid.Value, rockContext);
                if (fromValue != null)
                {
                    fromId = fromValue.Id;
                }
            }

            var recipients = new List <RecipientData>();

            string toValue = GetAttributeValue(action, "To");
            Guid   guid    = toValue.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Read(guid, rockContext);
                if (attribute != null)
                {
                    string toAttributeValue = action.GetWorklowAttributeValue(guid);
                    if (!string.IsNullOrWhiteSpace(toAttributeValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        {
                            recipients.Add(new RecipientData(toAttributeValue));
                            break;
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toAttributeValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var phoneNumber = new PersonAliasService(rockContext).Queryable()
                                                  .Where(a => a.Guid.Equals(personAliasGuid))
                                                  .SelectMany(a => a.Person.PhoneNumbers)
                                                  .Where(p => p.IsMessagingEnabled)
                                                  .FirstOrDefault();

                                if (phoneNumber == null)
                                {
                                    action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true);
                                }
                                else
                                {
                                    string smsNumber = phoneNumber.Number;
                                    if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                    {
                                        smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                    }

                                    var recipient = new RecipientData(smsNumber);
                                    recipients.Add(recipient);

                                    var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid);
                                    if (person != null)
                                    {
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toAttributeValue.AsIntegerOrNull();
                            Guid?groupGuid = toAttributeValue.AsGuidOrNull();
                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }

                            // Handle situations where the attribute value stored is the Guid
                            else if (groupGuid.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true);
                            }

                            if (qry != null)
                            {
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    var phoneNumber = person.PhoneNumbers
                                                      .Where(p => p.IsMessagingEnabled)
                                                      .FirstOrDefault();
                                    if (phoneNumber != null)
                                    {
                                        string smsNumber = phoneNumber.Number;
                                        if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode))
                                        {
                                            smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number;
                                        }

                                        var recipient = new RecipientData(smsNumber);
                                        recipients.Add(recipient);
                                        recipient.MergeFields.Add("Person", person);
                                    }
                                }
                            }
                            break;
                        }
                        }
                    }
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(toValue))
                {
                    recipients.Add(new RecipientData(toValue.ResolveMergeFields(mergeFields)));
                }
            }

            string message     = GetAttributeValue(action, "Message");
            Guid   messageGuid = message.AsGuid();

            if (!messageGuid.IsEmpty())
            {
                var attribute = AttributeCache.Read(messageGuid, rockContext);
                if (attribute != null)
                {
                    string messageAttributeValue = action.GetWorklowAttributeValue(messageGuid);
                    if (!string.IsNullOrWhiteSpace(messageAttributeValue))
                    {
                        if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType")
                        {
                            message = messageAttributeValue;
                        }
                    }
                }
            }

            if (recipients.Any() && !string.IsNullOrWhiteSpace(message))
            {
                var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid(), rockContext);
                if (mediumEntity != null)
                {
                    var medium = MediumContainer.GetComponent(mediumEntity.Name);
                    if (medium != null && medium.IsActive)
                    {
                        var transport = medium.Transport;
                        if (transport != null && transport.IsActive)
                        {
                            var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot");

                            foreach (var recipient in recipients)
                            {
                                var recipientMergeFields = new Dictionary <string, object>(mergeFields);
                                foreach (var mergeField in recipient.MergeFields)
                                {
                                    recipientMergeFields.Add(mergeField.Key, mergeField.Value);
                                }
                                var mediumData = new Dictionary <string, string>();
                                mediumData.Add("FromValue", fromId.Value.ToString());
                                mediumData.Add("Message", message.ResolveMergeFields(recipientMergeFields));

                                var number = new List <string> {
                                    recipient.To
                                };

                                transport.Send(mediumData, number, appRoot, string.Empty);
                            }
                        }
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Gets either a delimited string of email addresses or a list of recipients from an attribute value.
        /// </summary>
        /// <param name="recipientType">The recipient type.</param>
        /// <param name="attributeValue">The attribute value.</param>
        /// <param name="action">The action.</param>
        /// <param name="mergeFields">The merge fields.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="delimitedEmails">The delimited emails.</param>
        /// <param name="recipientList">The recipient list.</param>
        /// <returns></returns>
        private bool GetEmailsFromAttributeValue(RecipientType recipientType, string attributeValue, WorkflowAction action, Dictionary <string, object> mergeFields, RockContext rockContext, out string delimitedEmails, out List <RockEmailMessageRecipient> recipientList)
        {
            delimitedEmails = null;
            recipientList   = null;

            Guid?guid = attributeValue.AsGuidOrNull();

            if (guid.HasValue)
            {
                var attribute = AttributeCache.Get(guid.Value, rockContext);
                if (attribute != null)
                {
                    var recipientTypePrefix   = string.Empty;
                    var groupRoleAttributeKey = AttributeKey.GroupRole;
                    switch (recipientType)
                    {
                    case RecipientType.CC:
                        recipientTypePrefix = "CC ";
                        break;

                    case RecipientType.BCC:
                        recipientTypePrefix = "BCC ";
                        break;
                    }

                    string toValue = action.GetWorkflowAttributeValue(guid.Value);
                    if (!string.IsNullOrWhiteSpace(toValue))
                    {
                        switch (attribute.FieldType.Class)
                        {
                        case "Rock.Field.Types.TextFieldType":
                        case "Rock.Field.Types.EmailFieldType":
                        {
                            delimitedEmails = toValue;
                            return(true);
                        }

                        case "Rock.Field.Types.PersonFieldType":
                        {
                            Guid personAliasGuid = toValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                var person = new PersonAliasService(rockContext).Queryable()
                                             .Where(a => a.Guid.Equals(personAliasGuid))
                                             .Select(a => a.Person)
                                             .FirstOrDefault();
                                if (person == null)
                                {
                                    action.AddLogEntry($"Invalid {recipientTypePrefix}Recipient: Person not found", true);
                                }
                                else if (string.IsNullOrWhiteSpace(person.Email))
                                {
                                    action.AddLogEntry($"{recipientTypePrefix}Email was not sent: Recipient does not have an email address", true);
                                }
                                else if (!person.IsEmailActive)
                                {
                                    action.AddLogEntry($"{recipientTypePrefix}Email was not sent: Recipient email is not active", true);
                                }
                                else if (person.EmailPreference == EmailPreference.DoNotEmail)
                                {
                                    action.AddLogEntry($"{recipientTypePrefix}Email was not sent: Recipient has requested 'Do Not Email'", true);
                                }
                                else
                                {
                                    var personDict = new Dictionary <string, object>(mergeFields)
                                    {
                                        { "Person", person }
                                    };

                                    recipientList = new List <RockEmailMessageRecipient> {
                                        new RockEmailMessageRecipient(person, personDict)
                                    };
                                    return(true);
                                }
                            }

                            return(false);
                        }

                        case "Rock.Field.Types.GroupFieldType":
                        case "Rock.Field.Types.SecurityRoleFieldType":
                        {
                            int? groupId   = toValue.AsIntegerOrNull();
                            Guid?groupGuid = toValue.AsGuidOrNull();

                            /*
                             * 2020-03-25 - JPH
                             *
                             * Per Jon, even though the user may select a Group or Security Role Attribute for the CC and BCC
                             * Attributes, we only want to allow Group Role filtering for the 'Send To Email Addresses' Attribute.
                             * Otherwise, the UI starts to become too overwhelming for the end user making the selections.
                             */
                            Guid?groupRoleValueGuid = recipientType == RecipientType.SendTo ?
                                                      GetGroupRoleValueGuid(action, groupRoleAttributeKey) :
                                                      null;

                            IQueryable <GroupMember> qry = null;

                            // Handle situations where the attribute value is the ID
                            if (groupId.HasValue)
                            {
                                qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value);
                            }
                            else if (groupGuid.HasValue)
                            {
                                // Handle situations where the attribute value stored is the Guid
                                qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value);
                            }
                            else
                            {
                                action.AddLogEntry($"Invalid {recipientTypePrefix}Recipient: No valid group id or Guid", true);
                            }

                            if (groupRoleValueGuid.HasValue)
                            {
                                qry = qry.Where(m => m.GroupRole != null && m.GroupRole.Guid.Equals(groupRoleValueGuid.Value));
                            }

                            if (qry != null)
                            {
                                recipientList = new List <RockEmailMessageRecipient>();
                                foreach (var person in qry
                                         .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active)
                                         .Select(m => m.Person))
                                {
                                    if (person.IsEmailActive &&
                                        person.EmailPreference != EmailPreference.DoNotEmail &&
                                        !string.IsNullOrWhiteSpace(person.Email))
                                    {
                                        var personDict = new Dictionary <string, object>(mergeFields)
                                        {
                                            { "Person", person }
                                        };

                                        recipientList.Add(new RockEmailMessageRecipient(person, personDict));
                                    }
                                }

                                return(true);
                            }

                            return(false);
                        }
                        }
                    }
                }
            }
            else if (!string.IsNullOrWhiteSpace(attributeValue))
            {
                delimitedEmails = attributeValue;
                return(true);
            }

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

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

            var groupAndRoleValues = (GetAttributeValue(action, "GroupAndRole") ?? string.Empty).Split('|');

            if (groupAndRoleValues.Count() > 1)
            {
                var groupGuid = groupAndRoleValues[1].AsGuidOrNull();
                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (groupAndRoleValues.Count() > 2)
                    {
                        var groupTypeRoleGuid = groupAndRoleValues[2].AsGuidOrNull();
                        if (groupTypeRoleGuid.HasValue)
                        {
                            var groupRole = new GroupTypeRoleService(rockContext).Get(groupTypeRoleGuid.Value);
                            if (groupRole != null)
                            {
                                groupRoleId = groupRole.Id;
                            }
                        }
                    }

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

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

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

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

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

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

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

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var groupMember        = new GroupMember();
                groupMember.PersonId          = person.Id;
                groupMember.GroupId           = group.Id;
                groupMember.GroupRoleId       = groupRoleId.Value;
                groupMember.GroupMemberStatus = this.GetAttributeValue(action, "GroupMemberStatus").ConvertToEnum <GroupMemberStatus>(GroupMemberStatus.Active);
                if (groupMember.IsValidGroupMember(rockContext))
                {
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();

                    if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
                    {
                        Rock.Security.Role.Flush(group.Id);
                    }
                }
                else
                {
                    // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

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

            return(true);
        }
Ejemplo n.º 21
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.º 22
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.º 23
0
        /// <summary>
        /// Gets the suggestions.
        /// </summary>
        /// <param name="followingSuggestionType">Type of the following suggestion.</param>
        /// <param name="followerPersonIds">The follower person ids.</param>
        /// <returns></returns>
        public override List <PersonEntitySuggestion> GetSuggestions(FollowingSuggestionType followingSuggestionType, List <int> followerPersonIds)
        {
            var  suggestions           = new List <PersonEntitySuggestion>();
            var  groupEntityType       = EntityTypeCache.Get(typeof(Rock.Model.Group));
            var  personAliasEntityType = EntityTypeCache.Get(typeof(Rock.Model.PersonAlias));
            bool isAutoFollow          = GetAttributeValue(followingSuggestionType, "AutoFollow").AsBoolean();

            // Get the grouptype guid
            Guid?groupTypeGuid = GetAttributeValue(followingSuggestionType, "GroupType").AsGuidOrNull();

            if (groupTypeGuid.HasValue)
            {
                using (var rockContext = new RockContext())
                {
                    var followingService   = new FollowingService(rockContext);
                    var groupMemberService = new GroupMemberService(rockContext);
                    var personAliasService = new PersonAliasService(rockContext);

                    var followings = followingService.Queryable()
                                     .Where(a => a.EntityTypeId == groupEntityType.Id &&
                                            followerPersonIds.Contains(a.PersonAlias.PersonId))
                                     .Select(f => new
                    {
                        f.PersonAliasId,
                        f.PersonAlias.PersonId,
                        f.EntityId
                    }).Distinct()
                                     .ToList();

                    var followedGroup = followings.Select(a => a.EntityId).Distinct().ToList();
                    // Get all the groupmember records of Followed group
                    var followedGroupMembersQry = groupMemberService.Queryable().AsNoTracking()
                                                  .Where(m =>
                                                         m.GroupMemberStatus == GroupMemberStatus.Active &&
                                                         m.Group != null &&
                                                         m.Group.IsActive && !m.Group.IsArchived &&
                                                         m.Group.GroupType.Guid.Equals(groupTypeGuid.Value) &&
                                                         followedGroup.Contains(m.GroupId));


                    // If a specific role for the people being followed was specified, limit the query to only those with the selected role
                    Guid?groupRoleGuid = GetAttributeValue(followingSuggestionType, "GroupRole").AsGuidOrNull();
                    if (groupRoleGuid.HasValue)
                    {
                        followedGroupMembersQry = followedGroupMembersQry.Where(m => m.GroupRole.Guid.Equals(groupRoleGuid.Value));
                    }

                    var followedGroupMembers = followedGroupMembersQry.ToList();

                    // Run the query to get all the groups that follower is a member of with selected filters
                    var followerPersonGroups = followings
                                               .Select(f => new
                    {
                        GroupMembers = followedGroupMembers.Where(a => a.GroupId == f.EntityId).ToList(),
                        f.PersonAliasId,
                        f.PersonId
                    })
                                               .ToList();

                    var followedMembersList = followedGroupMembers
                                              .Select(a => a.PersonId)
                                              .Distinct()
                                              .ToList();
                    // Build a dictionary of the personid->personaliasid
                    var personAliasIds = new Dictionary <int, int>();
                    personAliasService.Queryable().AsNoTracking()
                    .Where(a =>
                           followedMembersList.Contains(a.PersonId) &&
                           a.PersonId == a.AliasPersonId)
                    .ToList()
                    .ForEach(a => personAliasIds.AddOrIgnore(a.PersonId, a.Id));


                    // Loop through each follower/group combination
                    foreach (var followerPersonGroup in followerPersonGroups)
                    {
                        // Loop through the other people in that group
                        foreach (var member in followerPersonGroup.GroupMembers)
                        {
                            if (!isAutoFollow)
                            {
                                // add them to the list of suggestions
                                suggestions.Add(new PersonEntitySuggestion(followerPersonGroup.PersonId, personAliasIds[member.PersonId]));
                            }
                            else
                            {
                                // auto-add the follow
                                int followeePersonAliasId = personAliasIds[member.PersonId];

                                // if person is not already following the person
                                bool isFollowing = followingService.Queryable().Where(f =>
                                                                                      f.EntityTypeId == personAliasEntityType.Id &&
                                                                                      f.EntityId == followeePersonAliasId &&
                                                                                      f.PersonAliasId == followerPersonGroup.PersonAliasId).Any();
                                if (!isFollowing)
                                {
                                    var following = new Following();
                                    following.EntityTypeId  = personAliasEntityType.Id;
                                    following.EntityId      = followeePersonAliasId;
                                    following.PersonAliasId = followerPersonGroup.PersonAliasId;
                                    followingService.Add(following);
                                    rockContext.SaveChanges();
                                }
                            }
                        }
                    }
                }
            }

            return(suggestions);
        }
Ejemplo n.º 24
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 connection request
            ConnectionRequest request  = null;
            Guid connectionRequestGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionRequestAttribute").AsGuid()).AsGuid();

            request = new ConnectionRequestService(rockContext).Get(connectionRequestGuid);
            if (request == null)
            {
                errorMessages.Add("Invalid Connection Request Attribute or Value!");
                return(false);
            }

            // Get the activity type
            ConnectionActivityType activityType = null;
            Guid activityTypeGuid = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionActivityTypeAttribute").AsGuid()).AsGuid();

            activityType = new ConnectionActivityTypeService(rockContext).Get(activityTypeGuid);
            if (activityType == null)
            {
                errorMessages.Add("Invalid Connection Activity Type Attribute or Value!");
                return(false);
            }

            // Get the note
            string noteValue = GetAttributeValue(action, "Note");
            string note      = string.Empty;
            Guid?  noteGuid  = noteValue.AsGuidOrNull();

            if (noteGuid.HasValue)
            {
                var attribute = AttributeCache.Read(noteGuid.Value, rockContext);
                if (attribute != null)
                {
                    note = action.GetWorklowAttributeValue(noteGuid.Value);
                }
            }
            else
            {
                note = noteValue;
            }

            // Get the connector
            int? personAliasId       = null;
            Guid?personAttributeGuid = GetAttributeValue(action, "PersonAttribute").AsGuidOrNull();

            if (personAttributeGuid.HasValue)
            {
                Guid?personAliasGuid = action.GetWorklowAttributeValue(personAttributeGuid.Value).AsGuidOrNull();
                if (personAliasGuid.HasValue)
                {
                    var personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value);
                    if (personAlias != null)
                    {
                        personAliasId = personAlias.Id;
                    }
                }
            }

            // Add the activity
            var activity = new ConnectionRequestActivity();

            activity.ConnectionRequestId      = request.Id;
            activity.ConnectionActivityTypeId = activityType.Id;
            activity.ConnectionOpportunityId  = request.ConnectionOpportunityId;
            activity.ConnectorPersonAliasId   = personAliasId;
            activity.Note = note;
            new ConnectionRequestActivityService(rockContext).Add(activity);
            rockContext.SaveChanges();

            return(true);
        }
Ejemplo n.º 25
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.º 26
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)
            {
                Guid checkinGroupAttributeGuid = GetAttributeValue(action, "CheckinGroupAttribute").AsGuid();
                if (checkinGroupAttributeGuid == Guid.Empty)
                {
                    throw new Exception("CheckInGroupAttribute not set. Set attribute to continue.");
                }
                string checkinGroupAttributeKey = AttributeCache.Get(checkinGroupAttributeGuid).Key;

                string sessionAttributeKey = GetAttributeValue(action, "SessionAttributeKey");

                AttendanceCode attendanceCode = null;
                DateTime       startDateTime  = RockDateTime.Now;

                bool reuseCodeForFamily = checkInState.CheckInType != null && checkInState.CheckInType.ReuseSameCode;
                int  securityCodeLength = checkInState.CheckInType != null ? checkInState.CheckInType.SecurityCodeAlphaNumericLength : 3;

                AttendanceCodeService attendanceCodeService = new AttendanceCodeService(rockContext);
                AttendanceService     attendanceService     = new AttendanceService(rockContext);
                GroupMemberService    groupMemberService    = new GroupMemberService(rockContext);
                PersonAliasService    personAliasService    = new PersonAliasService(rockContext);
                GroupService          groupService          = new GroupService(rockContext);

                var family = checkInState.CheckIn.CurrentFamily;
                if (family != null)
                {
                    foreach (var person in family.GetPeople(true))
                    {
                        if (reuseCodeForFamily && attendanceCode != null)
                        {
                            person.SecurityCode = attendanceCode.Code;
                        }
                        else
                        {
                            attendanceCode      = AttendanceCodeService.GetNew(securityCodeLength);
                            person.SecurityCode = attendanceCode.Code;
                        }

                        foreach (var groupType in person.GetGroupTypes(true))
                        {
                            foreach (var group in groupType.GetGroups(true))
                            {
                                var referenceGroupGuid = group.Group.GetAttributeValue(checkinGroupAttributeKey).AsGuid();
                                var referenceGroup     = groupService.Get(referenceGroupGuid);
                                if (referenceGroup == null)
                                {
                                    group.Selected = false;
                                    continue;
                                }
                                GroupMember groupMember = groupMemberService.GetByGroupIdAndPersonId(referenceGroup.Id, person.Person.Id).FirstOrDefault();
                                if (groupMember == null)
                                {
                                    group.Selected = false;
                                    continue;
                                }
                                groupMember.LoadAttributes();
                                int sessions = groupMember.GetAttributeValue(sessionAttributeKey).AsInteger();

                                foreach (var location in group.GetLocations(true))
                                {
                                    foreach (var schedule in location.GetSchedules(true))
                                    {
                                        if (sessions == 0)
                                        {
                                            continue;
                                        }

                                        // Only create one attendance record per day for each person/schedule/group/location
                                        var attendance = attendanceService.Get(startDateTime, location.Location.Id, schedule.Schedule.Id, group.Group.Id, person.Person.Id);
                                        if (attendance == null)
                                        {
                                            var primaryAlias = personAliasService.GetPrimaryAlias(person.Person.Id);
                                            if (primaryAlias != null)
                                            {
                                                attendance = attendanceService.AddOrUpdate(primaryAlias.Id, startDateTime.Date, group.Group.Id,
                                                                                           location.Location.Id, schedule.Schedule.Id, location.CampusId,
                                                                                           checkInState.Kiosk.Device.Id, checkInState.CheckIn.SearchType.Id,
                                                                                           checkInState.CheckIn.SearchValue, family.Group.Id, attendanceCode.Id);

                                                attendanceService.Add(attendance);
                                            }

                                            //decrement sessions and save
                                            sessions--;
                                            groupMember.SetAttributeValue(sessionAttributeKey, sessions);
                                            groupMember.SaveAttributeValues();
                                        }
                                        else
                                        {
                                            foreach (var cPerson in checkInState.CheckIn.Families.SelectMany(f => f.People))
                                            {
                                                cPerson.Selected = false;
                                                cPerson.GroupTypes.ForEach(gt => gt.Selected = false);
                                            }
                                            return(true);
                                        }

                                        attendance.AttendanceCodeId = attendanceCode.Id;
                                        attendance.StartDateTime    = startDateTime;
                                        attendance.EndDateTime      = null;
                                        attendance.DidAttend        = true;

                                        KioskLocationAttendance.AddAttendance(attendance);
                                    }
                                }
                            }
                        }
                    }
                }

                rockContext.SaveChanges();
                return(true);
            }

            errorMessages.Add($"Attempted to run {this.GetType().GetFriendlyTypeName()} in check-in, but the check-in state was null.");
            return(false);
        }
Ejemplo n.º 27
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);

            // Get the connection request
            ConnectionRequest connectionRequest = null;
            Guid connectionRequestGuid          = action.GetWorklowAttributeValue(GetAttributeValue(action, "ConnectionRequestAttribute").AsGuid()).AsGuid();

            connectionRequest = new ConnectionRequestService(rockContext).Get(connectionRequestGuid);
            if (connectionRequest == null)
            {
                errorMessages.Add("Invalid Connection Request Attribute or Value!");
                return(false);
            }

            // Get the connector
            int? personAliasId       = null;
            Guid?personAttributeGuid = GetAttributeValue(action, "PersonAttribute").AsGuidOrNull();

            if (personAttributeGuid.HasValue)
            {
                Guid?personAliasGuid = action.GetWorklowAttributeValue(personAttributeGuid.Value).AsGuidOrNull();
                if (personAliasGuid.HasValue)
                {
                    var personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value);
                    if (personAlias != null)
                    {
                        personAliasId = personAlias.Id;
                    }
                }
                else
                {
                    errorMessages.Add("Invalid Person Attribute or Value!");
                    return(false);
                }
            }

            // Set the connector to the connection
            if (!connectionRequest.ConnectorPersonAliasId.HasValue || !GetAttributeValue(action, "Ignore").AsBoolean())
            {
                int?oldConnectorPersonAliasId = connectionRequest.ConnectorPersonAliasId;
                int?newConnectorPersonAliasId = personAliasId;

                connectionRequest.ConnectorPersonAliasId = newConnectorPersonAliasId;
                rockContext.SaveChanges();

                if (newConnectorPersonAliasId.HasValue && !newConnectorPersonAliasId.Equals(oldConnectorPersonAliasId))
                {
                    var guid = Rock.SystemGuid.ConnectionActivityType.ASSIGNED.AsGuid();
                    var assignedActivityId = new ConnectionActivityTypeService(rockContext).Queryable()
                                             .Where(t => t.Guid == guid)
                                             .Select(t => t.Id)
                                             .FirstOrDefault();
                    if (assignedActivityId > 0)
                    {
                        var connectionRequestActivityService = new ConnectionRequestActivityService(rockContext);
                        var connectionRequestActivity        = new ConnectionRequestActivity();
                        connectionRequestActivity.ConnectionRequestId      = connectionRequest.Id;
                        connectionRequestActivity.ConnectionOpportunityId  = connectionRequest.ConnectionOpportunityId;
                        connectionRequestActivity.ConnectionActivityTypeId = assignedActivityId;
                        connectionRequestActivity.ConnectorPersonAliasId   = newConnectorPersonAliasId;
                        connectionRequestActivityService.Add(connectionRequestActivity);
                        rockContext.SaveChanges();
                    }
                }
            }

            return(true);
        }
Ejemplo n.º 28
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>();

            if (entity != null && entity is IEntity)
            {
                Guid guid = GetAttributeValue(action, "Attribute").AsGuid();
                if (!guid.IsEmpty())
                {
                    var attribute = AttributeCache.Get(guid, rockContext);
                    if (attribute != null)
                    {
                        // If a lava template was specified, use that to set the attribute value
                        string lavaTemplate = GetAttributeValue(action, "LavaTemplate");
                        if (!string.IsNullOrWhiteSpace(lavaTemplate))
                        {
                            var mergeFields = GetMergeFields(action);
                            mergeFields.Add("Entity", entity);
                            string parsedValue = lavaTemplate.ResolveMergeFields(mergeFields);
                            SetWorkflowAttributeValue(action, guid, parsedValue);
                        }
                        else
                        {
                            // Person is handled special since it needs the person alias id
                            if (entity is Person && attribute.FieldTypeId == FieldTypeCache.Get(SystemGuid.FieldType.PERSON.AsGuid(), rockContext).Id)
                            {
                                var person = (Person)entity;

                                var primaryAlias = new PersonAliasService(rockContext).Queryable().FirstOrDefault(a => a.AliasPersonId == person.Id);
                                if (primaryAlias != null)
                                {
                                    SetWorkflowAttributeValue(action, guid, primaryAlias.Guid.ToString());
                                    return(true);
                                }
                                else
                                {
                                    errorMessages.Add("Person Entity: Could not determine person's primary alias. PersonId=" + person.Id);
                                }
                            }
                            else
                            {
                                if (GetAttributeValue(action, "UseId").AsBoolean())
                                {
                                    SetWorkflowAttributeValue(action, guid, ((IEntity)entity).Id.ToString());
                                }
                                else
                                {
                                    SetWorkflowAttributeValue(action, guid, ((IEntity)entity).Guid.ToString());
                                }
                            }
                        }

                        return(true);
                    }
                    else
                    {
                        errorMessages.Add("Unable to find the attribute from the attribute GUID=" + guid.ToStringSafe());
                    }
                }
                else
                {
                    errorMessages.Add("Unable to find the attribute GUID.");
                }
            }
            else
            {
                if (!GetAttributeValue(action, "EntityIsRequired").AsBoolean(true))
                {
                    return(true);
                }

                errorMessages.Add("No entity was specified or the entity is not a Rock Entity.");
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));
            return(false);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// logic to setup the groups location entry panel
        /// </summary>
        /// <param name="group">The group.</param>
        private void ConfigureGroupLocationControls(Group group)
        {
            var rockContext = new RockContext();

            ddlMember.Items.Clear();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        ShowSelectedPane();
                    }
                }
                else
                {
                    lContent.Text = "<div class='alert alert-warning'>This editor only allows editing groups with a single location.</div>";
                }
            }
        }
Ejemplo n.º 30
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)
        {
            /*
             * 2019-12-09 - ED
             * This activity will create a new assessment for each assessment type selected. If an assessment already exists for that type it is left in a pending status but a new assessment is still created.
             * Per Jon, code in Rock should account for the possibility of multiple assessments for a type that are in a pending state and only select the latest one.
             */

            rockContext = rockContext ?? new RockContext();

            errorMessages = new List <string>();

            var assessmentTypesGuidString = GetAttributeValue(action, AttributeKey.AssessmentTypesKey, true);
            var assessmentTypeGuids       = assessmentTypesGuidString.IsNullOrWhiteSpace() ? null : assessmentTypesGuidString.Split(new char[] { ',' });

            var  personAliasGuid      = GetAttributeValue(action, AttributeKey.Person, true).AsGuidOrNull();
            Guid?requestedByAliasGuid = GetAttributeValue(action, AttributeKey.RequestedBy, true).AsGuidOrNull();
            var  dueDate = GetAttributeValue(action, AttributeKey.DueDate, true).AsDateTime();

            // Validate attribute data
            if (!assessmentTypeGuids.Any())
            {
                errorMessages.Add("No Assessments selected.");
                return(false);
            }

            if (personAliasGuid == null)
            {
                errorMessages.Add("Invalid Person Attribute or Value.");
                return(false);
            }

            var personAlias = new PersonAliasService(rockContext).Get(personAliasGuid.Value);

            if (personAlias == null)
            {
                errorMessages.Add("Invalid Person Attribute or Value.");
                return(false);
            }

            PersonAlias requestedByAlias = null;

            if (requestedByAliasGuid != null)
            {
                requestedByAlias = new PersonAliasService(rockContext).Get(requestedByAliasGuid.Value);
            }

            foreach (string assessmentTypeGuid in assessmentTypeGuids)
            {
                var assessmentTypeService = new AssessmentTypeService(rockContext);
                int?assessmentTypeId      = assessmentTypeService.GetId(assessmentTypeGuid.AsGuid());

                if (assessmentTypeId == null)
                {
                    // This really shouldn't be able to happen, but let's not risk an NRE.
                    errorMessages.Add($"Invalid Assessment Type: {assessmentTypeGuid}");
                    continue;
                }

                // Create a new assessment
                var assessment = new Assessment
                {
                    PersonAliasId          = personAlias.Id,
                    AssessmentTypeId       = assessmentTypeId.Value,
                    RequesterPersonAliasId = requestedByAlias?.Id,
                    RequestedDateTime      = RockDateTime.Now,
                    RequestedDueDate       = dueDate,
                    Status = AssessmentRequestStatus.Pending
                };

                var assessmentService = new AssessmentService(rockContext);
                assessmentService.Add(assessment);
                rockContext.SaveChanges();
            }

            return(true);
        }