2022-10-14 11:22:53 +00:00
|
|
|
const {Email} = require('vn-print');
|
2022-07-25 06:25:10 +00:00
|
|
|
|
2022-07-19 13:17:22 +00:00
|
|
|
module.exports = Self => {
|
|
|
|
Self.remoteMethod('send', {
|
|
|
|
description: 'Send notifications from queue',
|
2022-07-25 06:25:10 +00:00
|
|
|
accessType: 'WRITE',
|
2022-07-19 13:17:22 +00:00
|
|
|
returns: {
|
|
|
|
type: 'object',
|
|
|
|
root: true
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/send`,
|
|
|
|
verb: 'POST'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2022-07-25 06:25:10 +00:00
|
|
|
Self.send = async options => {
|
|
|
|
const models = Self.app.models;
|
2022-10-14 11:22:53 +00:00
|
|
|
const findStatus = 'pending';
|
2022-07-19 13:17:22 +00:00
|
|
|
|
2022-07-20 12:54:50 +00:00
|
|
|
const myOptions = {};
|
2022-07-25 06:25:10 +00:00
|
|
|
if (typeof options == 'object')
|
|
|
|
Object.assign(myOptions, options);
|
|
|
|
|
|
|
|
const notificationQueue = await models.NotificationQueue.find({
|
2022-10-14 11:22:53 +00:00
|
|
|
where: {status: findStatus},
|
2022-07-25 06:25:10 +00:00
|
|
|
include: [
|
|
|
|
{
|
|
|
|
relation: 'notification',
|
|
|
|
scope: {
|
|
|
|
include: {
|
|
|
|
relation: 'subscription',
|
|
|
|
scope: {
|
|
|
|
include: {
|
|
|
|
relation: 'user',
|
|
|
|
scope: {
|
2022-11-18 08:57:07 +00:00
|
|
|
fields: ['name', 'lang']
|
2022-07-25 06:25:10 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
]
|
2022-07-20 12:54:50 +00:00
|
|
|
}, myOptions);
|
|
|
|
|
2022-07-25 06:25:10 +00:00
|
|
|
const statusSent = 'sent';
|
|
|
|
const statusError = 'error';
|
2022-10-14 11:22:53 +00:00
|
|
|
|
2022-07-25 06:25:10 +00:00
|
|
|
for (const queue of notificationQueue) {
|
2022-10-14 11:22:53 +00:00
|
|
|
const queueName = queue.notification().name;
|
|
|
|
const queueParams = JSON.parse(queue.params);
|
|
|
|
|
|
|
|
for (const notificationUser of queue.notification().subscription()) {
|
|
|
|
try {
|
|
|
|
const sendParams = {
|
2022-11-18 08:57:07 +00:00
|
|
|
recipient: notificationUser.user().name + '@verdnatura.es',
|
2022-10-14 11:22:53 +00:00
|
|
|
lang: notificationUser.user().lang
|
|
|
|
};
|
2022-07-25 06:25:10 +00:00
|
|
|
|
2022-10-14 11:22:53 +00:00
|
|
|
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();
|
2022-07-25 06:25:10 +00:00
|
|
|
|
2022-10-14 11:22:53 +00:00
|
|
|
await queue.updateAttribute('status', statusSent);
|
|
|
|
} catch (error) {
|
|
|
|
await queue.updateAttribute('status', statusError);
|
|
|
|
}
|
2022-07-25 06:25:10 +00:00
|
|
|
}
|
|
|
|
}
|
2022-07-19 13:17:22 +00:00
|
|
|
};
|
|
|
|
};
|