6005-backupLabeler #2276

Merged
pablone merged 50 commits from 6005-backupLabeler into dev 2024-04-12 07:12:54 +00:00
26 changed files with 229 additions and 101 deletions

View File

@ -45,7 +45,6 @@ module.exports = Self => {
});
availableNotificationsMap.delete(active.notificationFk);
}
return {
active: [...activeNotificationsMap.entries()],
available: [...availableNotificationsMap.entries()]

View File

@ -4,8 +4,8 @@ describe('NotificationSubscription getList()', () => {
it('should return a list of available and active notifications of a user', async() => {
const userId = 9;
const {active, available} = await models.NotificationSubscription.getList(userId);
const notifications = await models.Notification.find({});
const totalAvailable = notifications.length - active.length;
const notifications = await models.NotificationSubscription.getAvailable(userId);
const totalAvailable = notifications.size - active.length;
expect(active.length).toEqual(3);
expect(available.length).toEqual(totalAvailable);

View File

@ -174,5 +174,8 @@
},
"WorkerActivityType": {
"dataSource": "vn"
},
"ProductionConfig": {
"dataSource": "vn"
}
}

View File

@ -0,0 +1,19 @@
{
"name": "ProductionConfig",
"base": "VnModel",
"options": {
"mysql": {
"table": "productionConfig"
}
},
"properties": {
"id": {
"type": "number",
"required": true,
"id": true
},
"backupPrinterNotificationDelay": {
"type": "string"
}
}
}

View File

@ -41,8 +41,7 @@ describe('loopback model NotificationSubscription', () => {
try {
const options = {transaction: tx, accessToken: {userId: 9}};
const notificationSubscriptionId = 2;
await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options);
await models.NotificationSubscription.destroyAll({id: 2}, options);
await tx.rollback();
} catch (e) {
@ -76,8 +75,7 @@ describe('loopback model NotificationSubscription', () => {
try {
const options = {transaction: tx, accessToken: {userId: 9}};
const notificationSubscriptionId = 6;
await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options);
await models.NotificationSubscription.destroyAll({id: 6}, options);
await tx.rollback();
} catch (e) {
@ -111,8 +109,7 @@ describe('loopback model NotificationSubscription', () => {
try {
const options = {transaction: tx, accessToken: {userId: 19}};
const notificationSubscriptionId = 4;
await models.NotificationSubscription.destroyAll({id: notificationSubscriptionId}, options);
await models.NotificationSubscription.destroyAll({id: 4}, options);
await tx.rollback();
} catch (e) {

View File

@ -113,9 +113,6 @@ INSERT INTO vn.ticket (clientFk, warehouseFk, shipped, nickname, refFk, addressF
(100, 4, '2022-07-12 00:00:00', 'root', NULL, 195, NULL, NULL, 0, 0, 0, 0, NULL, 0, '2022-07-12 16:18:58', 1, NULL, 4, NULL, 1, 567, 1, '2022-07-12', 0, 0, 6, NULL, NULL, NULL, NULL, NULL),
(100, 5, '2022-07-12 00:00:00', 'root', NULL, 195, NULL, NULL, 0, 0, 0, 0, NULL, 0, '2022-07-12 16:18:58', 1, NULL, 5, NULL, 1, 567, 1, '2022-07-12', 0, 0, 1, NULL, NULL, NULL, NULL, NULL);
*/
INSERT INTO vn.sector (description,warehouseFk) VALUES
('Sector One',1);
INSERT INTO vn.saleGroup (userFk,parkingFk,sectorFk) VALUES
(100,1,1);
@ -156,16 +153,6 @@ INSERT INTO `vn`.`occupationCode` (`code`, `name`)
('b', 'Representantes de comercio'),
('c', 'Personal de oficios en trabajos de construcción en general, y en instalac.,edificios y obras');
INSERT INTO `vn2008`.`payroll_employee` (`CodTrabajador`,`codempresa`)
VALUES
(36,20),
(43,20),
(76,20),
(1106,20),
(1107,20),
(1108,20),
(1109,20),
(1110,20);
INSERT INTO `vn`.`trainingCourseType` (`id`, `name`)
VALUES

View File

@ -198,7 +198,7 @@ INSERT INTO `vn`.`printer` (`id`, `name`, `path`, `isLabeler`, `sectorFk`, `ipAd
(2, 'printer2', 'path2', 1, 1 , NULL),
(4, 'printer4', 'path4', 0, NULL, '10.1.10.4');
UPDATE `vn`.`sector` SET mainPrinterFk = 1 WHERE id = 1;
UPDATE `vn`.`sector` SET `backupPrinterFk` = 1 WHERE id = 1;
INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`,`bossFk`, `phone`)
@ -2813,7 +2813,8 @@ INSERT INTO `util`.`notification` (`id`, `name`, `description`)
(4, 'supplier-pay-method-update', 'A supplier pay method has been updated'),
(5, 'modified-entry', 'An entry has been modified'),
(6, 'book-entry-deleted', 'accounting entries deleted'),
(7, 'zone-included','An email to notify zoneCollisions');
(7, 'zone-included','An email to notify zoneCollisions'),
(8, 'backup-printer-selected','A backup printer has been selected');
TRUNCATE `util`.`notificationAcl`;
INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`)
@ -2825,7 +2826,8 @@ INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`)
(4, 1),
(5, 9),
(6, 9),
(7, 9);
(7, 9),
(8, 66);
TRUNCATE `util`.`notificationQueue`;
INSERT INTO `util`.`notificationQueue` (`id`, `notificationFk`, `params`, `authorFk`, `status`, `created`)
@ -2845,15 +2847,16 @@ INSERT INTO `util`.`notificationSubscription` (`notificationFk`, `userFk`)
(1, 9),
(1, 3),
(6, 9),
(7, 9);
(7, 9),
(8, 66);
INSERT INTO `vn`.`routeConfig` (`id`, `defaultWorkCenterFk`)
VALUES
(1, 9);
INSERT INTO `vn`.`productionConfig` (`isPreviousPreparationRequired`, `ticketPrintedMax`, `ticketTrolleyMax`, `rookieDays`, `notBuyingMonths`, `id`, `isZoneClosedByExpeditionActivated`, `maxNotReadyCollections`, `minTicketsToCloseZone`, `movingTicketDelRoute`, `defaultZone`, `defautlAgencyMode`, `hasUniqueCollectionTime`, `maxCollectionWithoutUser`, `pendingCollectionsOrder`, `pendingCollectionsAge`)
INSERT INTO `vn`.`productionConfig` (`isPreviousPreparationRequired`, `ticketPrintedMax`, `ticketTrolleyMax`, `rookieDays`, `notBuyingMonths`, `id`, `isZoneClosedByExpeditionActivated`, `maxNotReadyCollections`, `minTicketsToCloseZone`, `movingTicketDelRoute`, `defaultZone`, `defautlAgencyMode`, `hasUniqueCollectionTime`, `maxCollectionWithoutUser`, `pendingCollectionsOrder`, `pendingCollectionsAge`, `backupPrinterNotificationDelay`)
VALUES
(0, 8, 80, 0, 0, 1, 0, 15, 25, -1, 697, 1328, 0, 1, 8, 6);
(0, 8, 80, 0, 0, 1, 0, 15, 25, -1, 697, 1328, 0, 1, 8, 6, 3600);
INSERT INTO `vn`.`collection` (`id`, `created`, `workerFk`, `stateFk`, `itemPackingTypeFk`, `saleTotalCount`, `salePickedCount`, `trainFk`, `sectorFk`, `wagons`)
VALUES

View File

@ -0,0 +1,11 @@
ALTER TABLE `vn`.`packingSite` DROP FOREIGN KEY IF EXISTS `packingSite_FK_4`;
ALTER TABLE `vn`.`arcRead` DROP FOREIGN KEY IF EXISTS `worker_printer_FK`;
ALTER TABLE `vn`.`host` DROP FOREIGN KEY IF EXISTS `configHost_FK`;
ALTER TABLE `vn`.`operator` DROP FOREIGN KEY IF EXISTS `operator_FK_5`;
ALTER TABLE `vn`.`packingSite` DROP FOREIGN KEY IF EXISTS `packingSite_FK_1`;
ALTER TABLE `vn`.`printQueue` DROP FOREIGN KEY IF EXISTS `printQueue_printerFk`;
ALTER TABLE `vn`.`sector` DROP FOREIGN KEY IF EXISTS `sector_FK_1`;
ALTER TABLE `vn`.`worker` DROP FOREIGN KEY IF EXISTS `worker_FK`;
ALTER TABLE dipole.printer DROP FOREIGN KEY IF EXISTS printer_FK;
ALTER TABLE dipole.expedition_PrintOut DROP FOREIGN KEY IF EXISTS expedition_PrintOut_FK;

View File

@ -0,0 +1,28 @@
ALTER TABLE `vn`.`printer` MODIFY COLUMN IF EXISTS `id` int unsigned auto_increment NOT NULL;
ALTER TABLE `vn`.`arcRead` MODIFY COLUMN IF EXISTS `printerFk` int unsigned DEFAULT NULL NULL;
ALTER TABLE `vn`.`arcRead` ADD CONSTRAINT `arcRead_FK` FOREIGN KEY IF NOT EXISTS (printerFk) REFERENCES vn.printer(id) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `vn`.`host` MODIFY COLUMN IF EXISTS `printerFk` int unsigned DEFAULT NULL NULL;
ALTER TABLE `vn`.`host` ADD CONSTRAINT `host_FK` FOREIGN KEY IF NOT EXISTS (printerFk) REFERENCES vn.printer(id) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `vn`.`operator` MODIFY COLUMN IF EXISTS `labelerFk` int unsigned DEFAULT NULL NULL;
ALTER TABLE `vn`.`operator` ADD CONSTRAINT `operator_FK_4` FOREIGN KEY IF NOT EXISTS (labelerFk) REFERENCES vn.printer(id) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `vn`.`packingSite` MODIFY COLUMN IF EXISTS `printerFk` int unsigned DEFAULT NULL NULL;
ALTER TABLE `vn`.`packingSite` ADD CONSTRAINT `packingSite_FK_1` FOREIGN KEY IF NOT EXISTS (printerFk) REFERENCES vn.printer(id) ON DELETE RESTRICT ON UPDATE RESTRICT;
ALTER TABLE `vn`.`packingSite` MODIFY COLUMN IF EXISTS `printerRfidFk` int unsigned DEFAULT NULL NULL;
ALTER TABLE `vn`.`packingSite` ADD CONSTRAINT `packingSite_FK_4` FOREIGN KEY IF NOT EXISTS(printerRfidFk) REFERENCES vn.printer(id) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `vn`.`printQueue` MODIFY COLUMN IF EXISTS `printerFk` int unsigned DEFAULT NULL NULL;
ALTER TABLE `vn`.`printQueue` ADD CONSTRAINT `printQueue_FK` FOREIGN KEY IF NOT EXISTS (id) REFERENCES vn.printer(id) ON DELETE RESTRICT ON UPDATE CASCADE;
ALTER TABLE `vn`.`sector` MODIFY COLUMN IF EXISTS `mainPrinterFk` int unsigned DEFAULT NULL NULL;
ALTER TABLE `vn`.`sector` ADD CONSTRAINT `sector_FK` FOREIGN KEY IF NOT EXISTS (mainPrinterFk) REFERENCES vn.printer(id) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `dipole`.`printer` MODIFY COLUMN IF EXISTS `id` int unsigned DEFAULT NULL NULL;
ALTER TABLE `dipole`.`printer` ADD CONSTRAINT `vnPrinter_FK` FOREIGN KEY IF NOT EXISTS (id) REFERENCES vn.printer(id) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `dipole`.`expedition_PrintOut` MODIFY COLUMN IF EXISTS `printerFk` int unsigned DEFAULT 0 NOT NULL;
ALTER TABLE `dipole`.`expedition_PrintOut` ADD CONSTRAINT `expedition_PrintOut_FK` FOREIGN KEY IF NOT EXISTS (printerFk) REFERENCES printer(id) ON DELETE CASCADE ON UPDATE CASCADE;

View File

@ -0,0 +1,17 @@
ALTER TABLE `vn`.`productionConfig` ADD IF NOT EXISTS backupPrinterNotificationDelay int unsigned NULL
COMMENT 'Minimum seconds Interval to Prevent Spam from Same-Type Notifications';
ALTER TABLE vn.sector DROP FOREIGN KEY IF EXISTS sector_FK;
ALTER TABLE `vn`.`sector` CHANGE IF EXISTS `mainPrinterFk` `backupPrinterFk` int unsigned DEFAULT NULL NULL;
ALTER TABLE `util`.`notificationSubscription` DROP FOREIGN KEY IF EXISTS `notificationSubscription_ibfk_1`;
ALTER TABLE `util`.`notificationQueue` DROP FOREIGN KEY IF EXISTS `nnotificationQueue_ibfk_1`;
ALTER TABLE `util`.`notificationAcl` DROP FOREIGN KEY IF EXISTS `notificationAcl_ibfk_1`;
ALTER TABLE `util`.`notification` MODIFY COLUMN IF EXISTS `id` int(11) auto_increment NOT NULL;
ALTER TABLE `util`.`notificationSubscription` ADD CONSTRAINT `notificationSubscription_Fk` FOREIGN KEY IF NOT EXISTS (`notificationFk`) REFERENCES `util`.`notification`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `util`.`notificationQueue` ADD CONSTRAINT `notificationQueue_Fk` FOREIGN KEY IF NOT EXISTS (`notificationFk`) REFERENCES `util`.`notification`(`name`) ON DELETE CASCADE ON UPDATE CASCADE;
ALTER TABLE `util`.`notificationAcl` ADD CONSTRAINT `notificationAcl_Fk` FOREIGN KEY IF NOT EXISTS (`notificationFk`) REFERENCES `util`.`notification`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

View File

@ -0,0 +1,12 @@
INSERT IGNORE INTO util.notification (name, description)
VALUES ('backup-printer-selected','A backup printer has been selected');
INSERT IGNORE INTO util.notificationSubscription (notificationFk, userFk)
SELECT id, 10435
FROM util.notification
WHERE name = 'backup-printer-selected';
INSERT IGNORE INTO util.notificationAcl (notificationFk, roleFk)
SELECT id, 66
FROM util.notification
WHERE name = 'backup-printer-selected';

View File

@ -48,7 +48,7 @@
"type": "number",
"required": false
},
"mainPrinterFk": {
"backupPrinterFk": {
"type": "number",
"required": false
},

View File

@ -3,60 +3,80 @@ const models = require('vn-loopback/server/server').models;
describe('Operator', () => {
const authorFk = 9;
const sectorId = 1;
const mainPrinter = 1;
const notificationName = 'not-main-printer-configured';
const operator = {
workerFk: 1,
trainFk: 1,
itemPackingTypeFk: 'H',
warehouseFk: 1,
sectorFk: sectorId
};
const labeler = 1;
const notificationName = 'backup-printer-selected';
const sentStatus = 'sent';
async function createOperator(labelerFk, options) {
operator.labelerFk = labelerFk;
await models.Operator.create(operator, options);
return models.NotificationQueue.findOne({
where: {
notificationFk: notificationName
}
}, options);
beforeEach(async() => {
await deleteNotification();
});
afterAll(async() => {
await deleteNotification();
});
async function deleteNotification() {
await models.NotificationQueue.destroyAll({notificationFk: notificationName});
}
it('should create notification when configured a not main printer in the sector', async() => {
const tx = await models.Operator.beginTransaction({});
async function updateOperatorAndFindNotification(labelerFk = labeler) {
await models.Operator.updateAll({id: authorFk}, {workerFk: authorFk, labelerFk: labelerFk, sectorFk: sectorId});
return models.NotificationQueue.findOne({order: 'id DESC'});
}
it('should create notification when configured a backup printer in the sector', async() => {
const notificationQueue = await updateOperatorAndFindNotification();
const params = JSON.parse(notificationQueue.params);
expect(notificationQueue.notificationFk).toEqual(notificationName);
expect(notificationQueue.authorFk).toEqual(authorFk);
expect(params.labelerId).toEqual(1);
expect(params.sectorId).toEqual(1);
expect(params.workerId).toEqual(9);
});
it('should not create notification when configured a non backup printer in the sector', async() => {
const notificationQueue = await updateOperatorAndFindNotification(2);
expect(notificationQueue?.notificationFk).not.toEqual(notificationName);
});
it('should create notification when delay is null', async() => {
const config = await models.ProductionConfig.findOne();
const delay = config.backupPrinterNotificationDelay;
await config.updateAttributes({backupPrinterNotificationDelay: null});
const lastNotification = await updateOperatorAndFindNotification();
await config.updateAttributes({backupPrinterNotificationDelay: delay});
expect(lastNotification.notificationFk).toEqual(notificationName);
});
it('should not sent notification when is already notified by another worker', async() => {
try {
const options = {transaction: tx, accessToken: {userId: authorFk}};
const notificationQueue = await createOperator(2, options);
const params = JSON.parse(notificationQueue.params);
expect(notificationQueue.notificationFk).toEqual(notificationName);
expect(notificationQueue.authorFk).toEqual(authorFk);
expect(params.labelerId).toEqual(2);
expect(params.sectorId).toEqual(1);
expect(params.workerId).toEqual(9);
await tx.rollback();
await models.NotificationQueue.create({
authorFk: 2,
notificationFk: notificationName,
params: JSON.stringify({'labelerId': labeler, 'sectorId': sectorId, 'workerId': 2}),
created: '2001-01-01 12:30:00',
status: sentStatus
});
await models.Operator.updateAll({id: 1}, {labelerFk: labeler, sectorFk: sectorId});
} catch (e) {
await tx.rollback();
throw e;
expect(e.message).toEqual('Previous notification sended with the same parameters');
}
});
it('should not create notification when configured the main printer in the sector', async() => {
const tx = await models.Operator.beginTransaction({});
it('should send a notification when the previous one has distinct params', async() => {
await models.NotificationQueue.create({
authorFk: 2,
notificationFk: notificationName,
params: JSON.stringify({'labelerId': labeler, 'sectorId': 2, 'workerId': 1}),
created: '2001-01-01 12:30:00',
status: sentStatus
});
const lastNotification = await updateOperatorAndFindNotification();
try {
const options = {transaction: tx, accessToken: {userId: authorFk}};
const notificationQueue = await createOperator(mainPrinter, options);
expect(notificationQueue).toEqual(null);
await tx.rollback();
} catch (e) {
await tx.rollback();
throw e;
}
expect(lastNotification.notificationFk).toEqual(notificationName);
});
});

View File

@ -1,19 +1,41 @@
module.exports = Self => {
Self.observe('after save', async function(ctx) {
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: ['mainPrinterFk']
fields: ['backupPrinterFk']
}, options);
if (sector.mainPrinterFk && sector.mainPrinterFk != instance.labelerFk) {
const userId = ctx.options.accessToken.userId;
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: Date.vnNow() - (backupPrinterNotificationDelay * 1000) + (3600 * 1000)},
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: 'not-main-printer-configured',
notificationFk: notificationName,
authorFk: userId,
params: JSON.stringify(
{
@ -22,7 +44,8 @@ module.exports = Self => {
'workerId': userId
}
)
}, options);
});
}
});
};

View File

@ -0,0 +1,14 @@
<email-body v-bind="$props">
<div class="grid-row">
<div class="grid-block vn-pa-ml">
<h1>{{ $t('title') }}</h1>
<p v-html="$t('description',
[
worker.nickname,
labeler.id,
sector.description,
]
)"/>
</div>
</div>
</email-body>

View File

@ -2,15 +2,14 @@ const Component = require(`vn-print/core/component`);
const emailBody = new Component('email-body');
module.exports = {
name: 'not-main-printer-configured',
name: 'backup-printer-selected',
async serverPrefetch() {
this.sector = await this.findOneFromDef('sector', [this.sectorId]);
if (!this.sector)
throw new Error('Something went wrong');
this.labeler = await this.findOneFromDef('printer', [this.labelerId]);
this.mainPrinter = await this.findOneFromDef('printer', [this.sector.mainPrinterFk]);
this.mainPrinter = await this.findOneFromDef('printer', [this.sector.backupPrinterFk]);
this.worker = await this.findOneFromDef('worker', [this.workerId]);
},
components: {
@ -29,5 +28,6 @@ module.exports = {
type: Number,
required: true
}
}
};

View File

@ -0,0 +1,3 @@
subject: Not main printer configured
title: Not main printer configured
description: 'The worker {0} is using the backup printer {1} for their sector {2}.'

View File

@ -0,0 +1,3 @@
subject: Seleccionada impresora de repuesto
title: Seleccionada impresora de repuesto
description: 'El trabajador {0} esta utilizando la impresora de repuesto {1} del sector {2}.'

View File

@ -1,3 +1,4 @@
SELECT id, name
SELECT id,
name
FROM vn.printer
WHERE id = ?

View File

@ -0,0 +1,5 @@
SELECT id,
description,
backupPrinterFk
FROM vn.sector
WHERE id = ?

View File

@ -1,3 +0,0 @@
subject: Not main printer configured
title: Not main printer configured
description: 'Printer #{0} {1} has been configured in sector #{2} {3} (the main printer for that sector is #{4} {5}). Ask the worker {6}.'

View File

@ -1,3 +0,0 @@
subject: Configurada impresora no principal
title: Configurada impresora no principal
description: 'Se ha configurado la impresora #{0} {1} en el sector #{2} {3} (la impresora principal de ese sector es la #{4} {5}). Preguntar al trabajador {6}.'

View File

@ -1,8 +0,0 @@
<email-body v-bind="$props">
<div class="grid-row">
<div class="grid-block vn-pa-ml">
<h1>{{ $t('title') }}</h1>
<p v-html="$t('description', [labeler.id, labeler.name, sector.id, sector.description, mainPrinter.id, mainPrinter.name, worker.nickname])"></p>
</div>
</div>
</email-body>

View File

@ -1,3 +0,0 @@
SELECT id, description, mainPrinterFk
FROM vn.sector
WHERE id = ?