/// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            JobDataMap dataMap = context.JobDetail.JobDataMap;

            var groupTypeService = new GroupTypeService(new RockContext());

            groupTypes = new List <GroupType>(groupTypeService.GetByGuids(dataMap.Get("GroupTypes").ToString().Split(',').Select(Guid.Parse).ToList()));

            var requestDateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.Get("OccurrenceDateRange").ToString() ?? "-1||");

            startDate = ( DateTime )requestDateRange.Start;
            endDate   = ( DateTime )requestDateRange.End;

            if (groupTypes.IsNull() || groupTypes.Count == 0)
            {
                context.Result = "Job failed. Unable to find group role/type";
                throw new Exception("No group role/type found");
            }

            systemEmailGuid = dataMap.GetString("SystemEmail").AsGuid();

            SendEmailToCampusPastors();

            context.Result = string.Format("{0} emails sent", engagementEmailsSent);
            if (errorMessages.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", errorCount));
                errorMessages.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errors = sb.ToString();
                context.Result += errors;
                var         exception = new Exception(errors);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Executes the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public virtual void Execute(IJobExecutionContext context)
        {
            var dataMap                 = context.JobDetail.JobDataMap;
            var JobStartDateTime        = RockDateTime.Now;
            var systemCommunicationGuid = Guid.Empty;
            var groupTypes              = new List <int>();
            var groups      = new List <int>();
            var showAddress = dataMap.Get("ShowAddress").ToString().AsBoolean();
            var showAmount  = dataMap.Get("ShowAmount").ToString().AsBoolean();
            var sendZero    = dataMap.Get("SendEmailswithZeroDonations").ToString().AsBoolean();

            using (var rockContext = new RockContext())
            {
                // get the last run date or yesterday
                DateTime?lastStartDateTime = null;

                // get job type id
                int jobId = context.JobDetail.Description.AsInteger();

                // load job
                var job = new ServiceJobService(rockContext)
                          .GetNoTracking(jobId);

                if (job != null && job.Guid != Rock.SystemGuid.ServiceJob.JOB_PULSE.AsGuid())
                {
                    lastStartDateTime = job.LastRunDateTime?.AddSeconds(0.0d - ( double )job.LastRunDurationSeconds);
                }
                var beginDateTime = lastStartDateTime ?? JobStartDateTime.AddDays(-1);
                //beginDateTime = JobStartDateTime.AddDays( -3 );

                var groupTypeService   = new GroupTypeService(rockContext);
                var groupMemberService = new GroupMemberService(rockContext);
                var groupService       = new GroupService(rockContext);

                var selectedGroupTypes = dataMap.Get("GroupTypes").ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                if (selectedGroupTypes.Any())
                {
                    groupTypes = new List <int>(groupTypeService.GetByGuids(selectedGroupTypes.Select(Guid.Parse).ToList()).Select(gt => gt.Id));
                }

                var groupGuid = dataMap.Get("Group").ToString().AsGuidOrNull();

                if ((groupTypes.IsNull() || groupTypes.Count == 0) && !groupGuid.HasValue)
                {
                    context.Result = "Job failed. Unable to find group type or selected group. Check your settings.";
                    throw new Exception("No group type found or group found.");
                }
                Group groupSetting = null;
                if (groupGuid.HasValue)
                {
                    groupSetting = groupService.Get(groupGuid.Value);
                    groups       = groupService.GetAllDescendentGroupIds(groupSetting.Id, false);
                    groups.Add(groupSetting.Id);
                }

                systemCommunicationGuid = dataMap.GetString("SystemCommunication").AsGuid();

                var groupMembers = groupMemberService
                                   .Queryable("Group,Person").AsNoTracking()
                                   .Where(m =>
                                          m.GroupMemberStatus == GroupMemberStatus.Active &&
                                          (
                                              (groupGuid.HasValue && groups.Contains(m.GroupId)) ||
                                              (!groupGuid.HasValue && groupTypes.Contains(m.Group.GroupTypeId))
                                          ))
                                   .ToList();

                foreach (var groupMember in groupMembers)
                {
                    groupMember.LoadAttributes();
                    var email  = groupMember.Person.Email;
                    var person = groupMember.Person;
                    var group  = groupMember.Group;
                    group.LoadAttributes();
                    bool disablePublicContributionRequests = groupMember.GetAttributeValue("DisablePublicContributionRequests").AsBoolean();

                    // only show Contribution stuff if contribution requests haven't been disabled
                    if (email.IsNotNullOrWhiteSpace() && !disablePublicContributionRequests)
                    {
                        // Progress
                        var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>();

                        var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable()
                                                .Where(d => d.EntityTypeId == entityTypeIdGroupMember &&
                                                       d.EntityId == groupMember.Id)
                                                .Sum(a => ( decimal? )a.Amount) ?? 0.00M;

                        var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
                        if (!individualFundraisingGoal.HasValue)
                        {
                            individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull();
                        }

                        var amountLeft = individualFundraisingGoal - contributionTotal;
                        var percentMet = individualFundraisingGoal > 0 ? contributionTotal * 100 / individualFundraisingGoal : 100;

                        var financialTransactions = new FinancialTransactionDetailService(rockContext).Queryable()
                                                    .Where(d => d.EntityTypeId == entityTypeIdGroupMember &&
                                                           d.EntityId == groupMember.Id &&
                                                           d.Transaction.TransactionDateTime >= beginDateTime)
                                                    .OrderByDescending(a => a.Transaction.TransactionDateTime);

                        if (financialTransactions.Any() || sendZero)
                        {
                            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(null, groupMember.Person);
                            mergeFields.Add("BeginDateTime", beginDateTime);
                            mergeFields.Add("FundraisingGoal", individualFundraisingGoal);
                            mergeFields.Add("AmountLeft", amountLeft);
                            mergeFields.Add("ContributionTotal", contributionTotal);
                            mergeFields.Add("PercentMet", percentMet);
                            mergeFields.Add("ShowAddress", showAddress);
                            mergeFields.Add("ShowAmount", showAmount);
                            mergeFields.Add("GroupMember", groupMember);
                            mergeFields.Add("Contributions", financialTransactions);

                            //var queryParams = new Dictionary<string, string>();
                            //queryParams.Add( "GroupId", group.Id.ToString() );
                            //queryParams.Add( "GroupMemberId", groupMember.Id.ToString() );
                            //mergeFields.Add( "MakeDonationUrl", LinkedPageUrl( "DonationPage", queryParams ) );

                            //string makeDonationButtonText = null;
                            //makeDonationButtonText = "Make Payment";

                            //mergeFields.Add( "MakeDonationButtonText", makeDonationButtonText );

                            var recipients = new List <RockMessageRecipient>();
                            recipients.Add(new RockEmailMessageRecipient(person, mergeFields));

                            var emailMessage = new RockEmailMessage(systemCommunicationGuid);
                            emailMessage.SetRecipients(recipients);
                            var errors = new List <string>();
                            emailMessage.Send(out errors);

                            if (errors.Any())
                            {
                                errorCount += errors.Count;
                                errorMessages.AddRange(errors);
                            }
                            else
                            {
                                groupMemberEmails++;
                            }
                        }
                    }
                    else if (!disablePublicContributionRequests)
                    {
                        errorCount += 1;
                        errorMessages.Add(string.Format("No email specified for {0}.", groupMember.Person.FullName));
                    }
                }
            }
            context.Result = string.Format("{0} emails sent", groupMemberEmails);
            if (errorMessages.Any())
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine();
                sb.Append(string.Format("{0} Errors: ", errorCount));
                errorMessages.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                string errors = sb.ToString();
                context.Result += errors;
                var         exception = new Exception(errors);
                HttpContext context2  = HttpContext.Current;
                ExceptionLogService.LogException(exception, context2);
                throw exception;
            }
        }