From be5526dee46307fa833f0850112ad77a28d117b4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 12 Sep 2024 14:49:24 +0200 Subject: [PATCH 1/3] refactor: refs #4452 Remove unnecessary files, update DB settings/schema, refactor RFID/event handling, add ZPL generation. --- .gitignore | 8 +-- README.md | 1 + backend/db/init.sql | 113 ------------------------------- backend/db/pool.js | 10 +-- backend/resources/zplTemplate.js | 6 +- backend/worker/worker.js | 74 +++++++++----------- backend/worker/workerPool.js | 18 ++--- docker-compose.yml | 1 - 8 files changed, 51 insertions(+), 180 deletions(-) delete mode 100644 backend/db/init.sql diff --git a/.gitignore b/.gitignore index 12e189f..4e6f25a 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ node_modules/ npm-debug.log yarn-error.log -.env # Logs logs/ @@ -27,9 +26,7 @@ build/Release/ .yarn-integrity # dotenv environment variables file -.env -.env.test -.env.production +.env* # Next.js build output .next/ @@ -66,5 +63,4 @@ $RECYCLE.BIN/ *.swp *~ -# Docker files -docker-compose.override.yml +zplData_*.txt \ No newline at end of file diff --git a/README.md b/README.md index 2e33bc0..9e8ff50 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ Este proyecto es una aplicación backend que utiliza Node.js, Docker, MariaDB y ```env DB_HOST=mariadb + DB_PORT=3306 DB_USER=user DB_PASSWORD=password DB_NAME=database diff --git a/backend/db/init.sql b/backend/db/init.sql deleted file mode 100644 index 001275c..0000000 --- a/backend/db/init.sql +++ /dev/null @@ -1,113 +0,0 @@ -CREATE TABLE IF NOT EXISTS `printer` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `name` varchar(50) DEFAULT NULL, - `path` varchar(50) DEFAULT NULL, - `modelFk` varchar(50) DEFAULT NULL, - `macWifi` varchar(20) DEFAULT NULL, - `ipAddress` varchar(15) DEFAULT NULL, - `reference` varchar(50) DEFAULT NULL, - `isLabeler` tinyint(1) DEFAULT 0 COMMENT 'Indica si es impresora de etiquetas', - `sectorFk` int(11) DEFAULT NULL, - `paperSizeFk` varchar(100) DEFAULT NULL, - `isRfid` tinyint(4) NOT NULL DEFAULT 0, - PRIMARY KEY (`id`), - UNIQUE KEY `printer_UN` (`reference`), - UNIQUE KEY `printer_UN1` (`macWifi`), - UNIQUE KEY `printer_UN2` (`name`), - KEY `printer_FK` (`modelFk`), - KEY `printer_sectorFk_idx` (`id`,`sectorFk`), - KEY `printer_sectorFk` (`sectorFk`), - KEY `printer_FK_1` (`paperSizeFk`) -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; - -INSERT INTO `printer` (id, name, ipAddress) VALUES (1, 'printer1', '192.168.233.14'); -INSERT INTO `printer` (id, name, ipAddress) VALUES (2, 'printer2', '192.168.233.14'); -INSERT INTO `printer` (id, name, ipAddress) VALUES (3, 'printer4', '192.168.233.14'); - -CREATE TABLE IF NOT EXISTS `expedition_PrintOut` ( - `expeditionFk` int(11) NOT NULL, - `ticketFk` int(11) NOT NULL, - `addressFk` int(11) NOT NULL, - `street` varchar(42) NOT NULL DEFAULT ' ', - `postalCode` varchar(10) NOT NULL DEFAULT ' ', - `city` varchar(100) NOT NULL DEFAULT ' ', - `shopName` varchar(100) NOT NULL DEFAULT ' ', - `isPrinted` int(11) NOT NULL DEFAULT 0, - `created` timestamp NOT NULL DEFAULT current_timestamp(), - `printerFk` int(10) unsigned NOT NULL DEFAULT 0, - `routeFk` int(11) NOT NULL DEFAULT 0, - `parkingCode` varchar(8) NOT NULL DEFAULT ' ', - `truckName` varchar(25) NOT NULL DEFAULT ' ', - `clientFk` int(11) NOT NULL, - `phone` varchar(15) DEFAULT NULL, - `province` varchar(20) NOT NULL, - `agency` varchar(100) DEFAULT NULL, - `m3` decimal(10,3) DEFAULT 0.000, - `workerCode` varchar(25) DEFAULT NULL, - `itemFk` int(11) DEFAULT NULL, - `quantity` int(11) DEFAULT NULL, - `longName` varchar(30) DEFAULT NULL, - `shelvingFk` varchar(5) DEFAULT NULL, - `comments` varchar(100) DEFAULT NULL, - PRIMARY KEY (`expeditionFk`), - KEY `expedition_PrintOut_FK` (`printerFk`), - CONSTRAINT `expedition_PrintOut_FK` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='listado de etiquetas a imprimir'; - -INSERT INTO `expedition_PrintOut` ( - `expeditionFk`, `ticketFk`, `addressFk`, `street`, `postalCode`, `city`, - `shopName`, `isPrinted`, `created`, `printerFk`, `routeFk`, `parkingCode`, - `truckName`, `clientFk`, `phone`, `province`, `agency`, `m3`, - `workerCode`, `itemFk`, `quantity`, `longName`, `shelvingFk`, `comments` -) -VALUES - (1, 1, 1, '1007 Mountain Drive', '46460', 'Gotham', 'Wayne Manor', 0, NOW(), 1, 1, 'A1', 'Truck 1', 1101, '1111111111', 'Gotham', 'Agency 1', 10.000, 'W1', 1001, 10, 'Item 1', 'S1', 'No comments'), - (2, 2, 2, '20 Ingram Street', '46460', 'Gotham', 'Parker Residence', 0, NOW(), 2, 2, 'A2', 'Truck 2', 1102, '2222222222', 'Gotham', 'Agency 2', 20.000, 'W2', 1002, 20, 'Item 2', 'S2', 'No comments'), - (3, 3, 3, '344 Clinton Street', '46460', 'Gotham', 'Kent Apartment', 0, NOW(), 1, 3, 'A3', 'Truck 3', 1103, '3333333333', 'Gotham', 'Agency 3', 30.000, 'W3', 1003, 30, 'Item 3', 'S3', 'No comments'), - (4, 4, 4, '10880 Malibu Point', '46460', 'Gotham', 'Stark Tower', 0, NOW(), 2, 4, 'A4', 'Truck 4', 1104, '4444444444', 'Gotham', 'Agency 4', 40.000, 'W4', 1004, 40, 'Item 4', 'S4', 'No comments'), - (5, 5, 5, 'Unknown Whereabouts', '46460', 'Gotham', 'Magneto Lair', 0, NOW(), 1, 5, 'A5', 'Truck 5', 1105, '5555555555', 'Gotham', 'Agency 5', 50.000, 'W5', 1005, 50, 'Item 5', 'S5', 'No comments'), - (6, 6, 6, 'Evil Hideout', '46460', 'Gotham', 'Legion Base', 0, NOW(), 1, 6, 'A6', 'Truck 6', 1106, '6666666666', 'Gotham', 'Agency 6', 60.000, 'W6', 1006, 60, 'Item 6', 'S6', 'No comments'), - (7, 7, 7, 'Anthill', '46460', 'Gotham', 'Pym Laboratory', 0, NOW(), 2, 7, 'A7', 'Truck 7', 1107, '7777777777', 'Gotham', 'Agency 7', 70.000, 'W7', 1007, 70, 'Item 7', 'S7', 'No comments'), - (8, 8, 8, '3800 Victory Pkwy', '46460', 'Gotham', 'Xavier Institute', 0, NOW(), 1, 8, 'A8', 'Truck 8', 1108, '8888888888', 'Gotham', 'Agency 8', 80.000, 'W8', 1008, 80, 'Item 8', 'S8', 'No comments'), - (9, 9, 9, 'Somewhere in New York', '46460', 'Gotham', 'Banner Lab', 0, NOW(), 1, 9, 'A9', 'Truck 9', 1109, '9999999999', 'Gotham', 'Agency 9', 90.000, 'W9', 1009, 90, 'Item 9', 'S9', 'No comments'), - (10, 10, 10, 'Streets of New York', '46460', 'Gotham', 'Daily Bugle', 0, NOW(), 2, 10, 'A10', 'Truck 10', 1110, '0000000000', 'Gotham', 'Agency 10', 100.000, 'W10', 1010, 100, 'Item 10', 'S10', 'No comments'), - (11, 1, 1, '1007 Mountain Drive', '46460', 'Gotham', 'Wayne Manor', 0, NOW(), 1, 1, 'A1', 'Truck 1', 1101, '1111111111', 'Gotham', 'Agency 1', 10.000, 'W1', 1001, 10, 'Item 1', 'S1', 'No comments'), - (12, 2, 2, '20 Ingram Street', '46460', 'Gotham', 'Parker Residence', 0, NOW(), 2, 2, 'A2', 'Truck 2', 1102, '2222222222', 'Gotham', 'Agency 2', 20.000, 'W2', 1002, 20, 'Item 2', 'S2', 'No comments'), - (13, 3, 3, '344 Clinton Street', '46460', 'Gotham', 'Kent Apartment', 0, NOW(), 1, 3, 'A3', 'Truck 3', 1103, '3333333333', 'Gotham', 'Agency 3', 30.000, 'W3', 1003, 30, 'Item 3', 'S3', 'No comments'), - (14, 4, 4, '10880 Malibu Point', '46460', 'Gotham', 'Stark Tower', 0, NOW(), 2, 4, 'A4', 'Truck 4', 1104, '4444444444', 'Gotham', 'Agency 4', 40.000, 'W4', 1004, 40, 'Item 4', 'S4', 'No comments'), - (15, 5, 5, 'Unknown Whereabouts', '46460', 'Gotham', 'Magneto Lair', 0, NOW(), 1, 5, 'A5', 'Truck 5', 1105, '5555555555', 'Gotham', 'Agency 5', 50.000, 'W5', 1005, 50, 'Item 5', 'S5', 'No comments'), - (16, 6, 6, 'Evil Hideout', '46460', 'Gotham', 'Legion Base', 0, NOW(), 1, 6, 'A6', 'Truck 6', 1106, '6666666666', 'Gotham', 'Agency 6', 60.000, 'W6', 1006, 60, 'Item 6', 'S6', 'No comments'), - (17, 7, 7, 'Anthill', '46460', 'Gotham', 'Pym Laboratory', 0, NOW(), 2, 7, 'A7', 'Truck 7', 1107, '7777777777', 'Gotham', 'Agency 7', 70.000, 'W7', 1007, 70, 'Item 7', 'S7', 'No comments'), - (18, 8, 8, '3800 Victory Pkwy', '46460', 'Gotham', 'Xavier Institute', 0, NOW(), 1, 8, 'A8', 'Truck 8', 1108, '8888888888', 'Gotham', 'Agency 8', 80.000, 'W8', 1008, 80, 'Item 8', 'S8', 'No comments'), - (19, 9, 9, 'Somewhere in New York', '46460', 'Gotham', 'Banner Lab', 0, NOW(), 1, 9, 'A9', 'Truck 9', 1109, '9999999999', 'Gotham', 'Agency 9', 90.000, 'W9', 1009, 90, 'Item 9', 'S9', 'No comments'), - (20, 10, 10, 'Streets of New York', '46460', 'Gotham', 'Daily Bugle', 0, NOW(), 2, 10, 'A10', 'Truck 10', 1110, '0000000000', 'Gotham', 'Agency 10', 100.000, 'W10', 1010, 100, 'Item 10', 'S10', 'No comments'), - (21, 1, 1, '1007 Mountain Drive', '46460', 'Gotham', 'Wayne Manor', 0, NOW(), 1, 1, 'A1', 'Truck 1', 1101, '1111111111', 'Gotham', 'Agency 1', 10.000, 'W1', 1001, 10, 'Item 1', 'S1', 'No comments'), - (22, 2, 2, '20 Ingram Street', '46460', 'Gotham', 'Parker Residence', 0, NOW(), 2, 2, 'A2', 'Truck 2', 1102, '2222222222', 'Gotham', 'Agency 2', 20.000, 'W2', 1002, 20, 'Item 2', 'S2', 'No comments'), - (23, 3, 3, '344 Clinton Street', '46460', 'Gotham', 'Kent Apartment', 0, NOW(), 1, 3, 'A3', 'Truck 3', 1103, '3333333333', 'Gotham', 'Agency 3', 30.000, 'W3', 1003, 30, 'Item 3', 'S3', 'No comments'), - (24, 4, 4, '10880 Malibu Point', '46460', 'Gotham', 'Stark Tower', 0, NOW(), 2, 4, 'A4', 'Truck 4', 1104, '4444444444', 'Gotham', 'Agency 4', 40.000, 'W4', 1004, 40, 'Item 4', 'S4', 'No comments'), - (25, 5, 5, 'Unknown Whereabouts', '46460', 'Gotham', 'Magneto Lair', 0, NOW(), 1, 5, 'A5', 'Truck 5', 1105, '5555555555', 'Gotham', 'Agency 5', 50.000, 'W5', 1005, 50, 'Item 5', 'S5', 'No comments'), - (26, 6, 6, 'Evil Hideout', '46460', 'Gotham', 'Legion Base', 0, NOW(), 1, 6, 'A6', 'Truck 6', 1106, '6666666666', 'Gotham', 'Agency 6', 60.000, 'W6', 1006, 60, 'Item 6', 'S6', 'No comments'), - (27, 7, 7, 'Anthill', '46460', 'Gotham', 'Pym Laboratory', 0, NOW(), 2, 7, 'A7', 'Truck 7', 1107, '7777777777', 'Gotham', 'Agency 7', 70.000, 'W7', 1007, 70, 'Item 7', 'S7', 'No comments'), - (28, 8, 8, '3800 Victory Pkwy', '46460', 'Gotham', 'Xavier Institute', 0, NOW(), 1, 8, 'A8', 'Truck 8', 1108, '8888888888', 'Gotham', 'Agency 8', 80.000, 'W8', 1008, 80, 'Item 8', 'S8', 'No comments'), - (29, 9, 9, 'Somewhere in New York', '46460', 'Gotham', 'Banner Lab', 0, NOW(), 1, 9, 'A9', 'Truck 9', 1109, '9999999999', 'Gotham', 'Agency 9', 90.000, 'W9', 1009, 90, 'Item 9', 'S9', 'No comments'), - (30, 10, 10, 'Streets of New York', '46460', 'Gotham', 'Daily Bugle', 0, NOW(), 2, 10, 'A10', 'Truck 10', 1110, '0000000000', 'Gotham', 'Agency 10', 100.000, 'W10', 1010, 100, 'Item 10', 'S10', 'No comments'), - (31, 1, 1, '1007 Mountain Drive', '46460', 'Gotham', 'Wayne Manor', 0, NOW(), 1, 1, 'A1', 'Truck 1', 1101, '1111111111', 'Gotham', 'Agency 1', 10.000, 'W1', 1001, 10, 'Item 1', 'S1', 'No comments'), - (32, 2, 2, '20 Ingram Street', '46460', 'Gotham', 'Parker Residence', 0, NOW(), 2, 2, 'A2', 'Truck 2', 1102, '2222222222', 'Gotham', 'Agency 2', 20.000, 'W2', 1002, 20, 'Item 2', 'S2', 'No comments'), - (33, 3, 3, '344 Clinton Street', '46460', 'Gotham', 'Kent Apartment', 0, NOW(), 1, 3, 'A3', 'Truck 3', 1103, '3333333333', 'Gotham', 'Agency 3', 30.000, 'W3', 1003, 30, 'Item 3', 'S3', 'No comments'), - (34, 4, 4, '10880 Malibu Point', '46460', 'Gotham', 'Stark Tower', 0, NOW(), 2, 4, 'A4', 'Truck 4', 1104, '4444444444', 'Gotham', 'Agency 4', 40.000, 'W4', 1004, 40, 'Item 4', 'S4', 'No comments'), - (35, 5, 5, 'Unknown Whereabouts', '46460', 'Gotham', 'Magneto Lair', 0, NOW(), 1, 5, 'A5', 'Truck 5', 1105, '5555555555', 'Gotham', 'Agency 5', 50.000, 'W5', 1005, 50, 'Item 5', 'S5', 'No comments'), - (36, 6, 6, 'Evil Hideout', '46460', 'Gotham', 'Legion Base', 0, NOW(), 1, 6, 'A6', 'Truck 6', 1106, '6666666666', 'Gotham', 'Agency 6', 60.000, 'W6', 1006, 60, 'Item 6', 'S6', 'No comments'), - (37, 7, 7, 'Anthill', '46460', 'Gotham', 'Pym Laboratory', 0, NOW(), 2, 7, 'A7', 'Truck 7', 1107, '7777777777', 'Gotham', 'Agency 7', 70.000, 'W7', 1007, 70, 'Item 7', 'S7', 'No comments'), - (38, 8, 8, '3800 Victory Pkwy', '46460', 'Gotham', 'Xavier Institute', 0, NOW(), 1, 8, 'A8', 'Truck 8', 1108, '8888888888', 'Gotham', 'Agency 8', 80.000, 'W8', 1008, 80, 'Item 8', 'S8', 'No comments'), - (39, 9, 9, 'Somewhere in New York', '46460', 'Gotham', 'Banner Lab', 0, NOW(), 1, 9, 'A9', 'Truck 9', 1109, '9999999999', 'Gotham', 'Agency 9', 90.000, 'W9', 1009, 90, 'Item 9', 'S9', 'No comments'), - (40, 10, 10, 'Streets of New York', '46460', 'Gotham', 'Daily Bugle', 0, NOW(), 2, 10, 'A10', 'Truck 10', 1110, '0000000000', 'Gotham', 'Agency 10', 100.000, 'W10', 1010, 100, 'Item 10', 'S10', 'No comments'), - (41, 1, 1, '1007 Mountain Drive', '46460', 'Gotham', 'Wayne Manor', 0, NOW(), 1, 1, 'A1', 'Truck 1', 1101, '1111111111', 'Gotham', 'Agency 1', 10.000, 'W1', 1001, 10, 'Item 1', 'S1', 'No comments'), - (42, 2, 2, '20 Ingram Street', '46460', 'Gotham', 'Parker Residence', 0, NOW(), 2, 2, 'A2', 'Truck 2', 1102, '2222222222', 'Gotham', 'Agency 2', 20.000, 'W2', 1002, 20, 'Item 2', 'S2', 'No comments'), - (43, 3, 3, '344 Clinton Street', '46460', 'Gotham', 'Kent Apartment', 0, NOW(), 1, 3, 'A3', 'Truck 3', 1103, '3333333333', 'Gotham', 'Agency 3', 30.000, 'W3', 1003, 30, 'Item 3', 'S3', 'No comments'), - (44, 4, 4, '10880 Malibu Point', '46460', 'Gotham', 'Stark Tower', 0, NOW(), 2, 4, 'A4', 'Truck 4', 1104, '4444444444', 'Gotham', 'Agency 4', 40.000, 'W4', 1004, 40, 'Item 4', 'S4', 'No comments'), - (45, 5, 5, 'Unknown Whereabouts', '46460', 'Gotham', 'Magneto Lair', 0, NOW(), 1, 5, 'A5', 'Truck 5', 1105, '5555555555', 'Gotham', 'Agency 5', 50.000, 'W5', 1005, 50, 'Item 5', 'S5', 'No comments'), - (46, 6, 6, 'Evil Hideout', '46460', 'Gotham', 'Legion Base', 0, NOW(), 1, 6, 'A6', 'Truck 6', 1106, '6666666666', 'Gotham', 'Agency 6', 60.000, 'W6', 1006, 60, 'Item 6', 'S6', 'No comments'), - (47, 7, 7, 'Anthill', '46460', 'Gotham', 'Pym Laboratory', 0, NOW(), 2, 7, 'A7', 'Truck 7', 1107, '7777777777', 'Gotham', 'Agency 7', 70.000, 'W7', 1007, 70, 'Item 7', 'S7', 'No comments'), - (48, 8, 8, '3800 Victory Pkwy', '46460', 'Gotham', 'Xavier Institute', 0, NOW(), 1, 8, 'A8', 'Truck 8', 1108, '8888888888', 'Gotham', 'Agency 8', 80.000, 'W8', 1008, 80, 'Item 8', 'S8', 'No comments'), - (49, 9, 9, 'Somewhere in New York', '46460', 'Gotham', 'Banner Lab', 0, NOW(), 1, 9, 'A9', 'Truck 9', 1109, '9999999999', 'Gotham', 'Agency 9', 90.000, 'W9', 1009, 90, 'Item 9', 'S9', 'No comments'), - (50, 10, 10, 'Streets of New York', '46460', 'Gotham', 'Daily Bugle', 0, NOW(), 2, 10, 'A10', 'Truck 10', 1110, '0000000000', 'Gotham', 'Agency 10', 100.000, 'W10', 1010, 100, 'Item 10', 'S10', 'No comments'), diff --git a/backend/db/pool.js b/backend/db/pool.js index 7a22d6c..b7ac7f9 100644 --- a/backend/db/pool.js +++ b/backend/db/pool.js @@ -3,13 +3,15 @@ const dotenv = require('dotenv'); // Cargar variables de entorno desde un archivo .env dotenv.config(); +const env = process.env; // Crear un pool de conexiones const pool = mysql.createPool({ - host: process.env.DB_HOST || 'mariadb', - user: process.env.DB_USER || 'user', - password: process.env.DB_PASSWORD || 'password', - database: process.env.DB_NAME || 'database', + host: env.DB_HOST || 'mariadb', + port: env.DB_PORT || 3306, + user: env.DB_USER || 'user', + password: env.DB_PASSWORD || 'password', + database: env.DB_NAME || 'database', waitForConnections: true, queueLimit: 0 }); diff --git a/backend/resources/zplTemplate.js b/backend/resources/zplTemplate.js index 6f27237..f60c629 100644 --- a/backend/resources/zplTemplate.js +++ b/backend/resources/zplTemplate.js @@ -26,12 +26,10 @@ module.exports = function generateZPL(record, label) { const recordKey = labelConfig.mappings[mappingKey]; const recordValue = upperCaseRecord[recordKey]; const placeholder = `#${mappingKey}`; - if(placeholder=='#RFID_Code'){ + if(placeholder == '#RFID_Code') zpl = zpl.replace(new RegExp(placeholder, 'g'), rf_id_venature + id_venature); - }else { + else zpl = zpl.replace(new RegExp(placeholder, 'g'), recordValue); - } - } } diff --git a/backend/worker/worker.js b/backend/worker/worker.js index 43e3305..1bbae4d 100644 --- a/backend/worker/worker.js +++ b/backend/worker/worker.js @@ -4,21 +4,21 @@ const path = require('path'); const pool = require('../db/pool'); const log4js = require('log4js'); const net = require('net'); -const generateZPL = require('../resources/zplTemplate'); // Importamos la función desde el archivo zplTemplate -const label = require('../resources/label.json'); // Importamos la función desde el archivo zplTemplate +const generateZPL = require('../resources/zplTemplate'); +const label = require('../resources/label.json'); // Configuración de log4js log4js.configure({ appenders: { - file: { type: 'file', filename: 'logs/app.log', maxLogSize: 10485760, backups: 3, compress: true }, - console: { type: 'console' } + file: { type: 'file', filename: 'logs/app.log', maxLogSize: 10485760, backups: 3, compress: true }, + console: { type: 'console' } }, categories: { - default: { appenders: ['file', 'console'], level: 'info' } + default: { appenders: ['file', 'console'], level: 'info' } } - }); +}); - const logger = log4js.getLogger('default'); +const logger = log4js.getLogger('default'); // Función para obtener una conexión con reintentos async function getConnectionWithRetries(retries = 5, delay = 5000) { @@ -47,14 +47,9 @@ async function sendZPL(zplContent, ipAddress, retries = 2, delay = 3000) { const client = new net.Socket(); client.connect(port, ipAddress, () => { - logger.info(`Conexión establecida con la impresora en el intento ${attempt + 1}`); - client.write(zplContent); - }); - - client.on('data', data => { - logger.info(`Respuesta de la impresora: ${data.toString()}`); - client.destroy(); // Destruye el cliente al recibir respuesta del servidor - resolve('success'); + client.write(zplContent, () => { + resolve('success'); + }); }); client.on('error', error => { @@ -69,17 +64,15 @@ async function sendZPL(zplContent, ipAddress, retries = 2, delay = 3000) { }); }); - if (result === 'success') { + if (result === 'success') return 'success'; - } else if (result === 'closed') { + else if (result === 'closed') continue; // Reintentar si la conexión se cerró sin error - } } catch (error) { logger.error(`Error al enviar ZPL a la impresora (intento ${attempt + 1}):`, error.message); - if (attempt >= retries - 1) { + if (attempt >= retries - 1) return 'error'; - } await new Promise(resolve => setTimeout(resolve, delay)); } @@ -87,15 +80,15 @@ async function sendZPL(zplContent, ipAddress, retries = 2, delay = 3000) { return 'error'; } - // Función para obtener la dirección IP de la impresora, realizando una llamada a la base de datos a la tabla de printer async function getPrinterIpAddress(printerFk) { const connection = await getConnectionWithRetries(); try { - const [rows] = await connection.query('SELECT ipAddress FROM printer WHERE id = ?', [printerFk]); - if (rows.length === 0) { + const [rows] = await connection.query(` + SELECT ipAddress FROM vn.printer WHERE id = ? + `, [printerFk]); + if (!rows.length) throw new Error(`No se encontró la impresora con id=${printerFk}`); - } return rows[0].ipAddress; } catch (error) { logger.error('Error al obtener la dirección IP de la impresora:', error); @@ -111,10 +104,12 @@ async function getRecordForProcessing(retries = 5, delay = 5000) { const connection = await getConnectionWithRetries(); try { await connection.beginTransaction(); - const [rows] = await connection.query('SELECT * FROM expedition_PrintOut WHERE isPrinted = 0 LIMIT 1 FOR UPDATE'); - if (rows.length === 0) { + const [rows] = await connection.query(` + SELECT * FROM expedition_PrintOut WHERE isPrinted = 0 LIMIT 1 FOR UPDATE + `); + if (!rows.length) { await connection.commit(); - return null; + return; } const record = rows[0]; @@ -128,13 +123,12 @@ async function getRecordForProcessing(retries = 5, delay = 5000) { await connection.rollback(); if (error.code === 'ER_LOCK_WAIT_TIMEOUT') { logger.error('Lock wait timeout exceeded, retrying...'); - if (attempt >= retries - 1) { + if (attempt >= retries - 1) throw new Error('No se pudo obtener el registro después de múltiples intentos.'); - } await new Promise(resolve => setTimeout(resolve, delay)); } else { logger.error('Error al obtener y marcar el registro para procesamiento:', error); - return null; + return; } } finally { connection.release(); @@ -149,7 +143,7 @@ async function processRecord(record) { try { await connection.beginTransaction(); - logger.info(`Procesando expeditionFk=${record.expeditionFk} en worker`); + logger.info(`Procesando expedición = ${record.expeditionFk}`); const zplData = generateZPL(record, label); const filePath = path.join(__dirname, `zplData_${record.expeditionFk}.txt`); @@ -157,20 +151,20 @@ async function processRecord(record) { await fs.writeFile(filePath, zplData["VerdNatura Label RFID"].zpl, 'utf8'); const zplContent = await fs.readFile(filePath, 'utf8'); + // Obtener la dirección IP de la impresora const ipAddress = await getPrinterIpAddress(record.printerFk); const sendResult = await sendZPL(zplContent, ipAddress); + if (sendResult === 'success') { - logger.info(`Etiqueta impresa correctamente para expeditionFk=${record.expeditionFk}`); await connection.query( 'UPDATE expedition_PrintOut SET isPrinted = 1 WHERE expeditionFk = ?', [record.expeditionFk] ); logger.info(`Base de datos actualizada para expeditionFk=${record.expeditionFk}`); - } else { + } else logger.error(`Error al enviar ZPL a la impresora para expeditionFk=${record.expeditionFk}`); - } parentPort.postMessage('done'); await connection.commit(); @@ -183,20 +177,18 @@ async function processRecord(record) { } } - // Escuchar mensajes del hilo principal -parentPort.on('message', async (message) => { +parentPort.on('message', async message => { if (message === 'check') { const record = await getRecordForProcessing(); - if (record) { + if (record) await processRecord(record); - } else { + else { // Si no hay registros, espera y vuelve a verificar - setTimeout(async () => { + setTimeout(async() => { parentPort.postMessage('done'); }, 5000); } - } else { + } else processRecord(message).catch(err => logger.error('Error en el worker:', err)); - } }); diff --git a/backend/worker/workerPool.js b/backend/worker/workerPool.js index f100e9e..825256b 100644 --- a/backend/worker/workerPool.js +++ b/backend/worker/workerPool.js @@ -22,25 +22,23 @@ class WorkerPool { // Inicializar workers initWorkers() { - for (let i = 0; i < this.numWorkers; i++) { + for (let i = 0; i < this.numWorkers; i++) this.createWorker(); - } } // Crear un nuevo worker y manejar sus mensajes createWorker() { const worker = new Worker('./worker/worker.js'); - worker.on('message', async (message) => { - if (message === 'done' || message === 'error') { + worker.on('message', async message => { + if (message === 'done' || message === 'error') worker.postMessage('check'); // Pedir al worker que verifique nuevos registros - } }); - worker.on('error', (error) => { + worker.on('error', error => { logger.error('Error en el worker:', error); // Si un worker falla, lo eliminamos del array y creamos uno nuevo this.replaceWorker(worker); }); - worker.on('exit', (code) => { + worker.on('exit', code => { if (code !== 0) { logger.error(`Worker stopped with exit code ${code}`); this.replaceWorker(worker); @@ -57,16 +55,14 @@ class WorkerPool { // Asignar tareas iniciales a los workers async assignTasks() { - for (const worker of this.workers) { + for (const worker of this.workers) worker.postMessage('check'); // Pedir al worker que verifique nuevos registros - } } // Cerrar todos los workers closeAllWorkers() { - for (const worker of this.workers) { + for (const worker of this.workers) worker.terminate(); - } } } diff --git a/docker-compose.yml b/docker-compose.yml index 55e956a..e5ab4c4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,7 +13,6 @@ services: - "3306:3306" volumes: - db_data:/var/lib/mysql - - ./backend/db/init.sql:/docker-entrypoint-initdb.d/init.sql backend: build: From 8d493fee9d863bbc313ae99414ddc2bdc9d71190 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 13 Sep 2024 11:30:03 +0200 Subject: [PATCH 2/3] refactor: refs #4452 Changes --- backend/worker/worker.js | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/backend/worker/worker.js b/backend/worker/worker.js index 6090e35..75715da 100644 --- a/backend/worker/worker.js +++ b/backend/worker/worker.js @@ -62,20 +62,19 @@ async function sendZPL(zplContent, ipAddress, retries = 2, delay = 3000) { client.on('close', () => { logger.info('Conexión cerrada'); // Si no se recibió ningún dato, considerarlo como cerrado exitosamente - if (!dataReceived) { + if (!dataReceived) resolve('success'); // Considerar éxito si la impresora cerró la conexión sin error - } else { + else resolve('closed'); - } }); }); if (result === 'success') return 'success'; - else if (result === 'closed') - if(retries>= attempt) - return 'error'; + else if (result === 'closed') { + if (retries >= attempt) return 'error'; continue; // Reintentar si la conexión se cerró sin error + } } catch (error) { logger.error(`Error al enviar ZPL a la impresora (intento ${attempt + 1}):`, error.message); From 77758cf31cd73b7ab0be880016e2837be4fd53f2 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 13 Sep 2024 12:28:01 +0200 Subject: [PATCH 3/3] refactor: refs #4452 Changes --- backend/resources/zplTemplate_tst.js | 108 --------------------------- backend/worker/worker.js | 9 +-- 2 files changed, 2 insertions(+), 115 deletions(-) delete mode 100644 backend/resources/zplTemplate_tst.js diff --git a/backend/resources/zplTemplate_tst.js b/backend/resources/zplTemplate_tst.js deleted file mode 100644 index 7120373..0000000 --- a/backend/resources/zplTemplate_tst.js +++ /dev/null @@ -1,108 +0,0 @@ -module.exports = function generateZPL(record) { - const rf_id_venature = "AABB"; - const id_venature = String(record.expeditionFk).padStart(20, '0'); // Convert to string before padStart - // Convert text values of the record to uppercase - const upperCaseRecord = {}; - for (let key in record) { - if (Object.prototype.hasOwnProperty.call(record, key)) { - if (typeof record[key] === 'string') - upperCaseRecord[key] = record[key].toUpperCase(); - else - upperCaseRecord[key] = record[key]; - } - } - - return { - "VerdNatura Label RFID": { - "name": "VerdNatura Label RFID", - "zpl": `^XA\r\n\r\n - ^POI\r\n\r\n - ^LRY\r\n\r\n - ^FO676,30\r\n - ^GB130,1160,100,B^FS\r\n\r\n - ^FO686,190\r\n - ^A@R,90,100,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.truckName}^FS\r\n\r\n - ^FO480,190\r\n - ^A@R,180,180,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.addressFk}^FS\r\n\r\n - ^FO390,350\r\n - ^A@R,100,120,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.routeFk}^FS\r\n\r\n - ^FO320,30\r\n - ^A@R,40,40,E:ARIALR.TTF 1036584\r\n - ^CI28^FD${upperCaseRecord.shopName}^FS\r\n\r\n - ^FO260,30\r\n - ^A@R,40,40,E:ARIALR.TTF 1036584\r\n - ^CI28^FD${upperCaseRecord.street}^FS\r\n\r\n - ^FO200,30\r\n - ^A@R,40,40,E:ARIALR.TTF 1036584\r\n - ^CI28^FD${upperCaseRecord.postalCode}^FS\r\n\r\n - ^FO200,210\r\n - ^A@R,40,40,E:ARIALR.TTF 1036584\r\n - ^CI28^FD${upperCaseRecord.city}^FS\r\n\r\n - ^FO140,30\r\n - ^A@R,40,40,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.clientFk}^FS\r\n\r\n - ^FO140,150\r\n - ^A@R,40,40,E:ARIALB.TTF 980756\r\n - ^CI28^FD / ^FS\r\n\r\n - ^FO140,210\r\n - ^A@R,40,40,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.ticketFk}^FS\r\n\r\n - ^FO140,490\r\n - ^A@R,40,40,E:ARIALR.TTF 1036584\r\n - ^CI28^FDTel: ${upperCaseRecord.phone}^FS\r\n\r\n - ^FO40,30\r\n - ^GB80,740,80,B^FS\r\n\r\n - ^FO40,250\r\n - ^A@R,70,70,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.province}^FS\r\n\r\n - ^FX CODIGO DE BARRAS\r\n - ^BY3,2,148\r\n - ^FO500,845\r\n - ^BCR,,N,N\r\n - ^CI28^FD${upperCaseRecord.expeditionFk}^FS\r\n\r\n - ^FX TEXTO CON CAJA CODIGO DE BARRAS\r\n - ^FO430,900\r\n - ^GB60,220,2,,^FS\r\n - ^FO435,932\r\n - ^A@R,40,40,E:ARIALR.TTF 1036584\r\n - ^CI28^FD${upperCaseRecord.expeditionFk}^FS\r\n\r\n - ^FO262,845\r\n - ^GB40,155,2,,^FS\r\n - ^FO268,854\r\n - ^A@R,24,24,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.itemFk}^FS\r\n\r\n - ^FO262,1030\r\n - ^GB40,155,2,,^FS\r\n - ^FO268,1130\r\n - ^A@R,24,24,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.quantity}^FS\r\n\r\n - ^FO200,845\r\n - ^GB40,340,2,,^FS\r\n - ^FO206,854\r\n - ^A@R,24,24,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.longName}^FS\r\n\r\n - ^FO142,845\r\n - ^GB40,130,2,,^FS\r\n - ^FO148,854\r\n - ^A@R,24,24,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.shelvingFk}^FS\r\n\r\n - ^FO142,1000\r\n - ^GB40,186,2,,^FS\r\n - ^FO148,1100\r\n - ^A@R,24,24,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.parkingCode}^FS\r\n\r\n - ^FO40,845\r\n - ^GB80,340,2,,^FS\r\n - ^FO86,854\r\n - ^A@R,24,24,E:ARIALB.TTF 980756\r\n - ^CI28^FD${upperCaseRecord.comments}^FS\r\n\r\n - ^FX INCLUIMOS LA ESCRITURA DE LA ETIQUETA RFID\r\n - ^RFW,H,0,12,E\r\n - ^FD${rf_id_venature + id_venature}^FS\r\n\r\n - ^XZ` - } - }; -}; diff --git a/backend/worker/worker.js b/backend/worker/worker.js index 75715da..0f4c5ef 100644 --- a/backend/worker/worker.js +++ b/backend/worker/worker.js @@ -38,14 +38,13 @@ async function getConnectionWithRetries(retries = 3, delay = 5000) { } //Función para enviar ZPL a la impresora con TCP socket y reintentos -async function sendZPL(zplContent, ipAddress, retries = 2, delay = 3000) { +async function sendZPL(zplContent, ipAddress, retries = 3, delay = 2000) { const port = 9100; // puerto que se utiliza para el envio de zpl junto con el ipAddress for (let attempt = 0; attempt < retries; attempt++) { try { const result = await new Promise((resolve, reject) => { const client = new net.Socket(); - let dataReceived = false; // Bandera para rastrear si se recibió respuesta client.connect(port, ipAddress, () => { client.write(zplContent, () => { @@ -61,11 +60,7 @@ async function sendZPL(zplContent, ipAddress, retries = 2, delay = 3000) { client.on('close', () => { logger.info('Conexión cerrada'); - // Si no se recibió ningún dato, considerarlo como cerrado exitosamente - if (!dataReceived) - resolve('success'); // Considerar éxito si la impresora cerró la conexión sin error - else - resolve('closed'); + resolve('closed'); }); });