Skip to content

Commit

Permalink
Merge pull request #2046 from objectcomputing/feature-2045/send-as-user
Browse files Browse the repository at this point in the history
Altered to send emails as logged in user where applicable.
  • Loading branch information
mkimberlin authored Nov 9, 2023
2 parents 79cfdd0 + ea0eef5 commit e8d9310
Show file tree
Hide file tree
Showing 12 changed files with 58 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

public interface EmailSender {

void sendEmail(String subject, String content, String... recipients);
void sendEmail(String fromName, String fromAddress, String subject, String content, String... recipients);

boolean sendEmailReceivesStatus(String subject, String content, String... recipients);
boolean sendEmailReceivesStatus(String fromName, String fromAddress, String subject, String content, String... recipients);

void setEmailFormat(String format);
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.objectcomputing.checkins.notifications.email;


import com.objectcomputing.checkins.exceptions.PermissionException;
import com.objectcomputing.checkins.services.memberprofile.MemberProfile;
import com.objectcomputing.checkins.services.memberprofile.currentuser.CurrentUserServices;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Post;
Expand All @@ -19,21 +22,30 @@
@Secured(SecurityRule.IS_AUTHENTICATED)
public class MailJetNotificationController {

private final CurrentUserServices currentUserServices;
private final EmailSender emailSender;
private final EventLoopGroup eventLoopGroup;
private final ExecutorService ioExecutorService;

public MailJetNotificationController(@Named(MailJetConfig.HTML_FORMAT) EmailSender emailSender,
public MailJetNotificationController(CurrentUserServices currentUserServices,
@Named(MailJetConfig.HTML_FORMAT) EmailSender emailSender,
EventLoopGroup eventLoopGroup,
@Named(TaskExecutors.IO) ExecutorService ioExecutorService) {
this.currentUserServices = currentUserServices;
this.emailSender = emailSender;
this.eventLoopGroup = eventLoopGroup;
this.ioExecutorService = ioExecutorService;
}

@Post()
public Mono<? extends HttpResponse<?>> sendEmailReceivesStatus(String subject, String content, String... recipients) {
return Mono.fromCallable(() -> emailSender.sendEmailReceivesStatus(subject, content, recipients))
if (!currentUserServices.isAdmin()) {
throw new PermissionException("You are not authorized to do this operation");
}

MemberProfile currentUser = currentUserServices.getCurrentUser();
String fromName = currentUser.getFirstName() + " " + currentUser.getLastName();
return Mono.fromCallable(() -> emailSender.sendEmailReceivesStatus(fromName, currentUser.getWorkEmail(), subject, content, recipients))
.publishOn(Schedulers.fromExecutor(eventLoopGroup))
.map(success -> (HttpResponse<?>) HttpResponse.ok())
.subscribeOn(Schedulers.fromExecutor(ioExecutorService));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,12 +73,16 @@ public static List<JSONArray> getEmailBatches(String... recipients) {

/**
* This call sends a message to the given recipient with attachment.
* @param fromName {@link String} The name of the person sending the email
* @param fromAddress {@link String} The email address of the person sending the email
* @param subject {@link String} Subject of email
* @param content {@link String} Contents of email
* @param recipients List of recipient email addresses
*/
@Override
public void sendEmail(String subject, String content, String... recipients) {
public void sendEmail(String fromName, String fromAddress, String subject, String content, String... recipients) {
if(fromName == null) fromName = this.fromName;
if(fromAddress == null) fromAddress = this.fromAddress;

List<JSONArray> emailBatches = getEmailBatches(recipients);
List<JSONArray> failedBatches = new ArrayList<>();
Expand Down Expand Up @@ -111,9 +115,9 @@ public void sendEmail(String subject, String content, String... recipients) {
}

@Override
public boolean sendEmailReceivesStatus(String subject, String content, String... recipients) {
public boolean sendEmailReceivesStatus(String fromName, String fromAddress, String subject, String content, String... recipients) {
try {
sendEmail(subject, content, recipients);
sendEmail(fromName, fromAddress, subject, content, recipients);
} catch (Exception e){
LOG.error("An unexpected exception occurred while sending the upload notification: " + e.getLocalizedMessage(), e);
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

import jakarta.inject.Named;
import jakarta.inject.Singleton;

import java.lang.reflect.Member;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
Expand Down Expand Up @@ -57,12 +59,14 @@ public List<Email> sendAndSaveEmail(String subject, String content, boolean html
throw new PermissionException("You are not authorized to do this operation");
}

MemberProfile currentUser = currentUserServices.getCurrentUser();
String fromName = currentUser.getFirstName() + " " + currentUser.getLastName();
LocalDateTime sendDate = LocalDateTime.now();
boolean status;
if (html) {
status = htmlEmailSender.sendEmailReceivesStatus(subject, content, recipients);
status = htmlEmailSender.sendEmailReceivesStatus(fromName, currentUser.getWorkEmail(), subject, content, recipients);
} else {
status = textEmailSender.sendEmailReceivesStatus(subject, content, recipients);
status = textEmailSender.sendEmailReceivesStatus(fromName, currentUser.getWorkEmail(), subject, content, recipients);
}

UUID senderId = currentUserServices.getCurrentUser().getId();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,15 +105,16 @@ public FeedbackRequest save(FeedbackRequest feedbackRequest) {
private void sendNewRequestEmail(FeedbackRequest storedRequest) {
MemberProfile creator = memberProfileServices.getById(storedRequest.getCreatorId());
MemberProfile requestee = memberProfileServices.getById(storedRequest.getRequesteeId());
String senderName = creator.getFirstName() + " " + creator.getLastName();
String newContent = "<h1>You have received a feedback request.</h1>" +
"<p><b>" + creator.getFirstName() + " " + creator.getLastName() + "</b> is requesting feedback on <b>" + requestee.getFirstName() + " " + requestee.getLastName() + "</b> from you.</p>";
"<p><b>" + senderName + "</b> is requesting feedback on <b>" + requestee.getFirstName() + " " + requestee.getLastName() + "</b> from you.</p>";
if (storedRequest.getDueDate() != null) {
newContent += "<p>This request is due on " + storedRequest.getDueDate().getMonth() + " " + storedRequest.getDueDate().getDayOfMonth()+ ", " + storedRequest.getDueDate().getYear() + ".";
}
newContent += "<p>Please go to your unique link at " + webURL + "/feedback/submit?request=" + storedRequest.getId() + " to complete this request.</p>";

// LOG.warn("Pretending to send an email about the new request to "+memberProfileServices.getById(storedRequest.getRecipientId()).getFirstName());
emailSender.sendEmail(notificationSubject, newContent, memberProfileServices.getById(storedRequest.getRecipientId()).getWorkEmail());
emailSender.sendEmail(senderName, creator.getWorkEmail(), notificationSubject, newContent, memberProfileServices.getById(storedRequest.getRecipientId()).getWorkEmail());
}

@Override
Expand Down Expand Up @@ -181,14 +182,15 @@ public FeedbackRequest update(FeedbackRequestUpdateDTO feedbackRequestUpdateDTO)
if (originalFeedback.getStatus().equals("submitted") && feedbackRequest.getStatus().equals("sent")) {
MemberProfile creator = memberProfileServices.getById(storedRequest.getCreatorId());
MemberProfile requestee = memberProfileServices.getById(storedRequest.getRequesteeId());
String senderName = creator.getFirstName() + " " + creator.getLastName();
String newContent = "<h1>You have received edit access to a feedback request.</h1>" +
"<p><b>" + creator.getFirstName() + " " + creator.getLastName() +
"<p><b>" + senderName +
"</b> has reopened the feedback request on <b>" +
requestee.getFirstName() + " " + requestee.getLastName() + "</b> from you." +
"You may make changes to your answers, but you will need to submit the form again when finished.</p>";
newContent += "<p>Please go to your unique link at " + webURL + "/feedback/submit?request=" + storedRequest.getId() + " to complete this request.</p>";
// LOG.warn("Pretending to send an email about the reopened request to "+memberProfileServices.getById(storedRequest.getRecipientId()).getFirstName());
emailSender.sendEmail(notificationSubject, newContent, memberProfileServices.getById(storedRequest.getRecipientId()).getWorkEmail());
emailSender.sendEmail(senderName, creator.getWorkEmail(), notificationSubject, newContent, memberProfileServices.getById(storedRequest.getRecipientId()).getWorkEmail());
}

// Send email if the feedback request has been reassigned
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ private void sendGuildMemberChangeNotification(List<MemberProfile> addedMembers,

String emailContent = constructEmailContent(addedMembers, removedMembers, guildName);
String subject = "Membership Changes have been made to the " + guildName +" guild";
emailSender.sendEmail(subject, emailContent, emailsOfGuildLeads.toArray(new String[0]));
emailSender.sendEmail(null, null, subject, emailContent, emailsOfGuildLeads.toArray(new String[0]));

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ else if (!currentUserServices.isAdmin() && !guildMember.getMemberId().equals(cur
}

emailSender
.sendEmail("Membership changes have been made to the " + guild.get().getName() + " guild",
.sendEmail(null, null, "Membership changes have been made to the " + guild.get().getName() + " guild",
constructEmailContent(guildMember, true),
getGuildLeadsEmails(guildLeads, guildMember).toArray(new String[0])
);
Expand Down Expand Up @@ -166,7 +166,7 @@ public void delete(@NotNull UUID id) {
.orElseThrow(() -> new NotFoundException("No Guild found with id " + guildMember.getGuildId()));

emailSender
.sendEmail("Membership Changes have been made to the " + guild.getName() + " guild",
.sendEmail(null, null, "Membership Changes have been made to the " + guild.getName() + " guild",
constructEmailContent(guildMember, false),
getGuildLeadsEmails(guildLeads, guildMember).toArray(new String[0])
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.objectcomputing.checkins.notifications.email.EmailSender;
import com.objectcomputing.checkins.services.feedback_request.FeedbackRequest;
import com.objectcomputing.checkins.services.feedback_request.FeedbackRequestRepository;
import com.objectcomputing.checkins.services.memberprofile.MemberProfile;
import com.objectcomputing.checkins.services.memberprofile.MemberProfileServices;
import io.micronaut.context.annotation.Property;
import jakarta.inject.Singleton;
Expand Down Expand Up @@ -37,8 +38,10 @@ public boolean GetTodaysRequests() {
List<FeedbackRequest> todaysRequests = new ArrayList<>();
todaysRequests.addAll(feedbackReqRepository.findByValues(null, null, null, today, null, null));
for (FeedbackRequest req: todaysRequests) {
MemberProfile from = memberProfileServices.getById(req.getCreatorId());
String fromName = from.getFirstName() + " " + from.getLastName();
String newContent = notificationContent + "<a href=\""+submitURL+req.getId()+"\">Check-Ins application</a>.";
emailSender.sendEmail(notificationSubject, newContent);
emailSender.sendEmail(fromName, from.getWorkEmail(), notificationSubject, newContent);
}

return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ void testSendAndSaveHtmlEmail() {
email.put("html", true);
email.put("recipients", List.of(recipient1.getWorkEmail(), recipient2.getWorkEmail()));

when(htmlEmailSender.sendEmailReceivesStatus(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
when(htmlEmailSender.sendEmailReceivesStatus(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);

final HttpRequest<?> request = HttpRequest.POST("", email)
.basicAuth(admin.getWorkEmail(), RoleType.Constants.ADMIN_ROLE);
Expand All @@ -102,8 +102,8 @@ void testSendAndSaveHtmlEmail() {
assertEquals(recipient2.getId(), secondEmailRes.getRecipient());
assertTrue(secondEmailRes.getTransmissionDate().isAfter(secondEmailRes.getSendDate()));

verify(htmlEmailSender).sendEmailReceivesStatus("Email Subject", "<p>Email content</p>", recipient1.getWorkEmail(), recipient2.getWorkEmail());
verify(textEmailSender, never()).sendEmailReceivesStatus(anyString(), anyString(), anyString(), anyString());
verify(htmlEmailSender).sendEmailReceivesStatus(admin.getFirstName()+" "+admin.getLastName(), admin.getWorkEmail(),"Email Subject", "<p>Email content</p>", recipient1.getWorkEmail(), recipient2.getWorkEmail());
verify(textEmailSender, never()).sendEmailReceivesStatus(anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
}

@Test
Expand All @@ -119,7 +119,7 @@ void testSendAndSaveTextEmail() {
email.put("html", false);
email.put("recipients", List.of(recipient1.getWorkEmail(), recipient2.getWorkEmail()));

when(textEmailSender.sendEmailReceivesStatus(anyString(), anyString(), anyString(), anyString())).thenReturn(true);
when(textEmailSender.sendEmailReceivesStatus(anyString(), anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true);

final HttpRequest<?> request = HttpRequest.POST("", email)
.basicAuth(admin.getWorkEmail(), RoleType.Constants.ADMIN_ROLE);
Expand All @@ -144,8 +144,8 @@ void testSendAndSaveTextEmail() {
assertEquals(recipient2.getId(), secondEmailRes.getRecipient());
assertTrue(secondEmailRes.getTransmissionDate().isAfter(secondEmailRes.getSendDate()));

verify(textEmailSender).sendEmailReceivesStatus("Email Subject", "Email content", recipient1.getWorkEmail(), recipient2.getWorkEmail());
verify(htmlEmailSender, never()).sendEmailReceivesStatus(anyString(), anyString(), anyString(), anyString());
verify(textEmailSender).sendEmailReceivesStatus(admin.getFirstName()+" "+admin.getLastName(), admin.getWorkEmail(), "Email Subject", "Email content", recipient1.getWorkEmail(), recipient2.getWorkEmail());
verify(htmlEmailSender, never()).sendEmailReceivesStatus(anyString(), anyString(), anyString(), anyString(), anyString(), anyString());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -226,10 +226,11 @@ void testCreateFeedbackRequestSendsEmail() {
.basicAuth(pdlMemberProfile.getWorkEmail(), RoleType.Constants.PDL_ROLE);
final HttpResponse<FeedbackRequestResponseDTO> response = client.toBlocking().exchange(request, FeedbackRequestResponseDTO.class);

String fromName = pdlMemberProfile.getFirstName()+" "+pdlMemberProfile.getLastName();
//verify appropriate email was sent
assertTrue(response.getBody().isPresent());
String correctContent = createEmailContent(feedbackRequest, response.getBody().get().getId(), pdlMemberProfile, employeeMemberProfile);
verify(emailSender).sendEmail(notificationSubject, correctContent, recipient.getWorkEmail());
verify(emailSender).sendEmail(fromName, pdlMemberProfile.getWorkEmail(), notificationSubject, correctContent, recipient.getWorkEmail());
}

@Test
Expand Down Expand Up @@ -1056,10 +1057,11 @@ void testFeedbackRequestEnableEditsSendsEmail() {
.basicAuth(pdl.getWorkEmail(), RoleType.Constants.PDL_ROLE);
final HttpResponse<FeedbackRequestResponseDTO> response = client.toBlocking().exchange(request, FeedbackRequestResponseDTO.class);

String fromName = pdl.getFirstName()+" "+pdl.getLastName();
// Verify appropriate email was sent
assertTrue(response.getBody().isPresent());
String correctContent = updateEmailContent(response.getBody().get().getId(), pdl, requestee);
verify(emailSender).sendEmail(notificationSubject, correctContent, recipient.getWorkEmail());
verify(emailSender).sendEmail(fromName, pdl.getWorkEmail(), notificationSubject, correctContent, recipient.getWorkEmail());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ void testEmailSentToGuildLeadWhenGuildMembersAdded() {
final HttpRequest<GuildUpdateDTO> request = HttpRequest.PUT("/", requestBody).basicAuth(memberProfileOfAdmin.getWorkEmail(), ADMIN_ROLE);
client.toBlocking().exchange(request, GuildResponseDTO.class);

verify(emailSender).sendEmail(
verify(emailSender).sendEmail(null, null,
"Membership Changes have been made to the Ninja guild",
"<h3>Changes have been made to the Ninja guild.</h3><h4>The following members have been added:</h4><ul><li>Bill Charles</li></ul><a href=\"https://checkins.objectcomputing.com/guilds\">Click here</a> to view the changes in the Check-Ins app.",
"[email protected]"
Expand Down Expand Up @@ -109,7 +109,7 @@ void testEmailSentToGuildLeadWhenGuildMembersRemoved() {
final HttpRequest<GuildUpdateDTO> request = HttpRequest.PUT("/", requestBody).basicAuth(memberProfileOfAdmin.getWorkEmail(), ADMIN_ROLE);
client.toBlocking().exchange(request, GuildResponseDTO.class);

verify(emailSender).sendEmail(
verify(emailSender).sendEmail(null, null,
"Membership Changes have been made to the Ninja guild",
"<h3>Changes have been made to the Ninja guild.</h3><h4>The following members have been removed:</h4><ul><li>Bill Charles</li></ul><a href=\"https://checkins.objectcomputing.com/guilds\">Click here</a> to view the changes in the Check-Ins app.",
"[email protected]"
Expand Down
Loading

0 comments on commit e8d9310

Please sign in to comment.