salix/back/methods/notification/send.js

85 lines
2.7 KiB
JavaScript
Raw Permalink Normal View History

const {Email} = require('vn-print');
2024-05-21 13:11:32 +00:00
const isProduction = require('vn-loopback/server/boot/isProduction');
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:27:05 +00:00
fields: ['name', 'lang'],
2022-11-18 09:25:25 +00:00
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);
2024-05-21 13:11:32 +00:00
if (isProduction())
2022-10-17 10:12:10 +00:00
await email.send();
await queue.updateAttribute('status', statusSent);
} catch (error) {
await queue.updateAttribute('status', statusError);
}
}
}
2022-07-19 13:17:22 +00:00
};
};