|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +const Services = { |
| 4 | + Email: require("./email.service"), |
| 5 | + Hacker: require("./hacker.service"), |
| 6 | + Logger: require("./logger.service"), |
| 7 | +}; |
| 8 | + |
| 9 | +const TAG = "[AutomatedEmail.Service]"; |
| 10 | + |
| 11 | +class AutomatedEmailService { |
| 12 | + /** |
| 13 | + * Send status emails to all hackers with the given status |
| 14 | + * @param {string} status - "Accepted", "Declined" |
| 15 | + * @returns {Promise<{success: number, failed: number}>} Number of successful and failed emails |
| 16 | + */ |
| 17 | + async sendAutomatedStatusEmails(status) { |
| 18 | + const results = { success: 0, failed: 0 }; |
| 19 | + try { |
| 20 | + // Get all hackers with the specified status |
| 21 | + const hackers = await Services.Hacker.findByStatus(status); |
| 22 | + |
| 23 | + // Send emails in parallel |
| 24 | + const emailPromises = hackers.map(async (hacker) => { |
| 25 | + try { |
| 26 | + await new Promise((resolve, reject) => { |
| 27 | + Services.Email.sendStatusUpdate( |
| 28 | + hacker.accountId.firstName, |
| 29 | + hacker.accountId.email, |
| 30 | + status, |
| 31 | + (err) => { |
| 32 | + if (err) { |
| 33 | + reject(err); |
| 34 | + } else { |
| 35 | + resolve(); |
| 36 | + } |
| 37 | + }, |
| 38 | + ); |
| 39 | + }); |
| 40 | + results.success++; |
| 41 | + } catch (err) { |
| 42 | + Services.Logger.error( |
| 43 | + `${TAG} Failed to send ${status} email to ${hacker.accountId.email}: ${err}`, |
| 44 | + ); |
| 45 | + results.failed++; |
| 46 | + } |
| 47 | + }); |
| 48 | + |
| 49 | + await Promise.all(emailPromises); |
| 50 | + return results; |
| 51 | + } catch (err) { |
| 52 | + Services.Logger.error( |
| 53 | + `${TAG} Error in sendAutomatedStatusEmails: ${err}`, |
| 54 | + ); |
| 55 | + throw err; |
| 56 | + } |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +module.exports = new AutomatedEmailService(); |
0 commit comments