Merge pull request 'refactor: refs #4452 Remove unnecessary files, update DB settings/schema, refactor RFID/event handling, add ZPL generation.' (#1) from 4452-vnChanges into main

Reviewed-on: verdnatura/dismuntel#1
This commit is contained in:
Guillermo Bonet 2024-09-13 10:28:22 +00:00
commit 4d40da52db
9 changed files with 52 additions and 298 deletions

8
.gitignore vendored
View File

@ -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

View File

@ -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

View File

@ -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'),

View File

@ -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
});

View File

@ -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);
}
}
}

View File

@ -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`
}
};
};

View File

@ -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 = 3, delay = 5000) {
@ -38,25 +38,18 @@ 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, () => {
logger.info(`Conexión establecida con la impresora en el intento ${attempt + 1}`);
client.write(zplContent);
});
client.on('data', data => {
dataReceived = true; // Se ha recibido respuesta
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 => {
@ -67,29 +60,21 @@ 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');
});
});
if (result === 'success') {
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);
if (attempt >= retries - 1) {
if (attempt >= retries - 1)
return 'error';
}
await new Promise(resolve => setTimeout(resolve, delay));
}
@ -97,15 +82,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);
@ -121,10 +106,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];
@ -138,13 +125,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();
@ -159,7 +145,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`);
@ -167,13 +153,13 @@ 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]
@ -186,7 +172,6 @@ async function processRecord(record) {
[record.expeditionFk]
);
}
parentPort.postMessage('done');
await connection.commit();
} catch (error) {
@ -198,20 +183,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));
}
});

View File

@ -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();
}
}
}

View File

@ -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: