Exemplo n.º 1
0
        private MpCommunication CreateJourneyInvitation(EmailCommunicationDTO communication, Participant particpant)
        {
            var template    = _communicationService.GetTemplate(communication.TemplateId);
            var fromContact = _contactService.GetContactById(_configurationWrapper.GetConfigIntValue("DefaultContactEmailId"));
            var replyTo     = _contactService.GetContactById(particpant.ContactId);
            var mergeData   = SetupMergeData(particpant.PreferredName, communication.groupId.Value);

            return(new MpCommunication
            {
                AuthorUserId = 5,
                DomainId = 1,
                EmailBody = template.Body,
                EmailSubject = template.Subject,
                FromContact = new MpContact {
                    ContactId = _defaultContactEmailId, EmailAddress = fromContact.Email_Address
                },
                ReplyToContact = new MpContact {
                    ContactId = _defaultContactEmailId, EmailAddress = replyTo.Email_Address
                },
                ToContacts = new List <MpContact> {
                    new MpContact {
                        ContactId = fromContact.Contact_ID, EmailAddress = communication.emailAddress
                    }
                },
                MergeData = mergeData
            });
        }
Exemplo n.º 2
0
        private void SendPendingInquiryReminderEmail(MpGroup group, IReadOnlyCollection <MpInquiry> inquiries)
        {
            var leaders         = ((List <MpGroupParticipant>)group.Participants).FindAll(p => p.GroupRoleId == _groupRoleLeaderId).ToList();
            var allLeaders      = string.Join(", ", leaders.Select(leader => $"{leader.NickName} {leader.LastName} ({leader.Email})").ToArray());
            var pendingRequests = string.Join("<br>", inquiries.Select(inquiry => $"{inquiry.FirstName} {inquiry.LastName} ({inquiry.EmailAddress})").ToArray());

            // ReSharper disable once LoopCanBePartlyConvertedToQuery
            foreach (var leader in leaders)
            {
                var mergeData = new Dictionary <string, object>
                {
                    { "Nick_Name", leader.NickName },
                    { "Last_Name", leader.LastName },
                    { "All_Leaders", allLeaders },
                    { "Pending_Requests", pendingRequests },
                    { "Group_Name", group.Name },
                    { "Group_Description", group.GroupDescription },
                    { "Group_ID", group.GroupId },
                    { "Pending_Requests_Count", inquiries.Count }
                };

                var email = new EmailCommunicationDTO
                {
                    groupId     = group.GroupId,
                    TemplateId  = _groupRequestPendingReminderEmailTemplateId,
                    ToContactId = leader.ContactId,
                    MergeData   = mergeData
                };
                _emailCommunicationService.SendEmail(email);
            }
        }
Exemplo n.º 3
0
        public bool PasswordResetRequest(string username)
        {
            int user_ID    = 0;
            int contact_Id = 0;

            // validate the email on the server side to avoid erroneous or malicious requests
            try
            {
                user_ID    = _userService.GetUserIdByUsername(username);
                contact_Id = _userService.GetContactIdByUserId(user_ID);
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Could not find email {0} for password reset", JsonConvert.SerializeObject(username, Formatting.Indented)), ex);
                return(false);
            }

            // create a token -- see http://stackoverflow.com/questions/664673/how-to-implement-password-resets
            var resetArray = Encoding.UTF8.GetBytes(Guid.NewGuid() + username + System.DateTime.Now);
            RNGCryptoServiceProvider prov = new RNGCryptoServiceProvider();

            prov.GetBytes(resetArray);
            var    resetToken = Encoding.UTF8.GetString(resetArray);
            string cleanToken = Regex.Replace(resetToken, "[^A-Za-z0-9]", "");

            Dictionary <string, object> userUpdateValues = new Dictionary <string, object>();

            userUpdateValues["User_ID"]            = user_ID;
            userUpdateValues["PasswordResetToken"] = cleanToken; // swap out for real implementation
            _userService.UpdateUser(userUpdateValues);

            string baseURL   = _configurationWrapper.GetConfigValue("BaseURL");
            string resetLink = (@"https://" + baseURL + "/reset-password?token=" + cleanToken);

            // add the email here...
            var emailCommunication = new EmailCommunicationDTO
            {
                FromContactId = 7, // church admin contact id
                FromUserId    = 5, // church admin user id
                ToContactId   = contact_Id,
                TemplateId    = 13356,
                MergeData     = new Dictionary <string, object>
                {
                    { "resetlink", resetLink }
                }
            };

            try
            {
                _emailCommunication.SendEmail(emailCommunication);
                return(true);
            }
            catch (Exception ex)
            {
                _logger.Error(string.Format("Could not send email {0} for password reset", JsonConvert.SerializeObject(username, Formatting.Indented)), ex);
                return(false);
            }
        }
