-
Notifications
You must be signed in to change notification settings - Fork 3
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
chore: add exit code on error #3638
Draft
AntBush
wants to merge
13
commits into
main
Choose a base branch
from
NDT-557-notification-for-email-cron-job-error
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+616
−3
Draft
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
4a2cf05
feat: send emails for milestone when due in 30 days
AntBush 54fcb80
feat: milestone cron
AntBush bdd400b
chore: update for correct permissions
AntBush 333366f
chore: update the cron with better container name
AntBush 271b63e
test: add tests api route and notify
AntBush 681844f
chore: add limiter
AntBush ff1a093
chore: fix failing test and add limiter
AntBush 9e2ee23
feat: service account permissions and get scope in request
AntBush c66487e
chore: schedule is now every day not just weekdays
AntBush e34cfda
chore: add limiter to serviceaccount route
AntBush e1992e1
chore: add console log
AntBush e5040ff
chore: update to handle multiple milestones due on the same day
AntBush 0c38cf3
chore: have process exit with error if condition is met
AntBush File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
78 changes: 78 additions & 0 deletions
78
app/backend/lib/emails/templates/notifyMilestoneReportDue.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
import { performQuery } from '../../graphql'; | ||
import { Context } from '../../ches/sendEmailMerge'; | ||
import { | ||
EmailTemplate, | ||
EmailTemplateProvider, | ||
replaceEmailsInNonProd, | ||
} from '../handleEmailNotification'; | ||
|
||
const getAnalystInfoByUserIds = ` | ||
query getAnalystNameByUserIds($_rowIds: [Int!]!) { | ||
allAnalysts(filter: {rowId: {in: $_rowIds}}) { | ||
nodes { | ||
givenName | ||
} | ||
} | ||
} | ||
`; | ||
const getEmails = async (ids: number[], req: any) => { | ||
const results = await performQuery( | ||
getAnalystInfoByUserIds, | ||
{ _rowIds: ids }, | ||
req | ||
); | ||
return results?.data?.allAnalysts.nodes; | ||
}; | ||
|
||
const notifyMilestoneReportDue: EmailTemplateProvider = async ( | ||
applicationId: string, | ||
url: string, | ||
initiator: any, | ||
params: any, | ||
req | ||
): Promise<EmailTemplate> => { | ||
const { milestoneReportData } = params; | ||
const recipients = [70, 71]; | ||
|
||
const emails = await getEmails(recipients, req); | ||
|
||
const contexts = emails.map((email) => { | ||
const { givenName, email: recipientEmail } = email; | ||
const emailTo = replaceEmailsInNonProd([recipientEmail]); | ||
const emailCC = replaceEmailsInNonProd([]); | ||
return { | ||
to: emailTo, | ||
cc: emailCC, | ||
context: { | ||
recipientName: givenName, | ||
milestones: milestoneReportData, | ||
}, | ||
delayTS: 0, | ||
tag: 'milestone-due', | ||
} as Context; | ||
}); | ||
|
||
const subject = `Reminder: Milestone Report${milestoneReportData.length > 1 ? 's' : ''} ${milestoneReportData.length > 1 ? 'are' : 'is'} coming Due`; | ||
|
||
return { | ||
emailTo: [], | ||
emailCC: [], | ||
tag: 'milestone-due', | ||
subject, | ||
body: ` | ||
<p>Hi {{ recipientName | trim }} </p> | ||
<p>This is a notification to let you know that one or more Milestone Reports are coming due in 30 days: <p> | ||
<ul> | ||
{% for milestone in milestones %} | ||
<li>Milestone {{ milestone.milestoneNumber }} for {{ milestone.organizationName | trim }}. Project: {{ milestone.ccbcNumber }}. Due {{ milestone.milestoneDate }}</li> | ||
{% endfor %} | ||
</ul> | ||
<p>To unsubscribe from these email notifications, email [email protected]</p> | ||
`, | ||
contexts, | ||
params: { milestoneReportData }, | ||
}; | ||
}; | ||
|
||
export default notifyMilestoneReportDue; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,175 @@ | ||
import { Router } from 'express'; | ||
import RateLimit from 'express-rate-limit'; | ||
import getAuthRole from '../../utils/getAuthRole'; | ||
import { performQuery } from './graphql'; | ||
import handleEmailNotification from './emails/handleEmailNotification'; | ||
import notifyMilestoneReportDue from './emails/templates/notifyMilestoneReportDue'; | ||
import validateKeycloakToken from './keycloakValidate'; | ||
|
||
const limiter = RateLimit({ | ||
windowMs: 1 * 60 * 1000, | ||
max: 30, | ||
}); | ||
|
||
const milestonesRouter = Router(); | ||
|
||
const processMilestones = async (req, res) => { | ||
// GraphQL query to get all milestones with archivedAt: null | ||
const sowMilestoneQuery = ` | ||
query MilestoneDatesQuery { | ||
allApplicationSowData( | ||
orderBy: AMENDMENT_NUMBER_DESC | ||
filter: {archivedAt: {isNull: true}} | ||
) { | ||
nodes { | ||
applicationId | ||
applicationByApplicationId { | ||
ccbcNumber | ||
organizationName | ||
projectName | ||
} | ||
sowTab2SBySowId( | ||
first: 1 | ||
orderBy: ID_DESC | ||
filter: {archivedAt: {isNull: true}} | ||
) { | ||
nodes { | ||
jsonData | ||
} | ||
} | ||
} | ||
} | ||
} | ||
`; | ||
let result; | ||
const applicationRowIdsVisited = new Set(); | ||
|
||
try { | ||
result = await performQuery(sowMilestoneQuery, {}, req); | ||
} catch (error) { | ||
return res.status(500).json({ error: result.error }).end(); | ||
} | ||
|
||
const today = new Date(); | ||
// Function to check if a given due date string is within 30 to 31 days from today. | ||
const isWithin30To31Days = (dueDateStr) => { | ||
const dueDate = new Date(dueDateStr); | ||
const timeDiff = dueDate.getTime() - today.getTime(); | ||
const daysDiff = timeDiff / (1000 * 3600 * 24); | ||
return daysDiff >= 30 && daysDiff <= 31; | ||
}; | ||
|
||
// Traverse the result, if there is a milestone due date within 30 to 31 days from today, | ||
// add the application row ID, CCBC number, and whether it is a milestone 1 or 2 to a list. | ||
const milestoneReportData = result.data.allApplicationSowData.nodes.reduce( | ||
(acc, node) => { | ||
const { applicationId, applicationByApplicationId, sowTab2SBySowId } = | ||
node; | ||
if (applicationRowIdsVisited.has(applicationId)) { | ||
return acc; | ||
} | ||
const { ccbcNumber, organizationName, projectName } = | ||
applicationByApplicationId; | ||
const milestoneData: Array<any> = sowTab2SBySowId.nodes[0] | ||
?.jsonData as Array<any>; | ||
const milestoneOneDue = milestoneData.find((milestone) => | ||
isWithin30To31Days(milestone.milestone1) | ||
); | ||
const milestoneTwoDue = milestoneData.find((milestone) => | ||
isWithin30To31Days(milestone.milestone2) | ||
); | ||
const milestoneThreeDue = milestoneData.find((milestone) => | ||
isWithin30To31Days(milestone.milestone3) | ||
); | ||
if (milestoneOneDue) { | ||
const applicationRowId = applicationId; | ||
if (!applicationRowIdsVisited.has(applicationRowId)) { | ||
acc.push({ | ||
applicationRowId, | ||
ccbcNumber, | ||
organizationName, | ||
projectName, | ||
milestoneNumber: '1', | ||
milestoneDate: new Date( | ||
milestoneOneDue.milestone1 | ||
).toLocaleDateString(), | ||
}); | ||
applicationRowIdsVisited.add(applicationRowId); | ||
} | ||
} | ||
if (milestoneTwoDue) { | ||
const applicationRowId = applicationId; | ||
if (!applicationRowIdsVisited.has(applicationRowId)) { | ||
acc.push({ | ||
applicationRowId, | ||
ccbcNumber, | ||
organizationName, | ||
projectName, | ||
milestoneNumber: '2', | ||
milestoneDate: new Date( | ||
milestoneTwoDue.milestone2 | ||
).toLocaleDateString(), | ||
}); | ||
applicationRowIdsVisited.add(applicationRowId); | ||
} | ||
} | ||
if (milestoneThreeDue) { | ||
const applicationRowId = applicationId; | ||
if (!applicationRowIdsVisited.has(applicationRowId)) { | ||
acc.push({ | ||
applicationRowId, | ||
ccbcNumber, | ||
organizationName, | ||
projectName, | ||
milestoneNumber: '3', | ||
milestoneDate: new Date( | ||
milestoneThreeDue.milestone3 | ||
).toLocaleDateString(), | ||
}); | ||
applicationRowIdsVisited.add(applicationRowId); | ||
} | ||
} | ||
return acc; | ||
}, | ||
[] | ||
); | ||
|
||
if (milestoneReportData.length > 0) { | ||
// Send an email to the analyst with the list of applications that have milestones due within 30 to 31 days. | ||
return handleEmailNotification( | ||
req, | ||
res, | ||
notifyMilestoneReportDue, | ||
{ milestoneReportData }, | ||
true | ||
); | ||
} | ||
|
||
return res | ||
.status(200) | ||
.json({ message: 'No milestones due in 30 days' }) | ||
.end(); | ||
}; | ||
|
||
milestonesRouter.get('/api/analyst/milestone/upcoming', limiter, (req, res) => { | ||
const authRole = getAuthRole(req); | ||
const isRoleAuthorized = | ||
authRole?.pgRole === 'ccbc_admin' || authRole?.pgRole === 'super_admin'; | ||
|
||
if (!isRoleAuthorized) { | ||
return res.status(404).end(); | ||
} | ||
return processMilestones(req, res); | ||
}); | ||
|
||
milestonesRouter.get( | ||
'/api/analyst/cron-milestones', | ||
limiter, | ||
validateKeycloakToken, | ||
(req, res) => { | ||
req.claims.identity_provider = 'serviceaccount'; | ||
processMilestones(req, res); | ||
} | ||
); | ||
|
||
export default milestonesRouter; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
app/tests/backend/lib/emails/templates/notifyMilestoneReportDue.test.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
import { mocked } from 'jest-mock'; | ||
import notifyMilestoneReportDue from '../../../../../backend/lib/emails/templates/notifyMilestoneReportDue'; | ||
import { performQuery } from '../../../../../backend/lib/graphql'; | ||
|
||
jest.mock('../../../../../backend/lib/graphql', () => ({ | ||
performQuery: jest.fn(), | ||
})); | ||
|
||
jest.mock('../../../../../backend/lib/emails/handleEmailNotification', () => ({ | ||
replaceEmailsInNonProd: jest.fn((emails) => emails), | ||
})); | ||
|
||
describe('notifyMilestoneReportDue template', () => { | ||
it('should return an email template with correct properties', async () => { | ||
const req = { | ||
body: { applicationId: '1', host: 'http://mock_host.ca' }, | ||
}; | ||
|
||
// Mock the performQuery function to return analyst data | ||
mocked(performQuery).mockResolvedValue({ | ||
data: { | ||
allAnalysts: { | ||
nodes: [ | ||
{ | ||
email: '[email protected]', | ||
givenName: 'Analyst One', | ||
}, | ||
{ | ||
email: '[email protected]', | ||
givenName: 'Analyst Two', | ||
}, | ||
], | ||
}, | ||
}, | ||
}); | ||
|
||
const applicationId = '1'; | ||
const url = 'http://mock_host.ca'; | ||
const milestoneReportData = [ | ||
{ | ||
milestoneNumber: 1, | ||
organizationName: 'Organization A', | ||
ccbcNumber: 'CCBC-000001', | ||
milestoneDate: '2023-11-01', | ||
}, | ||
{ | ||
milestoneNumber: 2, | ||
organizationName: 'Organization B', | ||
ccbcNumber: 'CCBC-000002', | ||
milestoneDate: '2023-12-01', | ||
}, | ||
]; | ||
|
||
const params = { milestoneReportData }; | ||
const emailTemplate = await notifyMilestoneReportDue( | ||
applicationId, | ||
url, | ||
{}, | ||
params, | ||
req | ||
); | ||
|
||
// Check that the subject is correct | ||
expect(emailTemplate.subject).toEqual( | ||
'Reminder: Milestone Reports are coming Due' | ||
); | ||
|
||
// Ensure contexts are created for each analyst | ||
expect(emailTemplate.contexts.length).toBe(2); | ||
|
||
// Validate the first context | ||
expect(emailTemplate.contexts[0].to).toEqual(['[email protected]']); | ||
expect(emailTemplate.contexts[0].context.recipientName).toEqual( | ||
'Analyst One' | ||
); | ||
expect(emailTemplate.contexts[0].context.milestones).toEqual( | ||
milestoneReportData | ||
); | ||
|
||
// Validate the second context | ||
expect(emailTemplate.contexts[1].to).toEqual(['[email protected]']); | ||
expect(emailTemplate.contexts[1].context.recipientName).toEqual( | ||
'Analyst Two' | ||
); | ||
expect(emailTemplate.contexts[1].context.milestones).toEqual( | ||
milestoneReportData | ||
); | ||
|
||
// Check other properties | ||
expect(emailTemplate.tag).toEqual('milestone-due'); | ||
expect(emailTemplate.params).toEqual({ milestoneReportData }); | ||
|
||
// Optionally, you can check the body content if needed | ||
expect(emailTemplate.body).toContain( | ||
'<p>Hi {{ recipientName | trim }} </p>' | ||
); | ||
}); | ||
}); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Check warning
Code scanning / ESLint
Disallow the use of `console` Warning