From 25011db767f67e69a8ab71aee656cf6d7ded1c1b Mon Sep 17 00:00:00 2001 From: JT Smith Date: Wed, 15 Jan 2025 16:22:47 -0600 Subject: [PATCH] Added EmailRole job handler. --- ving/jobs/handlers/EmailRole.mjs | 33 +++++++++++++++++++++++++++++--- ving/jobs/map.mjs | 4 +++- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/ving/jobs/handlers/EmailRole.mjs b/ving/jobs/handlers/EmailRole.mjs index 3ae43f7c..167c6352 100644 --- a/ving/jobs/handlers/EmailRole.mjs +++ b/ving/jobs/handlers/EmailRole.mjs @@ -1,15 +1,42 @@ import ving from '#ving/index.mjs'; +import { sendMail } from '#ving/email/send.mjs'; +import { useKind } from '#ving/record/utils.mjs'; +import { eq } from '#ving/drizzle/orm.mjs'; /** * This handler looks up all users with a specified role and sends them an email. * @param {Object} job A `BullMQ` job. * @param {Object} job.data An object with data needed for this job. + * @param {string} job.data.role The name of a role on the User record that if true will be sent this email. + * @param {string} job.data.subject The subject line of the email. + * @param {string} job.data.summary A very short summary of the message. + * @param {string} job.data.message The message body of the email. * @returns {boolean} `true` */ export default async function (job) { - ving.log('jobs').debug(`Test ran with data: ${JSON.stringify(job.data)} which is a ${typeof job.data}`); - if (job.data.error) { - throw new Error(job.data.error); + const users = await useKind('User'); + const roleUsers = await users.findMany(eq(users.table[job.data.role], true)); + ving.log('jobs').info(`${job.id} found ${roleUsers.length} users to send emails to.`); + let succeeded = 0; + let failures = 0; + for (const user of roleUsers) { + const vars = { + subject: job.data.subject, + summary: job.data.summary, + message: job.data.message, + }; + try { + await sendMail('generic', { + options: { to: user.get('email') }, + vars + }); + succeeded++; + } + catch (err) { + failures++; + ving.log('jobs').error(`${job.id} failed to send email to user ${user.get('id')} ${user.get('email')} because ${err.message} with message ${JSON.stringify(vars)}`); + } } + ving.log('jobs').info(`${job.id} sent ${succeeded} emails with ${failures} failures.`) return true; } \ No newline at end of file diff --git a/ving/jobs/map.mjs b/ving/jobs/map.mjs index fbcdaaca..15e25ef3 100644 --- a/ving/jobs/map.mjs +++ b/ving/jobs/map.mjs @@ -1,9 +1,11 @@ import Test from "#ving/jobs/handlers/Test.mjs"; import DeleteUnusedS3File from "#ving/jobs/handlers/DeleteUnusedS3File.mjs"; import CronJob from "#ving/jobs/handlers/CronJob.mjs"; +import EmailRole from "#ving/jobs/handlers/EmailRole.mjs"; export const jobHandlers = { Test, DeleteUnusedS3File, - CronJob + CronJob, + EmailRole } \ No newline at end of file