Exemplo n.º 4
0
 public IHttpActionResult PostReminder(EmailCommunicationDTO email)
 {
     try
     {
         email.TemplateId = _configurationWrapper.GetConfigIntValue("StreamReminderTemplate");
         _emailCommunication.SendEmail(email);
         return(this.Ok());
     }
     catch (System.Exception ex)
     {
         var apiError = new ApiErrorDto("Schedule Email failed", ex);
         throw new HttpResponseException(apiError.HttpResponseMessage);
     }
 }
        public void PostInvitationWhenRequesterIsMemberOfGoup()
        {
            var communication = new EmailCommunicationDTO()
            {
                emailAddress = "*****@*****.**"
            };

            _groupServiceMock.Setup(mocked => mocked.SendJourneyEmailInvite(communication, _fixture.Request.Headers.Authorization.ToString()));

            IHttpActionResult result = _fixture.PostInvitation(communication);

            _groupServiceMock.Verify(x => x.SendJourneyEmailInvite(communication, _fixture.Request.Headers.Authorization.ToString()), Times.Once);
            _groupServiceMock.VerifyAll();
        }
Exemplo n.º 6
0
        public IHttpActionResult Post(EmailCommunicationDTO email)
        {
            return(Authorized(token =>
            {
                try
                {
                    _emailCommunication.SendEmail(email, token);

                    return Ok();
                }
                catch (Exception ex)
                {
                    return InternalServerError(ex);
                }
            }));
        }
        public void DoNotPostInvitationWhenRequesterIsNotMemberOfGoup()
        {
            var communication = new EmailCommunicationDTO()
            {
                emailAddress = "*****@*****.**"
            };

            _groupServiceMock.Setup(mocked => mocked.SendJourneyEmailInvite(communication, _fixture.Request.Headers.Authorization.ToString())).Throws <InvalidOperationException>();

            IHttpActionResult result = _fixture.PostInvitation(communication);

            _groupServiceMock.VerifyAll();
            Assert.IsNotNull(result);

            Assert.IsInstanceOf(typeof(NotFoundResult), result);
        }
Exemplo n.º 8
0
        public void SendEmail(EmailCommunicationDTO email, string token)
        {
            var template = _communicationService.GetTemplate(email.TemplateId);

            if (token == null && email.FromUserId == null && template.FromContactId == 0)
            {
                throw (new InvalidOperationException("Must provide either email.FromUserId from  or an authentication token."));
            }

            var replyToContactId = email.ReplyToContactId ?? template.ReplyToContactId;
            var replyTo          = new MpContact {
                ContactId = replyToContactId, EmailAddress = _communicationService.GetEmailFromContactId(replyToContactId)
            };

            var fromContactId = email.FromContactId ?? template.FromContactId;
            var from          = new MpContact {
                ContactId = fromContactId, EmailAddress = _communicationService.GetEmailFromContactId(fromContactId)
            };

            MpContact to = GetMpContactFromEmailCommunicationDto(email);

            var communication = new MpCommunication
            {
                DomainId       = DomainID,
                AuthorUserId   = email.FromUserId ?? DefaultAuthorUserId,
                TemplateId     = email.TemplateId,
                EmailBody      = template.Body,
                EmailSubject   = template.Subject,
                ReplyToContact = replyTo,
                FromContact    = from,
                StartDate      = email.StartDate ?? DateTime.Now,
                MergeData      = email.MergeData,
                ToContacts     = new List <MpContact>()
            };

            communication.ToContacts.Add(to);

            if (!communication.MergeData.ContainsKey("BaseUrl"))
            {
                communication.MergeData.Add("BaseUrl", _configurationWrapper.GetConfigValue("BaseUrl"));
            }

            _communicationService.SendMessage(communication);
        }
