55 lines
2.1 KiB
JavaScript
55 lines
2.1 KiB
JavaScript
module.exports = Self => {
|
|
Self.observe('after save', async ctx => {
|
|
const instance = ctx.data || ctx.instance;
|
|
const models = Self.app.models;
|
|
const options = ctx.options;
|
|
const notificationName = 'backup-printer-selected';
|
|
const userId = ctx.options.accessToken?.userId || instance.workerFk;
|
|
|
|
if (!instance?.sectorFk || !instance?.labelerFk) return;
|
|
|
|
const sector = await models.Sector.findById(instance.sectorFk, {
|
|
fields: ['backupPrinterFk']
|
|
}, options);
|
|
|
|
if (sector.backupPrinterFk && sector.backupPrinterFk == instance.labelerFk) {
|
|
const {labelerFk, sectorFk} = instance;
|
|
const [{delay}] = await models.Notification.find({where: {name: notificationName}});
|
|
|
|
if (delay) {
|
|
const now = Date.vnNow() - (delay * 1000) + (3600 * 1000);
|
|
const notifications = await models.NotificationQueue.find(
|
|
{where:
|
|
|
|
{created: {gte: now},
|
|
notificationFk: notificationName,
|
|
status: 'sent'
|
|
}
|
|
});
|
|
|
|
const criteria = {labelerId: labelerFk, sectorId: sectorFk};
|
|
const filteredNotifications = notifications.filter(notification => {
|
|
const paramsObj = JSON.parse(notification.params);
|
|
return Object.keys(criteria).every(key => criteria[key] === paramsObj?.[key]);
|
|
});
|
|
|
|
if (filteredNotifications.length >= 1)
|
|
throw new Error('Previous notification sended with the same parameters');
|
|
}
|
|
|
|
await models.NotificationQueue.create({
|
|
notificationFk: notificationName,
|
|
authorFk: userId,
|
|
params: JSON.stringify(
|
|
{
|
|
'labelerId': instance.labelerFk,
|
|
'sectorId': instance.sectorFk,
|
|
'workerId': userId
|
|
}
|
|
)
|
|
});
|
|
}
|
|
});
|
|
};
|
|
|