Skip to content

Commit

Permalink
feat: switch stfc email to use status actions (#711)
Browse files Browse the repository at this point in the history
  • Loading branch information
bashanlam authored Nov 4, 2024
2 parents fdb37e1 + b5b4626 commit 8db66de
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 221 deletions.
16 changes: 5 additions & 11 deletions apps/backend/src/eventHandlers/MailService/SMTPMailService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { MailService, STFCEmailTemplate, SendMailResults } from './MailService';
import { ResultsPromise } from './SparkPost';

export class SMTPMailService extends MailService {
private _email: EmailTemplates<any>;
private emailTemplates: EmailTemplates<any>;

constructor() {
super();
Expand All @@ -29,7 +29,7 @@ export class SMTPMailService extends MailService {
});
}

this._email = new EmailTemplates({
this.emailTemplates = new EmailTemplates({
message: {
from: process.env.EMAIL_SENDER,
attachments,
Expand Down Expand Up @@ -100,7 +100,7 @@ export class SMTPMailService extends MailService {
this.getEmailTemplatePath('html', options.content.template_id) + '.pug';

if (
!(await (this._email as any).templateExists(template)) &&
!(await (this.emailTemplates as any).templateExists(template)) &&
process.env.NODE_ENV !== 'test'
) {
logger.logError('Template does not exist', {
Expand All @@ -112,7 +112,7 @@ export class SMTPMailService extends MailService {

options.recipients.forEach((participant) => {
emailPromises.push(
this._email.send({
this.emailTemplates.send({
template: options.content.template_id,
message: {
...(typeof participant.address !== 'string'
Expand Down Expand Up @@ -155,15 +155,9 @@ export class SMTPMailService extends MailService {
});
}

async getEmailTemplates(
includeDraft = false
): ResultsPromise<STFCEmailTemplate[]> {
async getEmailTemplates(): ResultsPromise<STFCEmailTemplate[]> {
return {
results: [
{
id: 'call-created-email',
name: 'Call Created Email',
},
{
id: 'clf-proposal-submitted-pi',
name: 'CLF PI Co-I Submission Email',
Expand Down
210 changes: 0 additions & 210 deletions apps/backend/src/eventHandlers/email/stfcEmailHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,8 @@ import { logger } from '@user-office-software/duo-logger';
import { container } from 'tsyringe';

import { Tokens } from '../../config/Tokens';
import { AdminDataSource } from '../../datasources/AdminDataSource';
import { CallDataSource } from '../../datasources/CallDataSource';
import { InstrumentDataSource } from '../../datasources/InstrumentDataSource';
import { QuestionaryDataSource } from '../../datasources/QuestionaryDataSource';
import { UserDataSource } from '../../datasources/UserDataSource';
import { ApplicationEvent } from '../../events/applicationEvents';
import { Event } from '../../events/event.enum';
import { Proposal } from '../../models/Proposal';
import { SettingsId } from '../../models/Settings';
import { User } from '../../models/User';
import EmailSettings from '../MailService/EmailSettings';
import { MailService } from '../MailService/MailService';

Expand All @@ -22,148 +14,8 @@ export async function stfcEmailHandler(event: ApplicationEvent) {
}

const mailService = container.resolve<MailService>(Tokens.MailService);
const callDataSource = container.resolve<CallDataSource>(
Tokens.CallDataSource
);
const userDataSource = container.resolve<UserDataSource>(
Tokens.UserDataSource
);

switch (event.type) {
/*
* Send the PI and co-proposers an email when any proposal is submitted.
* Send the User Office an email when a Rapid Access proposal is submitted.
*/
case Event.PROPOSAL_SUBMITTED: {
const emailsToSend: EmailSettings[] = [];

const call = await callDataSource.getCall(event.proposal.callId);

const callTitle = call?.shortCode?.toLowerCase() || '';

const isIsis = callTitle.includes('isis');
const isRapidAccess = callTitle.includes('rapid');
const isClf = ['artemis', 'hpl', 'lsf'].some((fac) =>
callTitle.includes(fac)
);

let piEmailTemplate: string;

if (isIsis) {
piEmailTemplate = isRapidAccess
? 'isis-rapid-proposal-submitted-pi'
: 'isis-proposal-submitted-pi';
} else if (isClf) {
piEmailTemplate = 'clf-proposal-submitted-pi';
} else {
logger.logError(
'Could not send email because facility could not be determined from call title.',
{ event, call, callTitle: call?.shortCode }
);

return;
}

const principalInvestigator = await userDataSource.getUser(
event.proposal.proposerId
);

const participants = await userDataSource.getProposalUsersFull(
event.proposal.primaryKey
);

if (principalInvestigator) {
const piEmail = piSubmissionEmail(
piEmailTemplate,
event.proposal,
principalInvestigator,
participants
);

emailsToSend.push(piEmail);
} else {
logger.logError(
'Could not send submission confirmation email to PI and participants, as the PI details could not be retrieved.',
{ event }
);
}

if (isRapidAccess) {
const questionaries = container.resolve<QuestionaryDataSource>(
Tokens.QuestionaryDataSource
);
const instruments = container.resolve<InstrumentDataSource>(
Tokens.InstrumentDataSource
);

const answer = await questionaries.getAnswer(
event.proposal.questionaryId,
'isis_instrument_picker'
);

let instrumentRequested;

if (answer) {
instrumentRequested = (
await instruments.getInstrument(answer?.answer.value.instrumentId)
)?.name;
}

if (!instrumentRequested) {
logger.logError(
'Could not include instrument in the Rapid submission confirmation email to User Office.',
{ event }
);

instrumentRequested = '';
}

const adminDataSource = container.resolve<AdminDataSource>(
Tokens.AdminDataSource
);

const uoAddress = (
await adminDataSource.getSetting(SettingsId.USER_OFFICE_EMAIL)
)?.settingsValue;

if (uoAddress) {
const uoRapidEmail = uoRapidSubmissionEmail(
event.proposal,
instrumentRequested,
principalInvestigator,
participants,
uoAddress
);

emailsToSend.push(uoRapidEmail);
} else {
logger.logError(
'Could not send UO Rapid submission email as the setting (USER_OFFICE_EMAIL) is not set.',
{ event }
);
}
}

emailsToSend.forEach((emailSettings) => {
mailService
.sendMail(emailSettings)
.then((res: any) => {
logger.logInfo('Emails sent on proposal submission:', {
result: res,
event,
});
})
.catch((err: string) => {
logger.logError('Could not send email(s) on proposal submission:', {
error: err,
event,
});
});
});

return;
}

case Event.CALL_CREATED: {
if (event?.call) {
if (!(process.env && process.env.FBS_EMAIL)) {
Expand Down Expand Up @@ -208,68 +60,6 @@ export async function stfcEmailHandler(event: ApplicationEvent) {
}
}

const piSubmissionEmail = (
templateName: string,
proposal: Proposal,
pi: User,
participants: User[]
): EmailSettings => ({
content: {
template_id: templateName,
},
substitution_data: {
piPreferredname: pi.preferredname,
piLastname: pi.lastname,
proposalNumber: proposal.proposalId,
proposalTitle: proposal.title,
coProposers:
participants.length > 0
? participants.map(
(participant) =>
`${participant.preferredname} ${participant.lastname} `
)
: '-',
},
recipients: [
{ address: pi.email },
...participants.map((participant) => {
return {
address: {
email: participant.email,
header_to: pi.email,
},
};
}),
],
});

const uoRapidSubmissionEmail = (
proposal: Proposal,
instrument: string,
pi: User | null,
participants: User[],
uoAddress: string
): EmailSettings => ({
content: {
template_id: 'isis-rapid-proposal-submitted-uo',
},
substitution_data: {
piPreferredname: pi?.preferredname || '',
piLastname: pi?.lastname || '',
proposalNumber: proposal.proposalId,
proposalTitle: proposal.title,
coProposers:
participants.length > 0
? participants.map(
(participant) =>
`${participant.preferredname} ${participant.lastname} `
)
: '-',
instrument: instrument,
},
recipients: [{ address: uoAddress }],
});

const callCreationEmail = function createNotificationEmail<T>(
notificationInput: T,
templateID: string,
Expand Down

0 comments on commit 8db66de

Please sign in to comment.