Exemplo n.º 9
0
        public void TestSendEmailWithContactId()
        {
            EmailCommunicationDTO emailData = new EmailCommunicationDTO
            {
                TemplateId  = 264567,
                MergeData   = new Dictionary <string, object>(),
                ToContactId = 10,
                StartDate   = DateTime.Now
            };

            MpMessageTemplate template = new MpMessageTemplate()
            {
                Body                = "body",
                Subject             = "subject",
                FromContactId       = 5,
                FromEmailAddress    = "*****@*****.**",
                ReplyToContactId    = 5,
                ReplyToEmailAddress = "[email protected]."
            };

            MpContact expectedContact = new MpContact()
            {
                ContactId    = emailData.ToContactId.Value,
                EmailAddress = "*****@*****.**"
            };

            _communicationService.Setup(mocked => mocked.GetTemplate(emailData.TemplateId)).Returns(template);
            _communicationService.Setup(mocked => mocked.GetEmailFromContactId(template.ReplyToContactId)).Returns(template.ReplyToEmailAddress);
            _communicationService.Setup(mocked => mocked.GetEmailFromContactId(emailData.ToContactId.Value)).Returns("*****@*****.**");
            _communicationService.Setup(mocked => mocked.GetEmailFromContactId(template.FromContactId)).Returns(template.FromEmailAddress);
            _communicationService.Setup(mocked => mocked.GetTemplate(emailData.TemplateId)).Returns(template);
            _contactService.Setup(mocked => mocked.GetContactIdByEmail(emailData.emailAddress)).Returns(0);

            var spiedComm = new MpCommunication();

            _communicationService.Setup(m => m.SendMessage(It.IsAny <MpCommunication>(), false))
            .Callback <MpCommunication, bool>((comm, token) => spiedComm = comm);


            fixture.SendEmail(emailData, null);
            _communicationService.Verify(m => m.SendMessage(It.IsAny <MpCommunication>(), false), Times.Once);
            Assert.AreEqual(JsonConvert.SerializeObject(expectedContact), JsonConvert.SerializeObject(spiedComm.ToContacts[0]));
        }
Exemplo n.º 10
0
 public IHttpActionResult PostInvitation([FromBody] EmailCommunicationDTO communication)
 {
     return(Authorized(token =>
     {
         try
         {
             _groupService.SendJourneyEmailInvite(communication, token);
             return Ok();
         }
         catch (InvalidOperationException)
         {
             return NotFound();
         }
         catch (Exception ex)
         {
             var apiError = new ApiErrorDto("Error sending a Journey Group invitation for groupID " + communication.groupId, ex);
             throw new HttpResponseException(apiError.HttpResponseMessage);
         }
     }));
 }
Exemplo n.º 11
0
        public void SendJourneyEmailInvite(EmailCommunicationDTO communication, string token)
        {
            var participant = GetParticipantRecord(token);
            var groups      = GetGroupsByTypeForParticipant(token, participant.ParticipantId, _journeyGroupTypeId);

            if (groups == null || groups.Count == 0)
            {
                throw new InvalidOperationException();
            }

            var membership = groups.Where(group => @group.GroupId == communication.groupId).ToList();

            if (membership.Count <= 0)
            {
                throw new InvalidOperationException();
            }

            var invitation = CreateJourneyInvitation(communication, participant);

            _communicationService.SendMessage(invitation);
        }
Exemplo n.º 12
0
        private void SendEmail(CheckScannerBatch batch, Exception error)
        {
            if (batch.MinistryPlatformContactId == null || batch.MinistryPlatformUserId == null)
            {
                return;
            }

            var email = new EmailCommunicationDTO
            {
                FromContactId = batch.MinistryPlatformContactId.Value,
                FromUserId    = batch.MinistryPlatformUserId,
                ToContactId   = batch.MinistryPlatformContactId.Value,
                TemplateId    = error == null ? _checkScannerBatchSuccessTemplateId : _checkScannerBatchFailureTemplateId,
                MergeData     = new Dictionary <string, object>
                {
                    { "batchName", batch.Name },
                    { "programId", batch.ProgramId },
                }
            };

            if (error != null)
            {
                email.MergeData["exception"] = error;
            }
            else
            {
                email.MergeData["batch"] = batch.EmailMsg;
            }


            try
            {
                _emailService.SendEmail(email);
            }
            catch (Exception e)
            {
                _logger.Error(string.Format("Could not send email {0} for batch", JsonConvert.SerializeObject(email, Formatting.Indented)), e);
            }
        }
Exemplo n.º 13
0
        private MpContact GetMpContactFromEmailCommunicationDto(EmailCommunicationDTO email)
        {
            MpContact to;

            if (!email.ToContactId.HasValue && email.emailAddress == null)
            {
                throw (new InvalidOperationException("Must provide either ToContactId or emailAddress."));
            }

            if (email.ToContactId.HasValue)
            {
                return(new MpContact {
                    ContactId = email.ToContactId.Value, EmailAddress = _communicationService.GetEmailFromContactId(email.ToContactId.Value)
                });
            }

            var contactId = 0;

            try
            {
                contactId = _contactService.GetContactIdByEmail(email.emailAddress);
            }
            catch (Exception)
            {
                //work around incorrectly handled case where multiple contacts exists for a single contact
                contactId = 0;
            }
            if (contactId == 0)
            {
                contactId = DefaultContactEmailId;
            }
            to = new MpContact {
                ContactId = contactId, EmailAddress = email.emailAddress
            };

            return(to);
        }