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 {backupPrinterNotificationDelay} = await models.ProductionConfig.findOne(); if (backupPrinterNotificationDelay) { const notifications = await models.NotificationQueue.find( {where: {created: {gte: new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000))}, notificationFk: notificationName, status: {neq: 'error'} } }); 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) return; } await models.NotificationQueue.create({ notificationFk: notificationName, authorFk: userId, params: JSON.stringify( { 'labelerId': instance.labelerFk, 'sectorId': instance.sectorFk, 'workerId': userId } ) }); } }); };