-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathautomatedEmails.service.js
More file actions
85 lines (76 loc) · 2.79 KB
/
automatedEmails.service.js
File metadata and controls
85 lines (76 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"use strict";
const Services = {
Email: require("./email.service"),
Hacker: require("./hacker.service"),
Logger: require("./logger.service"),
};
const TAG = "[AutomatedEmail.Service]";
class AutomatedEmailService {
/**
* Get count of hackers with the given status
* @param {string} status - "Accepted", "Declined"
* @returns {Promise<number>} Count of hackers with the status
*/
async getStatusCount(status) {
try {
const hackers = await Services.Hacker.findByStatus(status);
if (!hackers || !Array.isArray(hackers)) {
return 0;
}
return hackers.length;
} catch (err) {
Services.Logger.error(`${TAG} Error in getStatusCount: ${err}`);
throw err;
}
}
/**
* Send status emails to all hackers with the given status
* @param {string} status - "Accepted", "Declined"
* @returns {Promise<{success: number, failed: number}>}
*/
async sendAutomatedStatusEmails(status) {
const results = { success: 0, failed: 0 };
try {
const hackers = await Services.Hacker.findByStatus(status);
if (!hackers || !Array.isArray(hackers)) {
throw new Error(
`Expected array from findByStatus(${status}), got ${typeof hackers}`,
);
}
// Override: send Declined emails to Applied hackers
const emailStatus = status === "Applied" ? "Declined" : status;
const emailPromises = hackers.map(async (hacker) => {
try {
await new Promise((resolve, reject) => {
Services.Email.sendStatusUpdate(
hacker.accountId.firstName,
hacker.accountId.email,
emailStatus,
(err) => {
if (err) {
reject(err);
} else {
resolve();
}
},
);
});
results.success++;
} catch (err) {
Services.Logger.error(
`${TAG} Failed to send ${emailStatus} email to ${hacker.accountId.email}: ${err}`,
);
results.failed++;
}
});
await Promise.all(emailPromises);
return results;
} catch (err) {
Services.Logger.error(
`${TAG} Error in sendAutomatedStatusEmails: ${err}`,
);
throw err;
}
}
}
module.exports = new AutomatedEmailService();