Ejemplo n.º 1
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        private void ShowDetail(string itemKey, int itemKeyValue)
        {
            if (!itemKey.Equals("CommunicationId"))
            {
                return;
            }

            Rock.Model.Communication communication = null;

            if (!itemKeyValue.Equals(0))
            {
                communication              = new CommunicationService().Get(itemKeyValue);
                RockPage.PageTitle         = string.Format("Communication #{0}", communication.Id);
                this.AdditionalMergeFields = communication.AdditionalMergeFields.ToList();

                lTitle.Text = ("Subject: " + communication.Subject).FormatAsHtmlTitle();
            }
            else
            {
                communication = new Rock.Model.Communication()
                {
                    Status = CommunicationStatus.Transient
                };
                RockPage.PageTitle = "New Communication";
                lTitle.Text        = "New Communication".FormatAsHtmlTitle();
            }

            if (communication == null)
            {
                return;
            }

            ShowDetail(communication);
        }
Ejemplo n.º 2
0
        public void ConnectionRequestSendDateKeyWorksWithNullValue()
        {
            var communication = new Rock.Model.Communication();

            communication.SendDateTime = null;
            Assert.IsNull(communication.SendDateKey);
        }
        private void BuildCommunication(List <GroupMember> members)
        {
            members = members.Where(m => m.GroupMemberStatus == GroupMemberStatus.Active).ToList();
            if (!members.Any())
            {
                nbError.Text = "No members matched these filters.";
                return;
            }

            RockContext          rockContext          = new RockContext();
            CommunicationService communicationService = new CommunicationService(rockContext);
            var communication = new Rock.Model.Communication
            {
                IsBulkCommunication = true,
                Status = CommunicationStatus.Transient
            };

            foreach (var person in members.Select(m => m.Person).ToList())
            {
                communication.Recipients.Add(new CommunicationRecipient()
                {
                    PersonAliasId = person.PrimaryAliasId.Value
                });
            }

            communicationService.Add(communication);
            rockContext.SaveChanges();

            Response.Redirect("/Communication/" + communication.Id.ToString());
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Create and persist a new SMS Communication instance.
        /// </summary>
        /// <param name="dataContext"></param>
        /// <param name="guid"></param>
        /// <param name="communicationDateTime"></param>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <param name="openedDateTime"></param>
        /// <param name="senderPersonAliasGuid"></param>
        /// <param name="reviewerPersonAliasGuid"></param>
        /// <param name="smsSenderId"></param>
        /// <param name="isBulk"></param>
        /// <returns></returns>
        private Rock.Model.Communication CreateSmsCommunication(RockContext dataContext, string guid, DateTime?communicationDateTime, string title, string message, DateTime?openedDateTime, Guid senderPersonAliasGuid, Guid reviewerPersonAliasGuid, int smsSenderId, bool isBulk = false)
        {
            var personGuidToAliasIdMap = GetPersonGuidToAliasIdMap(dataContext);

            var communicationService = new CommunicationService(dataContext);

            var newSms = new Rock.Model.Communication();

            newSms.Guid = guid.AsGuid();
            newSms.CommunicationType     = CommunicationType.SMS;
            newSms.Subject               = title;
            newSms.Status                = CommunicationStatus.Approved;
            newSms.ReviewedDateTime      = communicationDateTime;
            newSms.ReviewerNote          = "Read and approved by the Communications Manager.";
            newSms.IsBulkCommunication   = isBulk;
            newSms.SenderPersonAliasId   = personGuidToAliasIdMap[senderPersonAliasGuid];
            newSms.ReviewerPersonAliasId = personGuidToAliasIdMap[reviewerPersonAliasGuid];
            newSms.SendDateTime          = communicationDateTime;
            newSms.SMSMessage            = message;

            newSms.SMSFromDefinedValueId = smsSenderId;

            newSms.CreatedDateTime        = communicationDateTime;
            newSms.CreatedByPersonAliasId = personGuidToAliasIdMap[senderPersonAliasGuid];

            newSms.ForeignKey = _TestDataSourceOfChange;

            communicationService.Add(newSms);

            dataContext.SaveChanges();

            return(newSms);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a new communication.
        /// </summary>
        /// <param name="fromPersonAliasId">From person alias identifier.</param>
        /// <param name="fromPersonName">Name of from person.</param>
        /// <param name="toPersonAliasId">To person alias identifier.</param>
        /// <param name="message">The message to send.</param>
        /// <param name="transportPhone">The transport phone.</param>
        /// <param name="responseCode">The reponseCode to use for tracking the conversation.</param>
        /// <param name="rockContext">A context to use for database calls.</param>
        private void CreateCommunication(int fromPersonAliasId, string fromPersonName, int toPersonAliasId, string message, string transportPhone, string responseCode, Rock.Data.RockContext rockContext)
        {
            // add communication for reply
            var communication = new Rock.Model.Communication();

            communication.IsBulkCommunication = false;
            communication.Status = CommunicationStatus.Approved;
            communication.SenderPersonAliasId = fromPersonAliasId;
            communication.Subject             = string.Format("From: {0}", fromPersonName);

            communication.SetMediumDataValue("Message", message);
            communication.SetMediumDataValue("FromValue", transportPhone);

            communication.MediumEntityTypeId = EntityTypeCache.Read("Rock.Communication.Medium.Sms").Id;

            var recipient = new Rock.Model.CommunicationRecipient();

            recipient.Status        = CommunicationRecipientStatus.Pending;
            recipient.PersonAliasId = toPersonAliasId;
            recipient.ResponseCode  = responseCode;
            communication.Recipients.Add(recipient);

            var communicationService = new Rock.Model.CommunicationService(rockContext);

            communicationService.Add(communication);
            rockContext.SaveChanges();

            // queue the sending
            var transaction = new Rock.Transactions.SendCommunicationTransaction();

            transaction.CommunicationId = communication.Id;
            transaction.PersonAlias     = null;
            Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="communication">The communication.</param>
        private void ShowDetail(Rock.Model.Communication communication)
        {
            CommunicationId = communication.Id;

            lStatus.Visible          = communication.Status != CommunicationStatus.Transient;
            lRecipientStatus.Visible = communication.Status != CommunicationStatus.Transient;

            lStatus.Text = string.Format("<span class='label label-communicationstatus-{0}'>{1}</span>", communication.Status.ConvertToString().ToLower().Replace(" ", ""), communication.Status.ConvertToString());

            ChannelEntityTypeId = communication.ChannelEntityTypeId;
            BindChannels();

            Recipients.Clear();
            communication.Recipients.ToList().ForEach(r => Recipients.Add(new Recipient(r.Person.Id, r.Person.FullName, r.Status)));
            BindRecipients();

            ChannelData = communication.ChannelData;
            ChannelData.Add("Subject", communication.Subject);

            ChannelControl control = LoadChannelControl(true);

            if (control != null && CurrentPerson != null)
            {
                control.InitializeFromSender(CurrentPerson);
            }

            dtpFutureSend.SelectedDateTime = communication.FutureSendDateTime;

            ShowActions(communication);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        private void ShowDetail(Rock.Model.Communication communication)
        {
            ShowStatus(communication);
            lTitle.Text = (communication.Name ?? communication.Subject ?? "Communication").FormatAsHtmlTitle();
            pdAuditDetails.SetEntity(communication, ResolveRockUrl("~"));

            SetPersonDateValue(lCreatedBy, communication.CreatedByPersonAlias, communication.CreatedDateTime, "Created By");
            SetPersonDateValue(lApprovedBy, communication.ReviewerPersonAlias, communication.ReviewedDateTime, "Approved By");

            if (communication.FutureSendDateTime.HasValue && communication.FutureSendDateTime.Value > RockDateTime.Now)
            {
                lFutureSend.Text = String.Format("<div class='alert alert-success'><strong>Future Send</strong> This communication is scheduled to be sent {0} <small>({1})</small>.</div>", communication.FutureSendDateTime.Value.ToRelativeDateString(), communication.FutureSendDateTime.Value.ToString());
            }

            pnlOpened.Visible = false;

            lDetails.Text = GetMediumData(communication);
            if (communication.UrlReferrer.IsNotNullOrWhitespace())
            {
                lDetails.Text += string.Format("<small>Originated from <a href='{0}'>this page</a></small>", communication.UrlReferrer);
            }

            BindRecipients();

            BindInteractions();

            ShowActions(communication);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Handles the Click event of the btnTest control and sends a test communication to the
        /// current person if they have an email address on their record.
        /// </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 btnTest_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CurrentPerson != null)
            {
                SetActionButtons(resetToSend: true);

                if (string.IsNullOrWhiteSpace(CurrentPerson.Email))
                {
                    nbError.Text    = "A test email cannot be sent because you do not have an email address.";
                    nbError.Visible = true;
                    return;
                }

                // Get existing or new communication record
                var communication = GetCommunication(new RockContext(), null);

                if (communication != null && CurrentPersonAliasId.HasValue)
                {
                    // Using a new context (so that changes in the UpdateCommunication() are not persisted )
                    var testCommunication = new Rock.Model.Communication();
                    testCommunication.SenderPersonAliasId       = communication.SenderPersonAliasId;
                    testCommunication.Subject                   = communication.Subject;
                    testCommunication.IsBulkCommunication       = communication.IsBulkCommunication;
                    testCommunication.MediumEntityTypeId        = communication.MediumEntityTypeId;
                    testCommunication.MediumDataJson            = communication.MediumDataJson;
                    testCommunication.AdditionalMergeFieldsJson = communication.AdditionalMergeFieldsJson;

                    testCommunication.FutureSendDateTime    = null;
                    testCommunication.Status                = CommunicationStatus.Approved;
                    testCommunication.ReviewedDateTime      = RockDateTime.Now;
                    testCommunication.ReviewerPersonAliasId = CurrentPersonAliasId.Value;

                    var testRecipient = new CommunicationRecipient();
                    if (communication.Recipients.Any())
                    {
                        var recipient = communication.Recipients.FirstOrDefault();
                        testRecipient.AdditionalMergeValuesJson = recipient.AdditionalMergeValuesJson;
                    }
                    testRecipient.Status        = CommunicationRecipientStatus.Pending;
                    testRecipient.PersonAliasId = CurrentPersonAliasId.Value;
                    testCommunication.Recipients.Add(testRecipient);

                    var rockContext          = new RockContext();
                    var communicationService = new CommunicationService(rockContext);
                    communicationService.Add(testCommunication);
                    rockContext.SaveChanges();

                    var medium = testCommunication.Medium;
                    if (medium != null)
                    {
                        medium.Send(testCommunication);
                    }

                    communicationService.Delete(testCommunication);
                    rockContext.SaveChanges();

                    nbTestResult.Visible = true;
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Create and persist a new Email Communication instance.
        /// </summary>
        /// <param name="dataContext"></param>
        /// <param name="guid"></param>
        /// <param name="communicationDateTime"></param>
        /// <param name="subject"></param>
        /// <param name="message"></param>
        /// <param name="openedDateTime"></param>
        /// <param name="senderPersonAliasGuid"></param>
        /// <param name="reviewerPersonAliasGuid"></param>
        /// <param name="isBulk"></param>
        /// <returns></returns>
        private Rock.Model.Communication CreateEmailCommunication(RockContext dataContext, string guid, DateTime?communicationDateTime, string subject, string message, DateTime?openedDateTime, Guid senderPersonAliasGuid, Guid reviewerPersonAliasGuid, bool isBulk = false)
        {
            var personGuidToAliasIdMap = GetPersonGuidToAliasIdMap(dataContext);

            var communicationService = new CommunicationService(dataContext);

            var newEmail = new Rock.Model.Communication();

            newEmail.Guid = guid.AsGuid();
            newEmail.CommunicationType     = CommunicationType.Email;
            newEmail.Subject               = subject;
            newEmail.Status                = CommunicationStatus.Approved;
            newEmail.ReviewedDateTime      = communicationDateTime;
            newEmail.ReviewerNote          = "Read and approved by the Communications Manager.";
            newEmail.IsBulkCommunication   = isBulk;
            newEmail.SenderPersonAliasId   = personGuidToAliasIdMap[senderPersonAliasGuid];
            newEmail.ReviewerPersonAliasId = personGuidToAliasIdMap[reviewerPersonAliasGuid];
            newEmail.SendDateTime          = communicationDateTime;
            newEmail.Message               = message;

            newEmail.CreatedDateTime        = communicationDateTime;
            newEmail.CreatedByPersonAliasId = personGuidToAliasIdMap[senderPersonAliasGuid];

            newEmail.ForeignKey = _TestDataSourceOfChange;

            communicationService.Add(newEmail);

            dataContext.SaveChanges();

            return(newEmail);
        }
        /// <summary>
        /// Sets up a communication model with the user-entered values
        /// </summary>
        /// <returns>The communication for this session.</returns>
        private Rock.Model.Communication SetupCommunication()
        {
            var communication = new Rock.Model.Communication
            {
                Status                = CommunicationStatus.Approved,
                ReviewedDateTime      = RockDateTime.Now,
                ReviewerPersonAliasId = CurrentPersonAliasId,
                SenderPersonAliasId   = CurrentPersonAliasId,
                CommunicationType     = CommunicationType.PushNotification
            };

            communication.EnabledLavaCommands     = GetAttributeValue(AttributeKey.EnabledLavaCommands);
            communication.CommunicationTemplateId = hfSelectedCommunicationTemplateId.Value.AsIntegerOrNull();

            var communicationData       = new CommunicationDetails();
            var pushNotificationControl = phPushControl.Controls[0] as PushNotification;

            if (pushNotificationControl != null)
            {
                pushNotificationControl.UpdateCommunication(communicationData);
            }

            CommunicationDetails.Copy(communicationData, communication);

            return(communication);
        }
        private Dictionary <string, string> CreateCommunication(List <PersonAlias> personAliases, RockContext rockContext = null)
        {
            if (rockContext == null)
            {
                rockContext = new RockContext();
            }
            var service       = new CommunicationService(rockContext);
            var communication = new Rock.Model.Communication();

            communication.IsBulkCommunication = false;
            communication.Status = CommunicationStatus.Transient;

            communication.SenderPersonAliasId = CurrentPersonAliasId;

            service.Add(communication);


            // Get the primary aliases
            foreach (var personAlias in personAliases)
            {
                var recipient = new CommunicationRecipient();
                recipient.PersonAliasId = personAlias.Id;
                communication.Recipients.Add(recipient);
            }

            rockContext.SaveChanges();

            var queryParameters = new Dictionary <string, string>();

            queryParameters.Add("CommunicationId", communication.Id.ToString());

            return(queryParameters);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Sends the specified communication.
        /// </summary>
        /// <param name="communication">The communication.</param>
        public virtual void Send(Rock.Model.Communication communication)
        {
            var transport = Transport;

            if (transport != null)
            {
                transport.Send(communication);
            }
        }
Ejemplo n.º 13
0
        private Rock.Model.Communication BuildCommunication(RockContext rockContext, DateTime requestDate)
        {
            var communication = new Rock.Model.Communication();

            communication.ForeignKey   = communicationForeignKey;
            communication.SendDateTime = requestDate;

            return(communication);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        private void ShowDetail()
        {
            Rock.Model.Communication communication = null;

            if (CommunicationId.HasValue)
            {
                communication = new CommunicationService(new RockContext())
                                .Queryable("CreatedByPersonAlias.Person")
                                .Where(c => c.Id == CommunicationId.Value)
                                .FirstOrDefault();
            }

            // If not valid for this block, hide contents and return
            if (communication == null ||
                communication.Status == CommunicationStatus.Transient ||
                communication.Status == CommunicationStatus.Draft)
            {
                // If viewing a new, transient or draft communication, hide this block and use NewCommunication block
                this.Visible = false;
                return;
            }

            ShowStatus(communication);
            lTitle.Text = (communication.Subject ?? "Communication").FormatAsHtmlTitle();

            SetPersonDateValue(lCreatedBy, communication.CreatedByPersonAlias, communication.CreatedDateTime, "Created By");
            SetPersonDateValue(lApprovedBy, communication.Reviewer, communication.ReviewedDateTime, "Approved By");

            if (communication.FutureSendDateTime.HasValue && communication.FutureSendDateTime.Value > RockDateTime.Now)
            {
                lFutureSend.Text = String.Format("<div class='alert alert-success'><strong>Future Send</strong> This communication is scheduled to be sent {0} <small>({1})</small>.</div>", communication.FutureSendDateTime.Value.ToRelativeDateString(), communication.FutureSendDateTime.Value.ToString());
            }

            pnlOpened.Visible = false;

            lDetails.Text = communication.ChannelDataJson;
            if (communication.ChannelEntityTypeId.HasValue)
            {
                var channelEntityType = EntityTypeCache.Read(communication.ChannelEntityTypeId.Value);
                if (channelEntityType != null)
                {
                    var channel = ChannelContainer.GetComponent(channelEntityType.Name);
                    if (channel != null)
                    {
                        pnlOpened.Visible = channel.Transport.CanTrackOpens;
                        lDetails.Text     = channel.GetMessageDetails(communication);
                    }
                }
            }

            BindRecipients();

            BindActivity();

            ShowActions(communication);
        }
        private static List <Rock.Model.Communication> CreateCommunications(int sender, CommunicationStatus communicationStatus, DateTime?reviewedDateTime, DateTime?futureSendDateTime, bool AddPendingRecipient, int?listGroupId)
        {
            // Create communication with no recipients.
            var communicationNoReciepients = new Rock.Model.Communication
            {
                Name = $"Test Communication {Guid.NewGuid()}",
                FutureSendDateTime  = futureSendDateTime,
                ListGroupId         = listGroupId,
                Message             = $"Test Communication {Guid.NewGuid()}",
                Subject             = $"Test Communication {Guid.NewGuid()}",
                FromEmail           = "*****@*****.**",
                CommunicationType   = CommunicationType.Email,
                SenderPersonAliasId = sender,
                IsBulkCommunication = false,
                Status           = communicationStatus,
                ReviewedDateTime = reviewedDateTime
            };

            // Create communication with recipients.
            var communicationReciepients = new Rock.Model.Communication
            {
                Name = $"Test Communication {Guid.NewGuid()}",
                FutureSendDateTime  = futureSendDateTime,
                ListGroupId         = listGroupId,
                Message             = $"Test Communication {Guid.NewGuid()}",
                Subject             = $"Test Communication {Guid.NewGuid()}",
                FromEmail           = "*****@*****.**",
                CommunicationType   = CommunicationType.Email,
                SenderPersonAliasId = sender,
                IsBulkCommunication = false,
                Status           = communicationStatus,
                ReviewedDateTime = reviewedDateTime
            };

            foreach (CommunicationRecipientStatus communicationRecipientStatus in Enum.GetValues(typeof(CommunicationRecipientStatus)))
            {
                if (!AddPendingRecipient && communicationRecipientStatus == CommunicationRecipientStatus.Pending)
                {
                    continue;
                }
                communicationReciepients.Recipients.Add(new CommunicationRecipient
                {
                    Status             = communicationRecipientStatus,
                    PersonAliasId      = GetNewPersonAlias(),
                    MediumEntityTypeId = EntityTypeCache.GetId(SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL)
                });
            }

            return(new List <Rock.Model.Communication>
            {
                communicationNoReciepients,
                communicationReciepients
            });
        }
Ejemplo n.º 16
0
        public void CommunicationSendDateKeyGetsSetCorrectly()
        {
            var testList = TestDataHelper.GetAnalyticsSourceDateTestData();

            foreach (var keyValue in testList)
            {
                var communication = new Rock.Model.Communication();
                communication.SendDateTime = keyValue.Value;
                Assert.AreEqual(keyValue.Key, communication.SendDateKey);
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Shows the actions.
        /// </summary>
        /// <param name="communication">The communication.</param>
        private void ShowActions(Rock.Model.Communication communication)
        {
            bool canApprove = IsUserAuthorized("Approve");

            // Set default visibility
            btnApprove.Visible = false;
            btnDeny.Visible    = false;
            btnEdit.Visible    = false;
            btnCancel.Visible  = false;
            btnCopy.Visible    = false;

            if (communication != null)
            {
                switch (communication.Status)
                {
                case CommunicationStatus.Transient:
                case CommunicationStatus.Draft:
                case CommunicationStatus.Denied:
                {
                    // This block isn't used for transient, draft or denied communications
                    break;
                }

                case CommunicationStatus.PendingApproval:
                {
                    if (canApprove)
                    {
                        btnApprove.Visible = true;
                        btnDeny.Visible    = true;
                        btnEdit.Visible    = true;
                    }
                    btnCancel.Visible = communication.IsAuthorized(Rock.Security.Authorization.EDIT, CurrentPerson);
                    break;
                }

                case CommunicationStatus.Approved:
                {
                    // If there are still any pending recipients, allow canceling of send
                    var hasPendingRecipients = new CommunicationRecipientService(new RockContext()).Queryable()
                                               .Where(r => r.CommunicationId == communication.Id).Where(r => r.Status == CommunicationRecipientStatus.Pending).Any();


                    btnCancel.Visible = hasPendingRecipients;

                    // Allow then to create a copy if they have VIEW (don't require full EDIT auth)
                    btnCopy.Visible = communication.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson);
                    break;
                }
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Handles the Click event of the btnSubmit 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 btnTest_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CurrentPersonAliasId.HasValue)
            {
                // Get existing or new communication record
                var communication = UpdateCommunication(new RockContext());

                if (communication != null)
                {
                    // Using a new context (so that changes in the UpdateCommunication() are not persisted )
                    var testCommunication = new Rock.Model.Communication();
                    testCommunication.SenderPersonAliasId       = communication.SenderPersonAliasId;
                    testCommunication.Subject                   = communication.Subject;
                    testCommunication.IsBulkCommunication       = communication.IsBulkCommunication;
                    testCommunication.MediumEntityTypeId        = communication.MediumEntityTypeId;
                    testCommunication.MediumDataJson            = communication.MediumDataJson;
                    testCommunication.AdditionalMergeFieldsJson = communication.AdditionalMergeFieldsJson;

                    testCommunication.FutureSendDateTime    = null;
                    testCommunication.Status                = CommunicationStatus.Approved;
                    testCommunication.ReviewedDateTime      = RockDateTime.Now;
                    testCommunication.ReviewerPersonAliasId = CurrentPersonAliasId;

                    var testRecipient = new CommunicationRecipient();
                    if (communication.Recipients.Any())
                    {
                        var recipient = communication.Recipients.FirstOrDefault();
                        testRecipient.AdditionalMergeValuesJson = recipient.AdditionalMergeValuesJson;
                    }
                    testRecipient.Status        = CommunicationRecipientStatus.Pending;
                    testRecipient.PersonAliasId = CurrentPersonAliasId.Value;
                    testCommunication.Recipients.Add(testRecipient);

                    var rockContext          = new RockContext();
                    var communicationService = new CommunicationService(rockContext);
                    communicationService.Add(testCommunication);
                    rockContext.SaveChanges();

                    var medium = testCommunication.Medium;
                    if (medium != null)
                    {
                        medium.Send(testCommunication);
                    }

                    communicationService.Delete(testCommunication);
                    rockContext.SaveChanges();

                    nbTestResult.Visible = true;
                }
            }
        }
        /// <summary>
        /// Gets the communication.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="peopleIds">The people ids.</param>
        /// <returns></returns>
        private Rock.Model.Communication GetCommunication(RockContext rockContext, List <int> peopleIds)
        {
            var communicationService = new CommunicationService(rockContext);
            var recipientService     = new CommunicationRecipientService(rockContext);

            if (GetTemplateData())
            {
                Rock.Model.Communication communication = new Rock.Model.Communication();
                communication.Status = CommunicationStatus.Transient;
                communication.SenderPersonAliasId = CurrentPersonAliasId;
                communicationService.Add(communication);
                communication.IsBulkCommunication = true;
                communication.MediumEntityTypeId  = EntityTypeCache.Read("Rock.Communication.Medium.Email").Id;
                communication.FutureSendDateTime  = null;

                // add each person as a recipient to the communication
                if (peopleIds != null)
                {
                    foreach (var personId in peopleIds)
                    {
                        if (!communication.Recipients.Any(r => r.PersonAlias.PersonId == personId))
                        {
                            var communicationRecipient = new CommunicationRecipient();
                            communicationRecipient.PersonAlias = new PersonAliasService(rockContext).GetPrimaryAlias(personId);
                            communication.Recipients.Add(communicationRecipient);
                        }
                    }
                }

                // add the MediumData to the communication
                communication.MediumData.Clear();
                foreach (var keyVal in MediumData)
                {
                    if (!string.IsNullOrEmpty(keyVal.Value))
                    {
                        communication.MediumData.Add(keyVal.Key, keyVal.Value);
                    }
                }

                if (communication.MediumData.ContainsKey("Subject"))
                {
                    communication.Subject = communication.MediumData["Subject"];
                    communication.MediumData.Remove("Subject");
                }

                return(communication);
            }

            return(null);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Shows the result.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="communication">The communication.</param>
        private void ShowResult(string message, Rock.Model.Communication communication)
        {
            ShowStatus(communication);

            pnlEdit.Visible = false;

            nbResult.Text = message;

            CurrentPageReference.Parameters.AddOrReplace("CommunicationId", communication.Id.ToString());
            hlViewCommunication.NavigateUrl = CurrentPageReference.BuildUrl();
            hlViewCommunication.Visible     = this.Page.ControlsOfTypeRecursive <RockWeb.Blocks.Communication.CommunicationDetail>().Any();

            pnlResult.Visible = true;
        }
        /// <summary>
        /// Populates the communication with recipients from the personal device identifiers.
        /// </summary>
        /// <param name="communication">The communication.</param>
        /// <param name="personalDeviceIds">The personal device ids.</param>
        private void PopulateCommunicationRecipients(Rock.Model.Communication communication, IEnumerable <int> personalDeviceIds)
        {
            foreach (var personalDeviceId in personalDeviceIds)
            {
                var testRecipient = new CommunicationRecipient
                {
                    Status             = CommunicationRecipientStatus.Pending,
                    PersonalDeviceId   = personalDeviceId,
                    MediumEntityTypeId = _pushMediumId
                };

                communication.Recipients.Add(testRecipient);
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Processes the text body.
        /// </summary>
        /// <param name="communication">The communication.</param>
        /// <param name="globalAttributes">The global attributes.</param>
        /// <param name="mergeObjects">The merge objects.</param>
        /// <param name="currentPersonOverride">The current person override.</param>
        /// <returns></returns>
        public static string ProcessTextBody(Rock.Model.Communication communication,
                                             Rock.Web.Cache.GlobalAttributesCache globalAttributes,
                                             Dictionary <string, object> mergeObjects,
                                             Person currentPersonOverride = null)
        {
            string defaultPlainText = communication.GetMediumDataValue("DefaultPlainText");
            string plainTextBody    = communication.GetMediumDataValue("TextMessage");

            if (string.IsNullOrWhiteSpace(plainTextBody) && !string.IsNullOrWhiteSpace(defaultPlainText))
            {
                plainTextBody = defaultPlainText;
            }

            return(plainTextBody.ResolveMergeFields(mergeObjects, currentPersonOverride, communication.EnabledLavaCommands));
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Shows the actions.
        /// </summary>
        /// <param name="communication">The communication.</param>
        private void ShowActions(Rock.Model.Communication communication)
        {
            bool canApprove = IsUserAuthorized("Approve");

            // Set default visibility
            btnApprove.Visible = false;
            btnDeny.Visible    = false;
            btnEdit.Visible    = false;
            btnCancel.Visible  = false;
            btnCopy.Visible    = false;

            if (communication != null)
            {
                switch (communication.Status)
                {
                case CommunicationStatus.Transient:
                case CommunicationStatus.Draft:
                case CommunicationStatus.Denied:
                {
                    // This block isn't used for transient, draft or denied communicaitons
                    break;
                }

                case CommunicationStatus.PendingApproval:
                {
                    if (canApprove)
                    {
                        btnApprove.Visible = true;
                        btnDeny.Visible    = true;
                        btnEdit.Visible    = true;
                    }
                    btnCancel.Visible = true;
                    break;
                }

                case CommunicationStatus.Approved:
                {
                    // If there are still any pending recipients, allow canceling of send
                    btnCancel.Visible = communication.Recipients
                                        .Where(r => r.Status == CommunicationRecipientStatus.Pending)
                                        .Any();

                    btnCopy.Visible = true;
                    break;
                }
                }
            }
        }
Ejemplo n.º 24
0
        private void SendTextMessage(List <Person> smsRecipients, Dictionary <string, object> mergeFields)
        {
            var rockContext                   = new RockContext();
            var communicationService          = new CommunicationService(rockContext);
            var communicationRecipientService = new CommunicationRecipientService(rockContext);

            var communication = new Rock.Model.Communication();

            communication.Status = CommunicationStatus.Approved;
            communication.SenderPersonAliasId = CurrentPerson.PrimaryAliasId;
            communicationService.Add(communication);
            communication.EnabledLavaCommands = GetAttributeValue("EnabledLavaCommands");
            communication.IsBulkCommunication = false;
            communication.CommunicationType   = CommunicationType.SMS;
            communication.ListGroup           = null;
            communication.ListGroupId         = null;
            communication.ExcludeDuplicateRecipientAddress = true;
            communication.CommunicationTemplateId          = null;
            communication.FromName  = mergeFields["FromName"].ToString().TrimForMaxLength(communication, "FromName");
            communication.FromEmail = mergeFields["FromEmail"].ToString().TrimForMaxLength(communication, "FromEmail");
            communication.Subject   = GetAttributeValue("Subject");
            communication.Message   = GetAttributeValue("MessageBody");

            communication.SMSFromDefinedValueId = DefinedValueCache.GetId(GetAttributeValue("SMSFromNumber").AsGuid());
            communication.SMSMessage            = GetAttributeValue("SMSMessageBody");
            communication.FutureSendDateTime    = null;

            communicationService.Add(communication);

            rockContext.SaveChanges();

            foreach (var smsPerson in smsRecipients)
            {
                communication.Recipients.Add(new CommunicationRecipient()
                {
                    PersonAliasId         = smsPerson.PrimaryAliasId,
                    MediumEntityTypeId    = EntityTypeCache.Get(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid()).Id,
                    AdditionalMergeValues = mergeFields
                });
            }
            rockContext.SaveChanges();

            var transaction = new Rock.Transactions.SendCommunicationTransaction();

            transaction.CommunicationId = communication.Id;
            transaction.PersonAlias     = CurrentPersonAlias;
            Rock.Transactions.RockQueue.TransactionQueue.Enqueue(transaction);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Creates the communication to the recipient's mobile device with attachments.
        /// </summary>
        /// <param name="fromPerson">From person.</param>
        /// <param name="toPersonAliasId">To person alias identifier.</param>
        /// <param name="message">The message.</param>
        /// <param name="fromPhone">From phone.</param>
        /// <param name="responseCode">The response code.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="attachments">The attachments.</param>
        public static void CreateCommunicationMobile(Person fromPerson, int?toPersonAliasId, string message, DefinedValueCache fromPhone, string responseCode, Rock.Data.RockContext rockContext, List <BinaryFile> attachments)
        {
            // NOTE: fromPerson should never be null since a Nameless Person record should have been created if a regular person record wasn't found
            string communicationName = fromPerson != null?string.Format("From: {0}", fromPerson.FullName) : "From: unknown person";

            var communicationService = new CommunicationService(rockContext);

            var createSMSCommunicationArgs = new CommunicationService.CreateSMSCommunicationArgs
            {
                FromPerson            = fromPerson,
                ToPersonAliasId       = toPersonAliasId,
                Message               = message,
                FromPhone             = fromPhone,
                CommunicationName     = communicationName,
                ResponseCode          = responseCode,
                SystemCommunicationId = null,
            };

            Rock.Model.Communication communication = communicationService.CreateSMSCommunication(createSMSCommunicationArgs);

            rockContext.SaveChanges();

            // Now that we have a communication ID we can add the attachments
            if (attachments != null && attachments.Any())
            {
                foreach (var attachment in attachments)
                {
                    var communicationAttachment = new CommunicationAttachment
                    {
                        BinaryFileId      = attachment.Id,
                        CommunicationId   = communication.Id,
                        CommunicationType = CommunicationType.SMS
                    };

                    communication.AddAttachment(communicationAttachment, CommunicationType.SMS);
                }

                rockContext.SaveChanges();
            }

            // queue the sending
            var transaction = new ProcessSendCommunication.Message()
            {
                CommunicationId = communication.Id,
            };

            transaction.Send();
        }
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            var mergeFields     = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
            int?communicationId = PageParameter(PageParameterKey.CommunicationId).AsIntegerOrNull();

            var rockContext = new RockContext();

            if (communicationId.HasValue)
            {
                _communication = new CommunicationService(rockContext).Get(communicationId.Value);
                mergeFields.Add("Communication", _communication);
            }

            var key = PageParameter(PageParameterKey.Person);

            if (!string.IsNullOrWhiteSpace(key))
            {
                var service = new PersonService(rockContext);
                _person = service.GetByPersonActionIdentifier(key, "Unsubscribe");
                if (_person == null)
                {
                    _person = new PersonService(rockContext).GetByUrlEncodedKey(key);
                }
            }

            if (_person == null && CurrentPerson != null)
            {
                _person = CurrentPerson;
            }

            LoadDropdowns(mergeFields);
            ShowOrHideInactFamily();

            if (_person != null)
            {
                nbEmailPreferenceSuccessMessage.NotificationBoxType = NotificationBoxType.Success;
                nbEmailPreferenceSuccessMessage.Text = GetAttributeValue(AttributeKey.SuccessText).ResolveMergeFields(mergeFields);
            }
            else
            {
                nbEmailPreferenceSuccessMessage.NotificationBoxType = NotificationBoxType.Danger;
                nbEmailPreferenceSuccessMessage.Text    = "Unfortunately, we're unable to update your email preference, as we're not sure who you are.";
                nbEmailPreferenceSuccessMessage.Visible = true;
                btnSubmit.Visible = false;
            }
        }
        private Dictionary <string, string> CreateCommunication()
        {
            var selectedMembers = Request.Form["selectedmembers"];
            var selectedIds     = new List <string>();

            if (selectedMembers != null && !string.IsNullOrWhiteSpace(selectedMembers))
            {
                selectedIds = selectedMembers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }
            else
            {
                mdAlert.Show("Please select members to communicate to.", ModalAlertType.Warning);
                return(new Dictionary <string, string>());
            }
            var rockContext   = new RockContext();
            var service       = new Rock.Model.CommunicationService(rockContext);
            var communication = new Rock.Model.Communication();

            communication.IsBulkCommunication = false;
            communication.Status = Rock.Model.CommunicationStatus.Transient;

            communication.SenderPersonAliasId = this.CurrentPersonAliasId;

            service.Add(communication);

            var personAliasIds = new PersonAliasService(rockContext).Queryable().AsNoTracking()
                                 .Where(a => selectedIds.Contains(a.PersonId.ToString()))
                                 .GroupBy(a => a.PersonId)
                                 .Select(a => a.Min(m => m.Id))
                                 .ToList();

            // Get the primary aliases
            foreach (int personAlias in personAliasIds)
            {
                var recipient = new Rock.Model.CommunicationRecipient();
                recipient.PersonAliasId = personAlias;
                communication.Recipients.Add(recipient);
            }

            rockContext.SaveChanges();

            var queryParameters = new Dictionary <string, string>();

            queryParameters.Add("CommunicationId", communication.Id.ToString());

            return(queryParameters);
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Shows the actions.
 /// </summary>
 /// <param name="communication">The communication.</param>
 private void ShowActions(Rock.Model.Communication communication)
 {
     // Determine if user is allowed to save changes, if not, disable
     // submit and save buttons
     if (IsUserAuthorized("Approve") ||
         (CurrentPersonAliasId.HasValue && CurrentPersonAliasId == communication.SenderPersonAliasId) ||
         IsUserAuthorized(Authorization.EDIT))
     {
         btnSubmit.Enabled = true;
         btnSave.Enabled   = true;
     }
     else
     {
         btnSubmit.Enabled = false;
         btnSave.Enabled   = false;
     }
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Shows the result.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="communication">The communication.</param>
        private void ShowResult(string message, Rock.Model.Communication communication)
        {
            pnlEdit.Visible = false;

            nbResult.Text = message;

            if (CurrentPageReference.Parameters.ContainsKey("CommunicationId"))
            {
                CurrentPageReference.Parameters["CommunicationId"] = communication.Id.ToString();
            }
            else
            {
                CurrentPageReference.Parameters.Add("CommunicationId", communication.Id.ToString());
            }
            hlViewCommunication.NavigateUrl = CurrentPageReference.BuildUrl();

            pnlResult.Visible = true;
        }
 /// <summary>
 /// Handles the RowDataBound event of the gCommunication control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="GridViewRowEventArgs"/> instance containing the event data.</param>
 /// <exception cref="System.NotImplementedException"></exception>
 void gCommunication_RowDataBound(object sender, GridViewRowEventArgs e)
 {
     if (!UserCanEdit && e.Row.RowType == DataControlRowType.DataRow)
     {
         Rock.Model.Communication communication = e.Row.DataItem as Rock.Model.Communication;
         if (
             !CurrentPersonAliasId.HasValue ||
             communication == null ||
             !communication.CreatedByPersonAliasId.HasValue ||
             communication.CreatedByPersonAliasId.Value != CurrentPersonAliasId.Value)
         {
             var lb = e.Row.Cells[5].ControlsOfTypeRecursive <LinkButton>().FirstOrDefault();
             if (lb != null)
             {
                 lb.Visible = false;
             }
         }
     }
 }
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="communication">The communication.</param>
        private void ShowDetail(Rock.Model.Communication communication)
        {
            Recipients.Clear();

            if (communication != null)
            {
                this.AdditionalMergeFields = communication.AdditionalMergeFields.ToList();
                lTitle.Text = ( communication.Subject ?? "New Communication" ).FormatAsHtmlTitle();

                foreach(var recipient in new CommunicationRecipientService(new RockContext())
                    .Queryable("Person.PhoneNumbers")
                    .Where( r => r.CommunicationId == communication.Id))
                {
                    Recipients.Add( new Recipient( recipient.Person, recipient.Status, recipient.StatusNote, recipient.OpenedClient, recipient.OpenedDateTime));
                }
            }
            else
            {
                communication = new Rock.Model.Communication() { Status = CommunicationStatus.Transient };
                lTitle.Text = "New Communication".FormatAsHtmlTitle();

                int? personId = PageParameter( "Person" ).AsInteger( false );
                if ( personId.HasValue )
                {
                    communication.IsBulkCommunication = false;
                    var person = new PersonService( new RockContext() ).Get( personId.Value );
                    if ( person != null )
                    {
                        Recipients.Add( new Recipient( person, CommunicationRecipientStatus.Pending, string.Empty, string.Empty, null ) );
                    }
                }
            }

            CommunicationId = communication.Id;

            ChannelEntityTypeId = communication.ChannelEntityTypeId;
            BindChannels();

            ChannelData = communication.ChannelData;
            ChannelData.Add( "Subject", communication.Subject );

            if (communication.Status == CommunicationStatus.Transient && !string.IsNullOrWhiteSpace(GetAttributeValue("DefaultTemplate")))
            {
                var template = new CommunicationTemplateService( new RockContext() ).Get( GetAttributeValue( "DefaultTemplate" ).AsGuid() );
                if (template != null && template.ChannelEntityTypeId == ChannelEntityTypeId)
                {
                    foreach(ListItem item in ddlTemplate.Items)
                    {
                        if (item.Value == template.Id.ToString())
                        {
                            item.Selected = true;
                            GetTemplateData( template.Id, false );
                        }
                        else
                        {
                            item.Selected = false;
                        }
                    }
                }
            }

            cbBulk.Checked = communication.IsBulkCommunication;

            ChannelControl control = LoadChannelControl( true );
            if ( control != null && CurrentPerson != null )
            {
                control.InitializeFromSender( CurrentPerson );
            }

            dtpFutureSend.SelectedDateTime = communication.FutureSendDateTime;

            ShowStatus( communication );
            ShowActions( communication );
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Updates a communication model with the user-entered values
        /// </summary>
        /// <param name="service">The service.</param>
        /// <returns></returns>
        private Rock.Model.Communication UpdateCommunication(CommunicationService service)
        {
            Rock.Model.Communication communication = null;
            if ( CommunicationId.HasValue )
            {
                communication = service.Get( CommunicationId.Value );
            }

            if (communication == null)
            {
                communication = new Rock.Model.Communication();
                communication.Status = CommunicationStatus.Transient;
                communication.SenderPersonId = CurrentPersonId;
                service.Add( communication, CurrentPersonId );
            }

            communication.ChannelEntityTypeId = ChannelEntityTypeId;

            foreach(var recipient in Recipients)
            {
                if ( !communication.Recipients.Where( r => r.PersonId == recipient.PersonId ).Any() )
                {
                    var communicationRecipient = new CommunicationRecipient();
                    communicationRecipient.Person = new PersonService().Get( recipient.PersonId );
                    communicationRecipient.Status = CommunicationRecipientStatus.Pending;
                    communication.Recipients.Add( communicationRecipient );
                }
            }

            GetChannelData();
            communication.ChannelData = ChannelData;
            if ( communication.ChannelData.ContainsKey( "Subject" ) )
            {
                communication.Subject = communication.ChannelData["Subject"];
                communication.ChannelData.Remove( "Subject" );
            }

            communication.FutureSendDateTime = dtpFutureSend.SelectedDateTime;

            return communication;
        }
        /// <summary>
        /// Handles the Click event of the btnTest control and sends a test communication to the
        /// current person if they have an email address on their record.
        /// </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 btnTest_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid && CurrentPerson != null )
            {
                SetActionButtons( resetToSend: true );

                if ( string.IsNullOrWhiteSpace( CurrentPerson.Email ) )
                {
                    nbError.Text = "A test email cannot be sent because you do not have an email address.";
                    nbError.Visible = true;
                    return;
                }

                // Get existing or new communication record
                var communication = GetCommunication( new RockContext(), null );

                if ( communication != null && CurrentPersonAliasId.HasValue )
                {
                    // Using a new context (so that changes in the UpdateCommunication() are not persisted )
                    var testCommunication = new Rock.Model.Communication();
                    testCommunication.SenderPersonAliasId = communication.SenderPersonAliasId;
                    testCommunication.Subject = communication.Subject;
                    testCommunication.IsBulkCommunication = communication.IsBulkCommunication;
                    testCommunication.MediumEntityTypeId = communication.MediumEntityTypeId;
                    testCommunication.MediumDataJson = communication.MediumDataJson;
                    testCommunication.AdditionalMergeFieldsJson = communication.AdditionalMergeFieldsJson;

                    testCommunication.FutureSendDateTime = null;
                    testCommunication.Status = CommunicationStatus.Approved;
                    testCommunication.ReviewedDateTime = RockDateTime.Now;
                    testCommunication.ReviewerPersonAliasId = CurrentPersonAliasId.Value;

                    var testRecipient = new CommunicationRecipient();
                    if ( communication.Recipients.Any() )
                    {
                        var recipient = communication.Recipients.FirstOrDefault();
                        testRecipient.AdditionalMergeValuesJson = recipient.AdditionalMergeValuesJson;
                    }
                    testRecipient.Status = CommunicationRecipientStatus.Pending;
                    testRecipient.PersonAliasId = CurrentPersonAliasId.Value;
                    testCommunication.Recipients.Add( testRecipient );

                    var rockContext = new RockContext();
                    var communicationService = new CommunicationService( rockContext );
                    communicationService.Add( testCommunication );
                    rockContext.SaveChanges();

                    var medium = testCommunication.Medium;
                    if ( medium != null )
                    {
                        medium.Send( testCommunication );
                    }

                    communicationService.Delete( testCommunication );
                    rockContext.SaveChanges();

                    nbTestResult.Visible = true;
                }
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Handles the Click event of the btnSubmit 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 btnTest_Click( object sender, EventArgs e )
        {
            if ( Page.IsValid && CurrentPersonAliasId.HasValue )
            {
                // Get existing or new communication record
                var rockContext = new RockContext();
                var communication = UpdateCommunication( rockContext );

                if ( communication != null  )
                {
                    // Using a new context (so that changes in the UpdateCommunication() are not persisted )
                    var testCommunication = new Rock.Model.Communication();
                    testCommunication.SenderPersonAliasId = communication.SenderPersonAliasId;
                    testCommunication.Subject = communication.Subject;
                    testCommunication.IsBulkCommunication = communication.IsBulkCommunication;
                    testCommunication.MediumEntityTypeId = communication.MediumEntityTypeId;
                    testCommunication.MediumDataJson = communication.MediumDataJson;
                    testCommunication.AdditionalMergeFieldsJson = communication.AdditionalMergeFieldsJson;

                    testCommunication.FutureSendDateTime = null;
                    testCommunication.Status = CommunicationStatus.Approved;
                    testCommunication.ReviewedDateTime = RockDateTime.Now;
                    testCommunication.ReviewerPersonAliasId = CurrentPersonAliasId;

                    var testRecipient = new CommunicationRecipient();
                    if ( communication.GetRecipientCount( rockContext ) > 0 )
                    {
                        var recipient = communication.GetRecipientsQry(rockContext).FirstOrDefault();
                        testRecipient.AdditionalMergeValuesJson = recipient.AdditionalMergeValuesJson;
                    }

                    testRecipient.Status = CommunicationRecipientStatus.Pending;
                    testRecipient.PersonAliasId = CurrentPersonAliasId.Value;
                    testCommunication.Recipients.Add( testRecipient );

                    var communicationService = new CommunicationService( rockContext );
                    communicationService.Add( testCommunication );
                    rockContext.SaveChanges();

                    var medium = testCommunication.Medium;
                    if ( medium != null )
                    {
                        medium.Send( testCommunication );
                    }

                    communicationService.Delete( testCommunication );
                    rockContext.SaveChanges();

                    nbTestResult.Visible = true;
                }
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Updates a communication model with the user-entered values
        /// </summary>
        /// <param name="communicationService">The service.</param>
        /// <returns></returns>
        private Rock.Model.Communication UpdateCommunication(RockContext rockContext)
        {
            var communicationService = new CommunicationService(rockContext);
            var recipientService = new CommunicationRecipientService(rockContext);

            Rock.Model.Communication communication = null;
            IQueryable<CommunicationRecipient> qryRecipients = null;

            if ( CommunicationId.HasValue )
            {
                communication = communicationService.Get( CommunicationId.Value );
            }

            if ( communication != null )
            {
                // Remove any deleted recipients
                HashSet<int> personIdHash = new HashSet<int>( Recipients.Select( a => a.PersonId ) );
                qryRecipients = communication.GetRecipientsQry( rockContext );

                foreach ( var item in qryRecipients.Select( a => new
                {
                    Id = a.Id,
                    PersonId = a.PersonAlias.PersonId
                }) )
                {
                    if ( !personIdHash.Contains(item.PersonId) )
                    {
                        var recipient = qryRecipients.Where( a => a.Id == item.Id ).FirstOrDefault();
                        recipientService.Delete( recipient );
                        communication.Recipients.Remove( recipient );
                    }
                }
            }

            if (communication == null)
            {
                communication = new Rock.Model.Communication();
                communication.Status = CommunicationStatus.Transient;
                communication.SenderPersonAliasId = CurrentPersonAliasId;
                communicationService.Add( communication );
            }

            if (qryRecipients == null)
            {
                qryRecipients = communication.GetRecipientsQry( rockContext );
            }

            // Add any new recipients
            HashSet<int> communicationPersonIdHash = new HashSet<int>( qryRecipients.Select( a => a.PersonAlias.PersonId ) );
            foreach(var recipient in Recipients )
            {
                if ( !communicationPersonIdHash.Contains( recipient.PersonId ) )
                {
                    var person = new PersonService( rockContext ).Get( recipient.PersonId );
                    if ( person != null )
                    {
                        var communicationRecipient = new CommunicationRecipient();
                        communicationRecipient.PersonAlias = person.PrimaryAlias;
                        communication.Recipients.Add( communicationRecipient );
                    }
                }
            }

            communication.IsBulkCommunication = cbBulk.Checked;

            communication.MediumEntityTypeId = MediumEntityTypeId;
            communication.MediumData.Clear();
            GetMediumData();
            foreach ( var keyVal in MediumData )
            {
                if ( !string.IsNullOrEmpty( keyVal.Value ) )
                {
                    communication.MediumData.Add( keyVal.Key, keyVal.Value );
                }
            }

            if ( communication.MediumData.ContainsKey( "Subject" ) )
            {
                communication.Subject = communication.MediumData["Subject"];
                communication.MediumData.Remove( "Subject" );
            }

            DateTime? futureSendDate = dtpFutureSend.SelectedDateTime;
            if ( futureSendDate.HasValue && futureSendDate.Value.CompareTo( RockDateTime.Now ) > 0 )
            {
                communication.FutureSendDateTime = futureSendDate;
            }
            else
            {
                communication.FutureSendDateTime = null;
            }

            return communication;
        }
        /// <summary>
        /// Updates a communication model with the user-entered values
        /// </summary>
        /// <param name="communicationService">The service.</param>
        /// <returns></returns>
        private Rock.Model.Communication UpdateCommunication(RockContext rockContext)
        {
            var communicationService = new CommunicationService(rockContext);
            var recipientService = new CommunicationRecipientService(rockContext);

            Rock.Model.Communication communication = null;
            if ( CommunicationId.HasValue )
            {
                communication = communicationService.Get( CommunicationId.Value );

                // Remove any deleted recipients
                foreach(var recipient in recipientService.GetByCommunicationId( CommunicationId.Value ) )
                {
                    if (!Recipients.Any( r => recipient.PersonAlias != null && r.PersonId == recipient.PersonAlias.PersonId))
                    {
                        recipientService.Delete(recipient);
                        communication.Recipients.Remove( recipient );
                    }
                }
            }

            if (communication == null)
            {
                communication = new Rock.Model.Communication();
                communication.Status = CommunicationStatus.Transient;
                communication.SenderPersonAliasId = CurrentPersonAliasId;
                communicationService.Add( communication );
            }

            // Add any new recipients
            foreach(var recipient in Recipients )
            {
                if ( !communication.Recipients.Any( r => r.PersonAlias != null && r.PersonAlias.PersonId == recipient.PersonId ) )
                {
                    var person = new PersonService( rockContext ).Get( recipient.PersonId );
                    if ( person != null )
                    {
                        var communicationRecipient = new CommunicationRecipient();
                        communicationRecipient.PersonAlias = person.PrimaryAlias;
                        communication.Recipients.Add( communicationRecipient );
                    }
                }
            }

            communication.IsBulkCommunication = cbBulk.Checked;

            communication.MediumEntityTypeId = MediumEntityTypeId;
            communication.MediumData.Clear();
            GetMediumData();
            foreach ( var keyVal in MediumData )
            {
                if ( !string.IsNullOrEmpty( keyVal.Value ) )
                {
                    communication.MediumData.Add( keyVal.Key, keyVal.Value );
                }
            }

            if ( communication.MediumData.ContainsKey( "Subject" ) )
            {
                communication.Subject = communication.MediumData["Subject"];
                communication.MediumData.Remove( "Subject" );
            }

            DateTime? futureSendDate = dtpFutureSend.SelectedDateTime;
            if ( futureSendDate.HasValue && futureSendDate.Value.CompareTo( RockDateTime.Now ) > 0 )
            {
                communication.FutureSendDateTime = futureSendDate;
            }
            else
            {
                communication.FutureSendDateTime = null;
            }

            return communication;
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Sends the communication.
        /// </summary>
        private void SendCommunication()
        {
            // create communication
            if ( this.CurrentPerson != null && _groupId != -1 && !string.IsNullOrWhiteSpace( GetAttributeValue( "CommunicationPage" ) ) )
            {
                var rockContext = new RockContext();
                var service = new Rock.Model.CommunicationService( rockContext );
                var communication = new Rock.Model.Communication();
                communication.IsBulkCommunication = false;
                communication.Status = Rock.Model.CommunicationStatus.Transient;

                communication.SenderPersonAliasId = this.CurrentPersonAliasId;

                service.Add( communication );

                var personAliasIds = new GroupMemberService( rockContext ).Queryable()
                                    .Where( m => m.GroupId == _groupId && m.GroupMemberStatus != GroupMemberStatus.Inactive )
                                    .ToList()
                                    .Select( m => m.Person.PrimaryAliasId )
                                    .ToList();

                // Get the primary aliases
                foreach ( int personAlias in personAliasIds )
                {
                    var recipient = new Rock.Model.CommunicationRecipient();
                    recipient.PersonAliasId = personAlias;
                    communication.Recipients.Add( recipient );
                }

                rockContext.SaveChanges();

                Dictionary<string, string> queryParameters = new Dictionary<string, string>();
                queryParameters.Add( "CommunicationId", communication.Id.ToString() );

                NavigateToLinkedPage( "CommunicationPage", queryParameters );
            }
        }
Ejemplo n.º 38
0
Archivo: Sms.cs Proyecto: Ganon11/Rock
        /// <summary>
        /// Creates a new communication.
        /// </summary>
        /// <param name="fromPersonId">Person ID of the sender.</param>
        /// <param name="fromPersonName">Name of from person.</param>
        /// <param name="toPersonId">The Person ID of the recipient.</param>
        /// <param name="message">The message to send.</param>
        /// <param name="transportPhone">The transport phone.</param>
        /// <param name="responseCode">The reponseCode to use for tracking the conversation.</param>
        /// <param name="rockContext">A context to use for database calls.</param>
        private void CreateCommunication( int fromPersonId, string fromPersonName, int toPersonId, string message, string transportPhone, string responseCode, Rock.Data.RockContext rockContext )
        {

            // add communication for reply
            var communication = new Rock.Model.Communication();
            communication.IsBulkCommunication = false;
            communication.Status = CommunicationStatus.Approved;
            communication.SenderPersonId = fromPersonId;
            communication.Subject = string.Format( "From: {0}", fromPersonName );

            communication.SetChannelDataValue( "Message", message );
            communication.SetChannelDataValue( "FromValue", transportPhone );

            communication.ChannelEntityTypeId = EntityTypeCache.Read( "Rock.Communication.Channel.Sms" ).Id;

            var recipient = new Rock.Model.CommunicationRecipient();
            recipient.Status = CommunicationRecipientStatus.Pending;
            recipient.PersonId = toPersonId;
            recipient.ResponseCode = responseCode;
            communication.Recipients.Add( recipient );

            var communicationService = new Rock.Model.CommunicationService( rockContext );
            communicationService.Add( communication );
            rockContext.SaveChanges();

            // queue the sending
            var transaction = new Rock.Transactions.SendCommunicationTransaction();
            transaction.CommunicationId = communication.Id;
            transaction.PersonAlias = null;
            Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction );
        }
        /// <summary>
        /// Gets the communication.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="peopleIds">The people ids.</param>
        /// <returns></returns>
        private Rock.Model.Communication GetCommunication( RockContext rockContext, List<int> peopleIds )
        {
            var communicationService = new CommunicationService(rockContext);
            var recipientService = new CommunicationRecipientService(rockContext);

            GetTemplateData();

            Rock.Model.Communication communication = new Rock.Model.Communication();
            communication.Status = CommunicationStatus.Transient;
            communication.SenderPersonAliasId = CurrentPersonAliasId;
            communicationService.Add( communication );
            communication.IsBulkCommunication = true;
            communication.MediumEntityTypeId = EntityTypeCache.Read( "Rock.Communication.Medium.Email" ).Id;
            communication.FutureSendDateTime = null;

            // add each person as a recipient to the communication
            if ( peopleIds != null )
            {
                foreach ( var personId in peopleIds )
                {
                    if ( !communication.Recipients.Any( r => r.PersonAlias.PersonId == personId ) )
                    {
                        var communicationRecipient = new CommunicationRecipient();
                        communicationRecipient.PersonAlias = new PersonAliasService( rockContext ).GetPrimaryAlias( personId );
                        communication.Recipients.Add( communicationRecipient );
                    }
                }
            }

            // add the MediumData to the communication
            communication.MediumData.Clear();
            foreach ( var keyVal in MediumData )
            {
                if ( !string.IsNullOrEmpty( keyVal.Value ) )
                {
                    communication.MediumData.Add( keyVal.Key, keyVal.Value );
                }
            }

            if ( communication.MediumData.ContainsKey( "Subject" ) )
            {
                communication.Subject = communication.MediumData["Subject"];
                communication.MediumData.Remove( "Subject" );
            }

            return communication;
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="itemKey">The item key.</param>
        /// <param name="itemKeyValue">The item key value.</param>
        private void ShowDetail( string itemKey, int itemKeyValue )
        {
            if ( !itemKey.Equals( "CommunicationId" ) )
            {
                return;
            }

            Rock.Model.Communication communication = null;

            if ( !itemKeyValue.Equals( 0 ) )
            {
                communication = new CommunicationService().Get( itemKeyValue );
                RockPage.PageTitle = string.Format( "Communication #{0}", communication.Id );
                this.AdditionalMergeFields = communication.AdditionalMergeFields.ToList();

                lTitle.Text = ("Subject: " + communication.Subject).FormatAsHtmlTitle();
            }
            else
            {
                communication = new Rock.Model.Communication() { Status = CommunicationStatus.Transient };
                RockPage.PageTitle = "New Communication";
                lTitle.Text = "New Communication".FormatAsHtmlTitle();
            }

            if ( communication == null )
            {
                return;
            }

            ShowDetail( communication );
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="communication">The communication.</param>
        private void ShowDetail(Rock.Model.Communication communication)
        {
            Recipients.Clear();

            if ( communication != null )
            {
                this.AdditionalMergeFields = communication.AdditionalMergeFields.ToList();
                lTitle.Text = ( communication.Subject ?? "New Communication" ).FormatAsHtmlTitle();
                var recipientList = new CommunicationRecipientService( new RockContext() )
                    .Queryable()
                    //.Include()
                    .Where( r => r.CommunicationId == communication.Id )
                    .Select(a => new {
                        a.PersonAlias.Person,
                        PersonHasSMS = a.PersonAlias.Person.PhoneNumbers.Any( p => p.IsMessagingEnabled ),
                        a.Status,
                        a.StatusNote,
                        a.OpenedClient,
                        a.OpenedDateTime
                    }).ToList();

                Recipients = recipientList.Select( recipient => new Recipient( recipient.Person, recipient.PersonHasSMS, recipient.Status, recipient.StatusNote, recipient.OpenedClient, recipient.OpenedDateTime ) ).ToList();
            }
            else
            {
                communication = new Rock.Model.Communication() { Status = CommunicationStatus.Transient };
                communication.SenderPersonAliasId = CurrentPersonAliasId;
                lTitle.Text = "New Communication".FormatAsHtmlTitle();

                int? personId = PageParameter( "Person" ).AsIntegerOrNull();
                if ( personId.HasValue )
                {
                    communication.IsBulkCommunication = false;
                    var person = new PersonService( new RockContext() ).Get( personId.Value );
                    if ( person != null )
                    {
                        Recipients.Add( new Recipient( person, person.PhoneNumbers.Any(p => p.IsMessagingEnabled), CommunicationRecipientStatus.Pending, string.Empty, string.Empty, null ) );
                    }
                }
            }

            CommunicationId = communication.Id;

            MediumEntityTypeId = communication.MediumEntityTypeId;
            BindMediums();

            MediumData = communication.MediumData;
            MediumData.AddOrReplace( "Subject", communication.Subject );

            if (communication.Status == CommunicationStatus.Transient && !string.IsNullOrWhiteSpace(GetAttributeValue("DefaultTemplate")))
            {
                var template = new CommunicationTemplateService( new RockContext() ).Get( GetAttributeValue( "DefaultTemplate" ).AsGuid() );

                // If a template guid was passed in, it overrides any default template.
                string templateGuid = PageParameter( "templateGuid" );
                if ( !string.IsNullOrEmpty( templateGuid ) )
                {
                    var guid = new Guid( templateGuid );
                    template = new CommunicationTemplateService( new RockContext() ).Queryable().Where( t => t.Guid == guid ).FirstOrDefault();
                }

                if (template != null && template.MediumEntityTypeId == MediumEntityTypeId)
                {
                    foreach(ListItem item in ddlTemplate.Items)
                    {
                        if (item.Value == template.Id.ToString())
                        {
                            item.Selected = true;
                            GetTemplateData( template.Id, false );
                        }
                        else
                        {
                            item.Selected = false;
                        }
                    }
                }
            }

            cbBulk.Checked = communication.IsBulkCommunication;

            MediumControl control = LoadMediumControl( true );
            InitializeControl( control );

            dtpFutureSend.SelectedDateTime = communication.FutureSendDateTime;

            ShowStatus( communication );
            ShowActions( communication );
        }