salix/back/methods/notification/send.js

84 lines
2.7 KiB
JavaScript
Raw Normal View History

const {Email} = require('vn-print');
2022-07-19 13:17:22 +00:00
module.exports = Self => {
Self.remoteMethod('send', {
description: 'Send notifications from queue',
accessType: 'WRITE',
2022-07-19 13:17:22 +00:00
returns: {
type: 'object',
root: true
},
http: {
path: `/send`,
verb: 'POST'
}
});
Self.send = async options => {
const models = Self.app.models;
const findStatus = 'pending';
2022-07-19 13:17:22 +00:00
2022-07-20 12:54:50 +00:00
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const notificationQueue = await models.NotificationQueue.find({
where: {status: findStatus},
include: [
{
relation: 'notification',
scope: {
include: {
relation: 'subscription',
scope: {
include: {
relation: 'user',
scope: {
2022-11-18 09:25:25 +00:00
fields: ['name', 'email', 'lang'],
include: {
relation: 'emailUser'
}
}
}
}
}
}
}
]
2022-07-20 12:54:50 +00:00
}, myOptions);
const statusSent = 'sent';
const statusError = 'error';
for (const queue of notificationQueue) {
const queueName = queue.notification().name;
const queueParams = JSON.parse(queue.params);
for (const notificationUser of queue.notification().subscription()) {
try {
const sendParams = {
2022-11-18 09:25:25 +00:00
recipient: notificationUser.user().emailUser().email,
lang: notificationUser.user().lang
};
if (notificationUser.userFk == queue.authorFk) {
await queue.updateAttribute('status', statusSent);
continue;
}
const newParams = Object.assign({}, queueParams, sendParams);
const email = new Email(queueName, newParams);
2022-10-17 10:12:10 +00:00
if (process.env.NODE_ENV != 'test')
await email.send();
await queue.updateAttribute('status', statusSent);
} catch (error) {
await queue.updateAttribute('status', statusError);
}
}
}
2022-07-19 13:17:22 +00:00
};
};