84 lines
2.7 KiB
JavaScript
84 lines
2.7 KiB
JavaScript
const {Email} = require('vn-print');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethod('send', {
|
|
description: 'Send notifications from queue',
|
|
accessType: 'WRITE',
|
|
returns: {
|
|
type: 'object',
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/send`,
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.send = async options => {
|
|
const models = Self.app.models;
|
|
|
|
const myOptions = {};
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
const notificationQueue = await models.NotificationQueue.find({
|
|
where: {status: 'pending'},
|
|
include: [
|
|
{
|
|
relation: 'notification',
|
|
scope: {
|
|
include: [{
|
|
relation: 'subscription',
|
|
scope: {
|
|
include: {
|
|
relation: 'user',
|
|
scope: {
|
|
fields: ['name', 'lang'],
|
|
include: {
|
|
relation: 'emailUser'
|
|
}
|
|
}
|
|
}
|
|
},
|
|
}, {
|
|
relation: 'notificationTemplate',
|
|
fields: ['id']
|
|
}]
|
|
}
|
|
|
|
}]
|
|
}, myOptions);
|
|
|
|
const statusSent = 'sent';
|
|
|
|
for (const queue of notificationQueue) {
|
|
const queueName = queue.notification().notificationTemplate().code;
|
|
const queueParams = JSON.parse(queue.params);
|
|
|
|
for (const notificationUser of queue.notification().subscription()) {
|
|
try {
|
|
const sendParams = {
|
|
recipient: 'pablone.verdnatura@gmail.com',
|
|
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);
|
|
|
|
if (process.env.NODE_ENV != 'test')
|
|
await email.send();
|
|
|
|
await queue.updateAttribute('status', statusSent);
|
|
} catch (error) {
|
|
await queue.updateAttribute('status', 'error');
|
|
}
|
|
}
|
|
}
|
|
};
|
|
};
|