From d0975f0acdb5bc289672218e747e7ee4c4ba585c Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 2 Nov 2023 16:25:25 +0100 Subject: [PATCH 001/150] ref #6276 operator_add --- db/changes/234601/00-newWareHouse.sql | 0 modules/worker/back/methods/operator/add.js | 21 +++++++++++++++++++++ modules/worker/back/models/operator.js | 4 +++- 3 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 db/changes/234601/00-newWareHouse.sql create mode 100644 modules/worker/back/methods/operator/add.js diff --git a/db/changes/234601/00-newWareHouse.sql b/db/changes/234601/00-newWareHouse.sql new file mode 100644 index 000000000..e69de29bb diff --git a/modules/worker/back/methods/operator/add.js b/modules/worker/back/methods/operator/add.js new file mode 100644 index 000000000..65639ad01 --- /dev/null +++ b/modules/worker/back/methods/operator/add.js @@ -0,0 +1,21 @@ +module.exports = Self => { + Self.remoteMethodCtx('add', { + description: 'Add a new operator', + accessType: 'WRITE', + http: { + path: `/add`, + verb: 'POST' + } + }); + + Self.add = async ctx => { + const userId = ctx.req.accessToken.userId; + // He visto findOrCreate pero no funciona + const user = await Self.findById(userId); + if (!user) { + await Self.create({ + workerFk: userId + }); + } + }; +}; diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index db1ac7e49..442ac343f 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -1,4 +1,6 @@ -module.exports = function(Self) { +module.exports = Self => { + require('../methods/operator/add')(Self); + Self.observe('after save', async function(ctx) { const instance = ctx.data || ctx.instance; const models = Self.app.models; From 251578146edd44bd55b2c5489c0b12351738ec3f Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 21 Nov 2023 12:32:36 +0100 Subject: [PATCH 002/150] refs #6276 several methods created --- back/methods/collection/assignCollection.js | 28 + back/models/collection.js | 1 + db/changes/234601/00-newWareHouse.sql | 4 + db/dump/fixtures.sql | 669 ++++++++++++++++++ modules/item/back/methods/item/card.js | 52 ++ modules/item/back/models/item.js | 1 + .../methods/expedition-pallet/getPallet.js | 53 ++ .../ticket/back/models/expeditionPallet.js | 3 + .../ticket/back/models/expeditionPallet.json | 29 +- modules/worker/back/methods/operator/add.js | 1 - .../methods/operator/getAvailablePrinters.js | 39 + .../back/methods/operator/getPrinter.js | 39 + modules/worker/back/models/operator.js | 2 + 13 files changed, 913 insertions(+), 8 deletions(-) create mode 100644 back/methods/collection/assignCollection.js create mode 100644 modules/item/back/methods/item/card.js create mode 100644 modules/ticket/back/methods/expedition-pallet/getPallet.js create mode 100644 modules/ticket/back/models/expeditionPallet.js create mode 100644 modules/worker/back/methods/operator/getAvailablePrinters.js create mode 100644 modules/worker/back/methods/operator/getPrinter.js diff --git a/back/methods/collection/assignCollection.js b/back/methods/collection/assignCollection.js new file mode 100644 index 000000000..e63e6c1d0 --- /dev/null +++ b/back/methods/collection/assignCollection.js @@ -0,0 +1,28 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.remoteMethodCtx('assignCollection', { + description: 'Assign a collection', + accessType: 'WRITE', + http: { + path: `/assignCollection`, + verb: 'POST' + }, + returns: { + type: ['object'], + }, + }); + + Self.assignCollection = async ctx => { + const userId = ctx.req.accessToken.userId; + + await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk)', [userId]); + + const [assignedCollection] = await Self.rawSql('SELECT @vCollectionFk'); + const {'@vCollectionFk': collectionFk} = assignedCollection; + + if (!collectionFk) throw new UserError('No hay tickets para sacar'); + await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk]); + + return collectionFk; + }; +}; diff --git a/back/models/collection.js b/back/models/collection.js index bfa906af6..28413743e 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -5,4 +5,5 @@ module.exports = Self => { require('../methods/collection/setSaleQuantity')(Self); require('../methods/collection/previousLabel')(Self); require('../methods/collection/getTickets')(Self); + require('../methods/collection/assignCollection')(Self); }; diff --git a/db/changes/234601/00-newWareHouse.sql b/db/changes/234601/00-newWareHouse.sql index e69de29bb..4a2344330 100644 --- a/db/changes/234601/00-newWareHouse.sql +++ b/db/changes/234601/00-newWareHouse.sql @@ -0,0 +1,4 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'employee'), + ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index fa204ddd5..6ef420526 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1218,6 +1218,7 @@ INSERT INTO `vn`.`train`(`id`, `name`) INSERT INTO `vn`.`operator` (`workerFk`, `numberOfWagons`, `trainFk`, `itemPackingTypeFk`, `warehouseFk`, `sectorFk`, `labelerFk`) VALUES ('1106', '1', '1', 'H', '1', '1', '1'), + ('9', '2', '1', 'H', '1', '1', '1'), ('1107', '1', '1', 'V', '1', '1', '1'); INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`, `created`, `trainFk`) @@ -2996,3 +2997,671 @@ INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) (1, 'Error in VAT calculation'), (2, 'Error in sales details'), (3, 'Error in customer data'); + + +/* + Se necesitan, para hacer un simulacro de pedido, lo siguiente: + + - Warehouse 999 + - Sectores + - Normal 9991 + - Previa 9992 + - Altillo 9993 + - Parkings + - Normal A-01-1, A-02-2, B-03-3, B-04-4, C-05-5 + - Previa P-01-1, P-02-2, P-03-3 + - Altillo M-01-1, M-02-2, M-03-3 + - Shelvings + - Normal NAA, NBB, NCC, NDD, NEE + - Previa PAA, PBB, PCC + - Altillo MAA, MBB, MCC + - Items + * Normal + * Previa: + - Ticket + - Sales + +*/ + +INSERT IGNORE INTO intrastat + SET id = 44219999, + description = 'Manufacturas de madera', + taxClassFk = 1, + taxCodeFk = 1; + +INSERT IGNORE INTO warehouse + SET id = 999, + name = 'TestingWarehouse', + hasAvailable = TRUE, + isForTicket = TRUE, + isInventory = TRUE, + hasUbications = TRUE, + hasProduction = TRUE; + +INSERT IGNORE INTO sector + SET id = 9991, + description = 'NormalSector', + warehouseFk = 999, + isPreviousPreparedByPacking = FALSE, + code = 'NS', + isPreviousPrepared = FALSE, + isPackagingArea = FALSE, + sonFk = NULL, + isMain = TRUE, + itemPackingTypeFk = NULL; + +INSERT IGNORE INTO sector + SET id = 9992, + description = 'PreviousSector', + warehouseFk = 999, + isPreviousPreparedByPacking = FALSE, + code = 'PS', + isPreviousPrepared = TRUE, + isPackagingArea = FALSE, + sonFk = NULL, + isMain = TRUE, + itemPackingTypeFk = NULL; + +INSERT IGNORE INTO sector + SET id = 9993, + description = 'MezaninneSector', + warehouseFk = 999, + isPreviousPreparedByPacking = TRUE, + code = 'MS', + isPreviousPrepared = FALSE, + isPackagingArea = FALSE, + sonFk = 9991, + isMain = TRUE, + itemPackingTypeFk = NULL; + +REPLACE parking SET id = 9991011, sectorFk = 9991, code = 'A-01-1', pickingOrder = 1; +REPLACE parking SET id = 9991012, sectorFk = 9991, code = 'A-02-2', pickingOrder = 2; +REPLACE parking SET id = 9991013, sectorFk = 9991, code = 'A-03-3', pickingOrder = 3; +REPLACE parking SET id = 9991014, sectorFk = 9991, code = 'A-04-4', pickingOrder = 4; +REPLACE parking SET id = 9991015, sectorFk = 9991, code = 'A-05-5', pickingOrder = 5; + +REPLACE parking SET id = 9992011, sectorFk = 9992, code = 'P-01-1', pickingOrder = 6; +REPLACE parking SET id = 9992012, sectorFk = 9992, code = 'P-02-2', pickingOrder = 7; +REPLACE parking SET id = 9992013, sectorFk = 9992, code = 'P-03-3', pickingOrder = 8; + +REPLACE parking SET id = 9993011, sectorFk = 9993, code = 'M-01-1', pickingOrder = 9; +REPLACE parking SET id = 9993012, sectorFk = 9993, code = 'M-02-2', pickingOrder = 10; +REPLACE parking SET id = 9993013, sectorFk = 9993, code = 'M-03-3', pickingOrder = 11; + +REPLACE shelving SET code = 'NAA', parkingFk = 9991011, priority = 1; +REPLACE shelving SET code = 'NBB', parkingFk = 9991012, priority = 1; +REPLACE shelving SET code = 'NCC', parkingFk = 9991013, priority = 1; +REPLACE shelving SET code = 'NDD', parkingFk = 9991014, priority = 1; +REPLACE shelving SET code = 'NEE', parkingFk = 9991015, priority = 1; + +REPLACE shelving SET code = 'PAA', parkingFk = 9992011, priority = 1; +REPLACE shelving SET code = 'PBB', parkingFk = 9992012, priority = 1; +REPLACE shelving SET code = 'PCC', parkingFk = 9992013, priority = 1; + +REPLACE shelving SET code = 'MAA', parkingFk = 9993011, priority = 1; +REPLACE shelving SET code = 'MBB', parkingFk = 9993012, priority = 1; +REPLACE shelving SET code = 'MCC', parkingFk = 9993013, priority = 1; + +INSERT IGNORE INTO itemType + SET id = 999, + code = 'WOO', + name = 'Wood Objects', + categoryFk = 3, + workerFk = 103, + isInventory = TRUE, + life = 10, + density = 250, + itemPackingTypeFk = NULL, + temperatureFk = 'warm'; + +INSERT IGNORE INTO travel + SET id = 99, + shipped = CURDATE(), + landed = CURDATE(), + warehouseInFk = 999, + warehouseOutFk = 1, + isReceived = TRUE, + agencyFk = 1; + +REPLACE entry + SET id = 999, + supplierFk = 791, + isConfirmed = TRUE, + dated = CURDATE(), + travelFk = 99, + companyFk = 442; + +REPLACE ticket + SET id = 999999, + clientFk = 2, + warehouseFk = 999, + shipped = CURDATE(), + nickname = 'Cliente', + addressFk = 1, + companyFk = 442, + agencyModeFk = 10, + landed = CURDATE(); + +REPLACE collection + SET id = 10101010, + workerFk = 103; + +INSERT IGNORE INTO ticketCollection + SET id = 10101010, + ticketFk = 999999, + collectionFk = 10101010; + +REPLACE item + SET id = 999991, + name = 'Palito para pinchos', + `size` = 25, + stems = NULL, + category = 'EXT', + typeFk = 999, + longName = 'Palito para pinchos', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 6, + intrastatFk = 44219999; + +REPLACE buy + SET id = 9999991, + entryFk = 999, + itemFk = 999991, + quantity = 8, + buyingValue = 0.61, + stickers = 1, + packing = 20, + `grouping` = 1, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 50; + +REPLACE sale + SET id = 99991, + itemFk = 999991, + ticketFk = 999999, + concept = 'Palito para pinchos', + quantity = 3, + price = 1, + discount = 0; + +REPLACE item + SET id = 999992, + name = 'Madera verde', + `size` = 10, + stems = NULL, + category = 'EXT', + typeFk = 999, + longName = 'Madera verde', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 50, + intrastatFk = 44219999; + +REPLACE buy + SET id = 9999992, + entryFk = 999, + itemFk = 999992, + quantity = 40, + buyingValue = 0.62, + stickers = 1, + packing = 40, + `grouping` = 5, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 25; + +REPLACE sale + SET id = 99992, + itemFk = 999992, + ticketFk = 999999, + concept = 'Madera Verde', + quantity = 10, + price = 1, + discount = 0; + +REPLACE item + SET id = 999993, + name = 'Madera Roja/Morada', + `size` = 12, + stems = 2, + category = 'EXT', + typeFk = 999, + longName = 'Madera Roja/Morada', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 35, + intrastatFk = 44219999; + +REPLACE buy + SET id = 9999993, + entryFk = 999, + itemFk = 999993, + quantity = 20, + buyingValue = 0.63, + stickers = 2, + packing = 10, + `grouping` = 5, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 25; + +REPLACE itemShelving + SET id = 9931, + itemFk = 999993, + shelvingFk = 'NCC', + visible = 10, + `grouping` = 5, + packing = 10; + +REPLACE sale + SET id = 99993, + itemFk = 999993, + ticketFk = 999999, + concept = 'Madera Roja/Morada', + quantity = 15, + price = 1, + discount = 0; + +REPLACE item + SET id = 999994, + name = 'Madera Naranja', + `size` = 18, + stems = 1, + category = 'EXT', + typeFk = 999, + longName = 'Madera Naranja', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 160, + intrastatFk = 44219999; + +REPLACE buy + SET id = 9999994, + entryFk = 999, + itemFk = 999994, + quantity = 20, + buyingValue = 0.64, + stickers = 1, + packing = 20, + `grouping` = 4, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 25; + +REPLACE sale + SET id = 99994, + itemFk = 999994, + ticketFk = 999999, + concept = 'Madera Naranja', + quantity = 4, + price = 1, + discount = 0; + +REPLACE item + SET id = 999995, + name = 'Madera Amarilla', + `size` = 11, + stems = 5, + category = 'EXT', + typeFk = 999, + longName = 'Madera Amarilla', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE buy + SET id = 9999995, + entryFk = 999, + itemFk = 999995, + quantity = 4, + buyingValue = 0.65, + stickers = 1, + packing = 20, + `grouping` = 1, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + +REPLACE sale + SET id = 99995, + itemFk = 999995, + ticketFk = 999999, + concept = 'Madera Amarilla', + quantity = 5, + price = 1, + discount = 0; + +-- Palito naranja +REPLACE item + SET id = 999998, + name = 'Palito naranja', + `size` = 11, + stems = 1, + category = 'EXT', + typeFk = 999, + longName = 'Palito naranja', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE buy + SET id = 9999998, + entryFk = 999, + itemFk = 999998, + quantity = 80, + buyingValue = 0.65, + stickers = 1, + packing = 200, + `grouping` = 30, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + +REPLACE sale + SET id = 99998, + itemFk = 999998, + ticketFk = 999999, + concept = 'Palito naranja', + quantity = 60, + price = 1, + discount = 0; + +-- Palito amarillo +REPLACE item + SET id = 999999, + name = 'Palito amarillo', + `size` = 11, + stems = 1, + category = 'EXT', + typeFk = 999, + longName = 'Palito amarillo', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE buy + SET id = 9999999, + entryFk = 999, + itemFk = 999999, + quantity = 70, + buyingValue = 0.65, + stickers = 1, + packing = 500, + `grouping` = 10, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + +REPLACE sale + SET id = 99999, + itemFk = 999999, + ticketFk = 999999, + concept = 'Palito amarillo', + quantity = 50, + price = 1, + discount = 0; + +-- Palito azul +REPLACE item + SET id = 1000000, + name = 'Palito azul', + `size` = 10, + stems = 1, + category = 'EXT', + typeFk = 999, + longName = 'Palito azul', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE buy + SET id = 10000000, + entryFk = 999, + itemFk = 1000000, + quantity = 75, + buyingValue = 0.65, + stickers = 2, + packing = 300, + `grouping` = 50, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + +REPLACE sale + SET id = 100000, + itemFk = 1000000, + ticketFk = 999999, + concept = 'Palito azul', + quantity = 50, + price = 1, + discount = 0; + +-- Palito rojo +REPLACE item + SET id = 1000001, + name = 'Palito rojo', + `size` = 10, + stems = NULL, + category = 'EXT', + typeFk = 999, + longName = 'Palito rojo', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE buy + SET id = 10000001, + entryFk = 999, + itemFk = 1000001, + quantity = 12, + buyingValue = 0.65, + stickers = 2, + packing = 50, + `grouping` = 5, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + + +REPLACE sale + SET id = 100001, + itemFk = 1000001, + ticketFk = 999999, + concept = 'Palito rojo', + quantity = 10, + price = 1, + discount = 0; + +-- Previa +INSERT IGNORE INTO item + SET id = 999996, + name = 'Bolas de madera', + `size` = 2, + stems = 4, + category = 'EXT', + typeFk = 999, + longName = 'Bolas de madera', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 20, + intrastatFk = 44219999; + +REPLACE buy + SET id = 9999996, + entryFk = 999, + itemFk = 999996, + quantity = 5, + buyingValue = 3, + stickers = 1, + packing = 5, + `grouping` = 2, + groupingMode = 1, + packageFk = 94, + price1 = 7, + price2 = 7, + price3 = 7, + minPrice = 7, + weight = 80; + +REPLACE sale + SET id = 99996, + itemFk = 999996, + ticketFk = 999999, + concept = 'Bolas de madera', + quantity = 4, + price = 7, + discount = 0, + isPicked = TRUE; + +INSERT IGNORE INTO item + SET id = 999997, + name = 'Palitos de polo MIX', + `size` = 14, + stems = NULL, + category = 'EXT', + typeFk = 999, + longName = 'Palitos de polo MIX', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 20, + intrastatFk = 44219999; + +REPLACE buy + SET id = 9999997, + entryFk = 999, + itemFk = 999997, + quantity = 100, + buyingValue = 3.2, + stickers = 1, + packing = 100, + `grouping` = 5, + groupingMode = 1, + packageFk = 94, + price1 = 7, + price2 = 7, + price3 = 7, + minPrice = 7, + weight = 80; + +REPLACE sale + SET id = 99997, + itemFk = 999997, + ticketFk = 999999, + concept = 'Palitos de polo MIX', + quantity = 5, + price = 7, + discount = 0; + +-- Ubicación +DELETE ish.* + FROM itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector s ON s.id = p.sectorFk + JOIN warehouse w ON w.id = s.warehouseFk + WHERE w.name = 'TestingWarehouse'; + +REPLACE vn.itemShelving +(id, itemFk, shelvingFk, visible, created, `grouping`, packing, packagingFk, userFk, isChecked) +VALUES + (9911, 999991, 'NAA', 8, '2023-09-20', 1, 20, NULL, 103, NULL), + (9912, 999998, 'NAA', 80, '2023-09-20', 10, 30, NULL, 103, NULL), + (9913, 1000001, 'NAA', 6, '2023-09-20', 3, 50, NULL, 103, NULL), + (9914, 1000000, 'NBB', 50, '2023-09-18', 25, 500, NULL, 103, NULL), + (9915, 999993, 'NBB', 25, '2023-09-18', NULL, 10, NULL, 103, NULL), + (9916, 999999, 'NBB', 30, '2023-09-18', 10, 500, NULL, 103, NULL), + (9917, 999993, 'NCC', 25, '2023-09-20', 5, 10, NULL, 103, NULL), + (9918, 999997, 'NCC', 10, '2023-09-20', NULL, 100, NULL, 103, NULL), + (9919, 999999, 'NCC', 40, '2023-09-20', 10, 500, NULL, 103, NULL), + (9920, 999995, 'NDD', 10, '2023-09-19', NULL, 20, NULL, 103, NULL), + (9921, 999994, 'NDD', 48, '2023-09-19', 4, 20, NULL, 103, NULL), + (9922, 1000001, 'NEE', 6, '2023-09-21', 3, 50, NULL, 103, NULL), + (9923, 999992, 'NEE', 50, '2023-09-21', NULL, 1, NULL, 103, NULL), + (9924, 1000000, 'NEE', 25, '2023-09-21', 25, 500, NULL, 103, NULL), + (9925, 999996, 'PAA', 5, '2023-09-27', 1, 5, NULL, 103, NULL), + (9926, 999997, 'PCC', 10, '2023-09-27', 5, 100, NULL, 103, NULL); + +-- Previous for Bolas de madera +INSERT IGNORE INTO sectorCollection + SET id = 99, + userFk = 1, + sectorFk = 9992; + +INSERT IGNORE INTO saleGroup + SET id = 999, + userFk = 1, + parkingFk = 9992011, + sectorFk = 9992; + +INSERT IGNORE INTO sectorCollectionSaleGroup + SET id = 9999, + sectorCollectionFk = 99, + saleGroupFk = 999; + +REPLACE saleGroupDetail + SET id = 99991, + saleFk = 99996, + saleGroupFk = 999; + +REPLACE saleTracking + SET saleFk = 99996, + isChecked = TRUE, + workerFk = 103, + stateFk = 28; + +INSERT IGNORE INTO itemShelvingSale + SET id = 991, + itemShelvingFk = 9962, + saleFk = 99996, + quantity = 5, + userFk = 1; + + +CALL itemShelvingSale_reserveByCollection(10101010); + +UPDATE vn.collection + SET workerFk=9 + WHERE id=10101010; diff --git a/modules/item/back/methods/item/card.js b/modules/item/back/methods/item/card.js new file mode 100644 index 000000000..6d861b394 --- /dev/null +++ b/modules/item/back/methods/item/card.js @@ -0,0 +1,52 @@ +module.exports = Self => { + Self.remoteMethod('card', { + description: 'Idk', + accessType: 'READ', + http: { + path: `/card`, + verb: 'GET' + }, + accepts: [ + { + arg: 'itemFk', + type: 'number', + required: true, + }, + { + arg: 'warehouseFk', + type: 'number', + required: true, + } + ], + returns: { + type: ['object'], + root: true + }, + }); + + Self.card = async(itemFk, warehouseFk) => { + const models = Self.app.models; + + const [result] = await Self.rawSql('CALL vn.item_getInfo(?, ?)', [itemFk, warehouseFk]); + + const barcodeItems = await Self.rawSql('SELECT vn.barcodeToItem(?) as realIdItem', [itemFk]); + const realIdItems = barcodeItems.map(barcodeItem => barcodeItem.realIdItem); + + const barcodes = await models.ItemBarcode.find({ + fields: ['code'], + where: { + realIdItem: { + inq: realIdItems + } + } + }); + + let itemInfo; + if (result.length) { + itemInfo = {...result[0]}; + itemInfo.barcodes = barcodes.map(barcode => barcode.code); + } + + return itemInfo; + }; +}; diff --git a/modules/item/back/models/item.js b/modules/item/back/models/item.js index eac1ecb7d..17c7a59f1 100644 --- a/modules/item/back/models/item.js +++ b/modules/item/back/models/item.js @@ -17,6 +17,7 @@ module.exports = Self => { require('../methods/item/buyerWasteEmail')(Self); require('../methods/item/labelPdf')(Self); require('../methods/item/setVisibleDiscard')(Self); + require('../methods/item/card')(Self); Self.validatesPresenceOf('originFk', {message: 'Cannot be blank'}); diff --git a/modules/ticket/back/methods/expedition-pallet/getPallet.js b/modules/ticket/back/methods/expedition-pallet/getPallet.js new file mode 100644 index 000000000..09775a6fa --- /dev/null +++ b/modules/ticket/back/methods/expedition-pallet/getPallet.js @@ -0,0 +1,53 @@ + +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.remoteMethod('getPallet', { + description: 'Get pallet', + accessType: 'READ', + accepts: [ + { + arg: 'expeditionFk', + type: 'integer', + }, + ], + http: { + path: `/getPallet`, + verb: 'GET' + }, + returns: { + type: 'object', + }, + }); + + Self.getPallet = async expeditionFk => { + try { + const pallet = await Self.findOne({ + fields: ['truckFk'], + where: { + id: expeditionFk + }, + include: [ + { + relation: 'expeditionTruck', + scope: { + fields: ['eta', 'description'] + } + } + ], + }); + + if (pallet) { + const truck = pallet.expeditionTruck(); + return { + truckFk: pallet.truckFk, + eta: truck.eta, + description: truck.description + }; + } + + throw new UserError('palletDoesNotExist'); + } catch (e) { + return {message: e.message}; + } + }; +}; diff --git a/modules/ticket/back/models/expeditionPallet.js b/modules/ticket/back/models/expeditionPallet.js new file mode 100644 index 000000000..f41ad7712 --- /dev/null +++ b/modules/ticket/back/models/expeditionPallet.js @@ -0,0 +1,3 @@ +module.exports = function(Self) { + require('../methods/expedition-pallet/getPallet')(Self); +}; diff --git a/modules/ticket/back/models/expeditionPallet.json b/modules/ticket/back/models/expeditionPallet.json index c5a38df75..7cb4e1e6d 100644 --- a/modules/ticket/back/models/expeditionPallet.json +++ b/modules/ticket/back/models/expeditionPallet.json @@ -1,5 +1,6 @@ { "name": "ExpeditionPallet", + "base": "VnModel", "options": { "mysql": { "table": "expeditionPallet" @@ -10,13 +11,27 @@ "type": "number", "id": true, "description": "Identifier" - } + }, + "truckFk": { + "type": "number" + }, + "built": { + "type": "date" + }, + "position": { + "type": "number" + }, + "isPrint": { + "type": "number" + } }, - "acls": [{ - "accessType": "WRITE", - "principalType": "ROLE", - "principalId": "production", - "permission": "ALLOW" - }] + "relations": { + "expeditionTruck": { + "type": "belongsTo", + "model": "ExpeditionTruck", + "foreignKey": "truckFk" + } + } + } diff --git a/modules/worker/back/methods/operator/add.js b/modules/worker/back/methods/operator/add.js index 65639ad01..eaf74e7b4 100644 --- a/modules/worker/back/methods/operator/add.js +++ b/modules/worker/back/methods/operator/add.js @@ -10,7 +10,6 @@ module.exports = Self => { Self.add = async ctx => { const userId = ctx.req.accessToken.userId; - // He visto findOrCreate pero no funciona const user = await Self.findById(userId); if (!user) { await Self.create({ diff --git a/modules/worker/back/methods/operator/getAvailablePrinters.js b/modules/worker/back/methods/operator/getAvailablePrinters.js new file mode 100644 index 000000000..2e787da2b --- /dev/null +++ b/modules/worker/back/methods/operator/getAvailablePrinters.js @@ -0,0 +1,39 @@ +module.exports = Self => { + Self.remoteMethodCtx('getAvailablePrinters', { + description: 'Retrieve available printers for an user', + accessType: 'READ', + http: { + path: `/getAvailabePrinters`, + verb: 'GET' + }, + returns: { + type: ['object'], + }, + }); + + Self.getAvailablePrinters = async ctx => { + const userId = ctx.req.accessToken.userId; + + const operators = await Self.find({ + fields: [], + where: { + workerFk: userId, + }, + + include: { + relation: 'printer', + scope: { + fields: ['id', 'name'] + }, + where: { + isLabeler: {neq: 0} + } + } + }); + if (operators.length) { + return operators.map(operator => { + return operator.printer(); + }); + } + }; +}; diff --git a/modules/worker/back/methods/operator/getPrinter.js b/modules/worker/back/methods/operator/getPrinter.js new file mode 100644 index 000000000..c46734517 --- /dev/null +++ b/modules/worker/back/methods/operator/getPrinter.js @@ -0,0 +1,39 @@ +module.exports = Self => { + Self.remoteMethodCtx('getPrinter', { + description: 'Gets user\'s printer', + accessType: 'READ', + http: { + path: `/getPrinter`, + verb: 'GET' + }, + returns: { + type: 'object', + }, + }); + + Self.getPrinter = async ctx => { + const userId = ctx.req.accessToken.userId; + + const operator = await Self.findOne({ + include: [ + { + relation: 'printer', + scope: { + fields: ['id', 'name'], + } + } + ], + where: { + workerFk: userId + } + }); + + if (operator) { + const printer = operator.printer(); + return { + id: printer.id, + name: printer.name + }; + } + }; +}; diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index 442ac343f..5e8870130 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -1,5 +1,7 @@ module.exports = Self => { require('../methods/operator/add')(Self); + require('../methods/operator/getPrinter')(Self); + require('../methods/operator/getAvailablePrinters')(Self); Self.observe('after save', async function(ctx) { const instance = ctx.data || ctx.instance; From fac6aab26c23e556e6b55e7138029d5424a25267 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 22 Nov 2023 14:25:19 +0100 Subject: [PATCH 003/150] refs #6276 machineWorker_update --- back/methods/machine-worker/updateMachine.js | 71 +++++++++++++++++++ back/model-config.json | 6 ++ back/models/machine-worker-config.json | 18 +++++ back/models/machine-worker.js | 3 + back/models/machine.json | 18 +++++ .../{234601 => 234801}/00-newWareHouse.sql | 6 +- 6 files changed, 121 insertions(+), 1 deletion(-) create mode 100644 back/methods/machine-worker/updateMachine.js create mode 100644 back/models/machine-worker-config.json create mode 100644 back/models/machine-worker.js create mode 100644 back/models/machine.json rename db/changes/{234601 => 234801}/00-newWareHouse.sql (60%) diff --git a/back/methods/machine-worker/updateMachine.js b/back/methods/machine-worker/updateMachine.js new file mode 100644 index 000000000..ac52a3f48 --- /dev/null +++ b/back/methods/machine-worker/updateMachine.js @@ -0,0 +1,71 @@ +module.exports = Self => { + Self.remoteMethodCtx('updateMachine', { + description: '', + accessType: 'WRITE', + accepts: [ + { + arg: 'plate', + type: 'string', + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/update-machine`, + verb: 'POST' + } + }); + + Self.updateMachine = async(ctx, plate, options) => { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + let insertState = false; + + const machine = await models.Machine.findOne({ + fields: ['id', 'plate'], + where: {plate} + }, myOptions); + + if (machine) { + const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); + + const machineWorker = await models.MachineWorker.findOne({ + where: { + workerFk: userId, + inTime: {gte: new Date(Date.now() - maxHours * 60 * 60 * 1000)}, + outTimed: null, + machineFk: machine.id, + } + + }); + if (machineWorker) { + await machineWorker.updateAttributes({ + inTime: new Date(Date.now()) + }, myOptions); + } + insertState = true; + } + + if (tx) await tx.commit(); + return insertState; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/back/model-config.json b/back/model-config.json index ebc0e321b..856167757 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -79,9 +79,15 @@ "Language": { "dataSource": "vn" }, + "Machine": { + "dataSource": "vn" + }, "MachineWorker": { "dataSource": "vn" }, + "MachineWorkerConfig": { + "dataSource": "vn" + }, "MobileAppVersionControl": { "dataSource": "vn" }, diff --git a/back/models/machine-worker-config.json b/back/models/machine-worker-config.json new file mode 100644 index 000000000..dfb77124e --- /dev/null +++ b/back/models/machine-worker-config.json @@ -0,0 +1,18 @@ +{ + "name": "MachineWorkerConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "vn.machineWorkerConfig" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "maxHours": { + "type": "number" + } + } +} diff --git a/back/models/machine-worker.js b/back/models/machine-worker.js new file mode 100644 index 000000000..324ca28a9 --- /dev/null +++ b/back/models/machine-worker.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/machine-worker/updateMachine')(Self); +}; diff --git a/back/models/machine.json b/back/models/machine.json new file mode 100644 index 000000000..7029091a2 --- /dev/null +++ b/back/models/machine.json @@ -0,0 +1,18 @@ +{ + "name": "Machine", + "base": "VnModel", + "options": { + "mysql": { + "table": "vn.machine" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "plate": { + "type": "string" + } + } +} diff --git a/db/changes/234601/00-newWareHouse.sql b/db/changes/234801/00-newWareHouse.sql similarity index 60% rename from db/changes/234601/00-newWareHouse.sql rename to db/changes/234801/00-newWareHouse.sql index 4a2344330..e55835563 100644 --- a/db/changes/234601/00-newWareHouse.sql +++ b/db/changes/234801/00-newWareHouse.sql @@ -1,4 +1,8 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'); \ No newline at end of file + ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('MachineWorker','updateMachine','WRITE','ALLOW','ROLE','employee'); + +INSERT INTO `vn`.`machineWorkerConfig` (id, maxHours) + VALUES (1, 12) \ No newline at end of file From f862ed7d8af3076ab15aa6000575e6611cb2d2a6 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 23 Nov 2023 13:19:59 +0100 Subject: [PATCH 004/150] refs #6274 refactor updateInTime --- back/methods/machine-worker/updateInTime.js | 63 ++++++++++++++++ back/methods/machine-worker/updateMachine.js | 71 ------------------- back/models/machine-worker.js | 2 +- .../{234801 => 235001}/00-newWareHouse.sql | 5 +- db/dump/fixtures.sql | 3 + 5 files changed, 68 insertions(+), 76 deletions(-) create mode 100644 back/methods/machine-worker/updateInTime.js delete mode 100644 back/methods/machine-worker/updateMachine.js rename db/changes/{234801 => 235001}/00-newWareHouse.sql (64%) diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js new file mode 100644 index 000000000..b8e2becf2 --- /dev/null +++ b/back/methods/machine-worker/updateInTime.js @@ -0,0 +1,63 @@ +module.exports = Self => { + Self.remoteMethodCtx('updateInTime', { + description: '', + accessType: 'WRITE', + accepts: [ + { + arg: 'plate', + type: 'string', + } + ], + http: { + path: `/updateInTime`, + verb: 'POST' + } + }); + + Self.updateInTime = async(ctx, plate, options) => { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const machine = await models.Machine.findOne({ + fields: ['id', 'plate'], + where: {plate} + }, myOptions); + + if (!machine) throw new Error(`plate ${plate} does not exist`); + + const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); + + const machineWorker = await models.MachineWorker.findOne({ + where: { + workerFk: userId, + inTime: {gte: new Date(Date.now() - maxHours * 60 * 60 * 1000)}, + outTimed: null, + machineFk: machine.id, + } + + }); + if (machineWorker) { + await machineWorker.updateAttributes({ + inTime: new Date(Date.now()) + }, myOptions); + } + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/back/methods/machine-worker/updateMachine.js b/back/methods/machine-worker/updateMachine.js deleted file mode 100644 index ac52a3f48..000000000 --- a/back/methods/machine-worker/updateMachine.js +++ /dev/null @@ -1,71 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('updateMachine', { - description: '', - accessType: 'WRITE', - accepts: [ - { - arg: 'plate', - type: 'string', - } - ], - returns: { - type: 'object', - root: true - }, - http: { - path: `/update-machine`, - verb: 'POST' - } - }); - - Self.updateMachine = async(ctx, plate, options) => { - const models = Self.app.models; - const userId = ctx.req.accessToken.userId; - - let tx; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - let insertState = false; - - const machine = await models.Machine.findOne({ - fields: ['id', 'plate'], - where: {plate} - }, myOptions); - - if (machine) { - const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); - - const machineWorker = await models.MachineWorker.findOne({ - where: { - workerFk: userId, - inTime: {gte: new Date(Date.now() - maxHours * 60 * 60 * 1000)}, - outTimed: null, - machineFk: machine.id, - } - - }); - if (machineWorker) { - await machineWorker.updateAttributes({ - inTime: new Date(Date.now()) - }, myOptions); - } - insertState = true; - } - - if (tx) await tx.commit(); - return insertState; - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/back/models/machine-worker.js b/back/models/machine-worker.js index 324ca28a9..cbc5fd53e 100644 --- a/back/models/machine-worker.js +++ b/back/models/machine-worker.js @@ -1,3 +1,3 @@ module.exports = Self => { - require('../methods/machine-worker/updateMachine')(Self); + require('../methods/machine-worker/updateInTime')(Self); }; diff --git a/db/changes/234801/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql similarity index 64% rename from db/changes/234801/00-newWareHouse.sql rename to db/changes/235001/00-newWareHouse.sql index e55835563..955088866 100644 --- a/db/changes/234801/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -2,7 +2,4 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp VALUES ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'employee'), ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('MachineWorker','updateMachine','WRITE','ALLOW','ROLE','employee'); - -INSERT INTO `vn`.`machineWorkerConfig` (id, maxHours) - VALUES (1, 12) \ No newline at end of file + ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 39007fcc1..e8ae2f9a3 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3671,3 +3671,6 @@ CALL itemShelvingSale_reserveByCollection(10101010); UPDATE vn.collection SET workerFk=9 WHERE id=10101010; + +INSERT INTO `vn`.`machineWorkerConfig` (id, maxHours) + VALUES (1, 12) \ No newline at end of file From 877c6792733033ff568b98bc3c253dddfba6fce7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 29 Nov 2023 13:22:44 +0100 Subject: [PATCH 005/150] refs #6276 getVersion --- .../mobile-app-version-control/getVersion.js | 45 +++++++++++++++++++ back/models/mobile-app-version-control.js | 3 ++ back/models/mobile-app-version-control.json | 39 ++++++++++++++++ db/changes/235001/00-newWareHouse.sql | 3 +- modules/worker/back/model-config.json | 3 ++ .../worker/back/models/worker-app-tester.json | 22 +++++++++ 6 files changed, 114 insertions(+), 1 deletion(-) create mode 100644 back/methods/mobile-app-version-control/getVersion.js create mode 100644 back/models/mobile-app-version-control.js create mode 100644 back/models/mobile-app-version-control.json create mode 100644 modules/worker/back/models/worker-app-tester.json diff --git a/back/methods/mobile-app-version-control/getVersion.js b/back/methods/mobile-app-version-control/getVersion.js new file mode 100644 index 000000000..510fd6c4a --- /dev/null +++ b/back/methods/mobile-app-version-control/getVersion.js @@ -0,0 +1,45 @@ +module.exports = Self => { + Self.remoteMethodCtx('getVersion', { + description: 'gets app version data', + accessType: 'READ', + accepts: [{ + arg: 'app', + type: 'string', + required: true + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getVersion`, + verb: 'GET' + } + }); + + Self.getVersion = async(ctx, app) => { + const {models} = Self.app; + const userId = ctx.req.accessToken.userId; + + const workerFk = await models.WorkerAppTester.findOne({ + where: { + workerFk: userId + } + }); + let fields = ['id', 'appName']; + + if (workerFk) + fields = [...fields, ...['isVersionBetaCritical', 'versionBeta', 'urlBeta']]; + else + fields = [...fields, ...['isVersionCritical', 'version', 'urlProduction']]; + + const filter = { + where: { + appName: app + }, + fields, + }; + + return await Self.findOne(filter); + }; +}; diff --git a/back/models/mobile-app-version-control.js b/back/models/mobile-app-version-control.js new file mode 100644 index 000000000..ee8fa2ab6 --- /dev/null +++ b/back/models/mobile-app-version-control.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/mobile-app-version-control/getVersion')(Self); +}; diff --git a/back/models/mobile-app-version-control.json b/back/models/mobile-app-version-control.json new file mode 100644 index 000000000..819ad33f5 --- /dev/null +++ b/back/models/mobile-app-version-control.json @@ -0,0 +1,39 @@ +{ + "name": "MobileAppVersionControl", + "base": "VnModel", + "options": { + "mysql": { + "table": "vn.mobileAppVersionControl" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "appName": { + "type": "string" + }, + + "version": { + "type": "string" + }, + + "isVersionCritical": { + "type": "boolean" + }, + + "urlProduction": { + "type": "string" + }, + "urlBeta": { + "type": "string" + }, + "versionBeta": { + "type": "string" + }, + "isVersionBetaCritical": { + "type": "boolean" + } + } +} diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index 955088866..9111a8a04 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -2,4 +2,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp VALUES ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'employee'), ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file + ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'), + ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'); \ No newline at end of file diff --git a/modules/worker/back/model-config.json b/modules/worker/back/model-config.json index 8352eb070..650a8d0c2 100644 --- a/modules/worker/back/model-config.json +++ b/modules/worker/back/model-config.json @@ -53,6 +53,9 @@ "Time": { "dataSource": "vn" }, + "WorkerAppTester": { + "dataSource": "vn" + }, "WorkCenter": { "dataSource": "vn" }, diff --git a/modules/worker/back/models/worker-app-tester.json b/modules/worker/back/models/worker-app-tester.json new file mode 100644 index 000000000..7e9706dcb --- /dev/null +++ b/modules/worker/back/models/worker-app-tester.json @@ -0,0 +1,22 @@ +{ + "name": "WorkerAppTester", + "base": "VnModel", + "options": { + "mysql": { + "table": "vn.workerAppTester" + } + }, + "properties": { + "workerFk": { + "id": true, + "type": "number" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + } + } +} \ No newline at end of file From 27d223cbab099ff9bd73d97d1872401dd5cc1962 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 29 Nov 2023 16:25:15 +0100 Subject: [PATCH 006/150] refs #6276 machineWorker_add --- back/methods/machine-worker/add.js | 68 +++++++++++++++++++++ back/methods/machine-worker/updateInTime.js | 2 +- back/models/machine-worker.js | 1 + db/changes/235001/00-newWareHouse.sql | 1 + 4 files changed, 71 insertions(+), 1 deletion(-) create mode 100644 back/methods/machine-worker/add.js diff --git a/back/methods/machine-worker/add.js b/back/methods/machine-worker/add.js new file mode 100644 index 000000000..3da236cb8 --- /dev/null +++ b/back/methods/machine-worker/add.js @@ -0,0 +1,68 @@ +module.exports = Self => { + Self.remoteMethodCtx('add', { + description: 'Insert log if the worker has not logged anything in the last 12 hours', + accessType: 'READ', + accepts: [ + { + arg: 'plate', + type: 'string', + } + ], + http: { + path: `/add`, + verb: 'POST' + } + }); + + Self.add = async(ctx, plate, options) => { + const models = Self.app.models; + const userId = ctx.req.accessToken.userId; + + let tx; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const machine = await models.Machine.findOne({ + fields: ['id', 'plate'], + where: {plate} + }, myOptions); + + if (!machine) throw new Error(`plate ${plate} does not exist`); + + const twelveHoursAgo = Date.vnNew(); + twelveHoursAgo.setHours(twelveHoursAgo.getHours() - 12); + + const isRegistered = await models.MachineWorker.findOne({ + where: { + and: [ + {machineFk: machine.id}, + {workerFk: userId}, + {outTime: {gte: twelveHoursAgo}} + ] + } + }, myOptions); + console.log(isRegistered); + if (!isRegistered) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); + else { + await models.MachineWorker.updateAll( + {or: [{workerFk: userId}, {machineFk: machine.id}]}, + {outTime: Date.vnNew()}, + myOptions + ); + } + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index b8e2becf2..917733686 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -1,6 +1,6 @@ module.exports = Self => { Self.remoteMethodCtx('updateInTime', { - description: '', + description: 'Updates the corresponding registry if the worker has been registered in the last few hours', accessType: 'WRITE', accepts: [ { diff --git a/back/models/machine-worker.js b/back/models/machine-worker.js index cbc5fd53e..b44cb1fb6 100644 --- a/back/models/machine-worker.js +++ b/back/models/machine-worker.js @@ -1,3 +1,4 @@ module.exports = Self => { require('../methods/machine-worker/updateInTime')(Self); + require('../methods/machine-worker/add')(Self); }; diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index 9111a8a04..05003d8ec 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -3,4 +3,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'employee'), ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'), ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'), + ('MachineWorker','add','READ','ALLOW','ROLE','employee'), ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'); \ No newline at end of file From 375cb1acc0759e560a88c0ae464bca3e92c61818 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 29 Nov 2023 16:28:14 +0100 Subject: [PATCH 007/150] refs #6276 console removed --- back/methods/machine-worker/add.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/machine-worker/add.js b/back/methods/machine-worker/add.js index 3da236cb8..65eb5d297 100644 --- a/back/methods/machine-worker/add.js +++ b/back/methods/machine-worker/add.js @@ -49,7 +49,7 @@ module.exports = Self => { ] } }, myOptions); - console.log(isRegistered); + if (!isRegistered) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); else { await models.MachineWorker.updateAll( From 40236fdb7bac7b299e6118e51b12cc0a69fbf226 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 30 Nov 2023 13:23:10 +0100 Subject: [PATCH 008/150] refs #6276 itemShelvingMake_multi --- .../back/methods/item-shelving/makeMulti.js | 74 +++++++++++++++++++ modules/item/back/models/item-shelving.js | 1 + modules/item/back/models/item-shelving.json | 2 +- 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 modules/item/back/methods/item-shelving/makeMulti.js diff --git a/modules/item/back/methods/item-shelving/makeMulti.js b/modules/item/back/methods/item-shelving/makeMulti.js new file mode 100644 index 000000000..d4b451760 --- /dev/null +++ b/modules/item/back/methods/item-shelving/makeMulti.js @@ -0,0 +1,74 @@ +module.exports = Self => { + Self.remoteMethod('makeMulti', { + description: 'Add a record or update it if it already exists.', + accessType: 'WRITE', + accepts: [{ + arg: 'shelvingFk', + type: 'number', + required: true, + }, + { + arg: 'items', + type: ['number'], + required: true, + description: 'array of item foreign keys' + }, + { + arg: 'warehouseFk', + type: 'number', + required: true + }], + + http: { + path: `/makeMulti`, + verb: 'POST' + } + }); + + Self.makeMulti = async(shelvingFk, items, warehouseFk, options) => { + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + const discardItems = []; + + try { + for (let item of items) { + if (!discardItems.includes(item)) { + let quantity = items.reduce((acc, cur) => { + return acc + (cur === item ? 1 : 0); + }, 0); + discardItems.push(item); + + let [result] = await Self.rawSql('SELECT vn.itemPacking(?, ?)', [item, warehouseFk]); + let packing; + + if (result) packing = Object.values(result)[0]; + if (!packing) packing = 1; + + quantity = quantity * packing; + + await Self.rawSql('CALL vn.itemShelving_add(?, ?, ?, NULL, NULL, ?, ?)', + [shelvingFk, + item, + quantity, + packing, + warehouseFk] + ); + } + } + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/item/back/models/item-shelving.js b/modules/item/back/models/item-shelving.js index 98ff18931..4684d49e2 100644 --- a/modules/item/back/models/item-shelving.js +++ b/modules/item/back/models/item-shelving.js @@ -1,4 +1,5 @@ module.exports = Self => { require('../methods/item-shelving/deleteItemShelvings')(Self); require('../methods/item-shelving/getInventory')(Self); + require('../methods/item-shelving/makeMulti')(Self); }; diff --git a/modules/item/back/models/item-shelving.json b/modules/item/back/models/item-shelving.json index bb1a141c4..61d05539e 100644 --- a/modules/item/back/models/item-shelving.json +++ b/modules/item/back/models/item-shelving.json @@ -1,6 +1,6 @@ { "name": "ItemShelving", - "base": "Loggable", + "base": "VnModel", "options": { "mysql": { "table": "itemShelving" From 3333c837029fa3c87713f26914049f416c85c7b5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 30 Nov 2023 16:25:13 +0100 Subject: [PATCH 009/150] refs #6276 WIP itemShelving_return --- .../item/back/methods/item-shelving/return.js | 77 +++++++++++++++++++ modules/item/back/models/item-shelving.js | 1 + modules/item/back/models/item-shelving.json | 5 +- 3 files changed, 81 insertions(+), 2 deletions(-) create mode 100644 modules/item/back/methods/item-shelving/return.js diff --git a/modules/item/back/methods/item-shelving/return.js b/modules/item/back/methods/item-shelving/return.js new file mode 100644 index 000000000..dc17719de --- /dev/null +++ b/modules/item/back/methods/item-shelving/return.js @@ -0,0 +1,77 @@ +module.exports = Self => { + Self.remoteMethod('return', { + description: 'Returns a list of items and possible alternative locations', + accessType: 'READ', + accepts: [{ + arg: 'shelvingFk', + type: 'string', + required: true, + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/return`, + verb: 'POST' + } + }); + + Self.return = async(shelvingFk, options) => { + const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const filterItemShelvings = { + fields: ['id', 'visible', 'itemFk', 'packing', 'grouping', 'isChecked', 'shelvingFk'], + where: {shelvingFk}, + include: [ + { + relation: 'item', + scope: { + fields: ['longName', 'name', 'size'] + } + }, + { + relation: 'shelving', + + scope: { + include: { + fields: ['id', 'name', 'code'], + relation: 'parking', + } + + } + }, + ] + }; + + let itemShelvings = await models.ItemShelving.find(filterItemShelvings, myOptions); + + let alternatives = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)', [shelvingFk]); + console.log(alternatives); + + if (itemShelvings) { + itemShelvings = itemShelvings.map(itemShelving => { + const item = itemShelving.item(); + const shelving = itemShelving.shelving(); + const parking = shelving ? shelving.parking() : null; + + return { + item: itemShelving.itemFk, + description: item ? item.longName || `${item.name} ${item.size}` : '', + visible: itemShelving.visible, + stickers: Math.ceil(itemShelving.visible / itemShelving.packing), + packing: itemShelving.packing, + grouping: itemShelving.grouping, + code: parking ? parking.code : '', + id: itemShelving.id, + priority: shelving ? shelving.priority : 0, + isChecked: itemShelving.isChecked + }; + }); + } + }; +}; diff --git a/modules/item/back/models/item-shelving.js b/modules/item/back/models/item-shelving.js index 4684d49e2..e610aabec 100644 --- a/modules/item/back/models/item-shelving.js +++ b/modules/item/back/models/item-shelving.js @@ -2,4 +2,5 @@ module.exports = Self => { require('../methods/item-shelving/deleteItemShelvings')(Self); require('../methods/item-shelving/getInventory')(Self); require('../methods/item-shelving/makeMulti')(Self); + require('../methods/item-shelving/return')(Self); }; diff --git a/modules/item/back/models/item-shelving.json b/modules/item/back/models/item-shelving.json index 61d05539e..bf9e5e4b1 100644 --- a/modules/item/back/models/item-shelving.json +++ b/modules/item/back/models/item-shelving.json @@ -51,7 +51,8 @@ "shelving": { "type": "belongsTo", "model": "Shelving", - "foreignKey": "shelvingFk" - } + "foreignKey": "shelvingFk", + "primaryKey": "code" + } } } From d5f09c2f75dc674f34d0df45aca8f591735e68c5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Dec 2023 09:44:49 +0100 Subject: [PATCH 010/150] refs #6276 saleTrackingDel --- db/changes/235001/00-newWareHouse.sql | 3 +- .../back/methods/sale-tracking/delete.js | 30 +++++++++++-------- modules/ticket/front/sale-tracking/index.js | 2 +- 3 files changed, 20 insertions(+), 15 deletions(-) diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index 05003d8ec..c6f595400 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -4,4 +4,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'), ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'), ('MachineWorker','add','READ','ALLOW','ROLE','employee'), - ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'); \ No newline at end of file + ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'), + ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file diff --git a/modules/ticket/back/methods/sale-tracking/delete.js b/modules/ticket/back/methods/sale-tracking/delete.js index 0b977e5d4..5efd267dc 100644 --- a/modules/ticket/back/methods/sale-tracking/delete.js +++ b/modules/ticket/back/methods/sale-tracking/delete.js @@ -10,12 +10,12 @@ module.exports = Self => { description: 'The sale id' }, { - arg: 'stateCode', - type: 'string' - } + arg: 'stateCodes', + type: ['string'] + }, ], returns: { - type: ['object'], + type: 'boolean', root: true }, http: { @@ -24,7 +24,7 @@ module.exports = Self => { } }); - Self.delete = async(saleFk, stateCode, options) => { + Self.delete = async(saleFk, stateCodes, options) => { const models = Self.app.models; const myOptions = {}; let tx; @@ -38,20 +38,24 @@ module.exports = Self => { } try { - if (stateCode === 'PREPARED') { - const itemShelvingSales = await models.ItemShelvingSale.find({where: {saleFk: saleFk}}, myOptions); - for (let itemShelvingSale of itemShelvingSales) - await itemShelvingSale.destroy(myOptions); - } + const itemShelvingSales = await models.ItemShelvingSale.find({where: {saleFk: saleFk}}, myOptions); - const state = await models.State.findOne({ - where: {code: stateCode} + for (let itemShelvingSale of itemShelvingSales) + await itemShelvingSale.destroy(myOptions); + + const states = await models.State.find({ + fields: ['id'], + where: { + code: {inq: stateCodes} + } }, myOptions); + const stateIds = states.map(state => state.id); + const filter = { where: { saleFk: saleFk, - stateFk: state.id + stateFk: {inq: stateIds} } }; const saleTrackings = await models.SaleTracking.find(filter, myOptions); diff --git a/modules/ticket/front/sale-tracking/index.js b/modules/ticket/front/sale-tracking/index.js index 6c0e7232e..095d581a1 100644 --- a/modules/ticket/front/sale-tracking/index.js +++ b/modules/ticket/front/sale-tracking/index.js @@ -100,7 +100,7 @@ class Controller extends Section { saleTrackingDel(sale, stateCode) { const params = { saleFk: sale.saleFk, - stateCode: stateCode + stateCodes: [stateCode] }; this.$http.post(`SaleTrackings/delete`, params).then(() => { this.vnApp.showSuccess(this.$t('Data saved!')); From f2ab44bb8f3e8bbdeeac2be8ed0deb422697ef2b Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Dec 2023 10:14:32 +0100 Subject: [PATCH 011/150] refs #6276 itemShelving_return --- .../item/back/methods/item-shelving/return.js | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/modules/item/back/methods/item-shelving/return.js b/modules/item/back/methods/item-shelving/return.js index dc17719de..6e0f80824 100644 --- a/modules/item/back/methods/item-shelving/return.js +++ b/modules/item/back/methods/item-shelving/return.js @@ -8,7 +8,7 @@ module.exports = Self => { required: true, }], returns: { - type: 'object', + type: ['object'], root: true }, http: { @@ -50,8 +50,7 @@ module.exports = Self => { let itemShelvings = await models.ItemShelving.find(filterItemShelvings, myOptions); - let alternatives = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)', [shelvingFk]); - console.log(alternatives); + const alternatives = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)', [shelvingFk]); if (itemShelvings) { itemShelvings = itemShelvings.map(itemShelving => { @@ -59,19 +58,23 @@ module.exports = Self => { const shelving = itemShelving.shelving(); const parking = shelving ? shelving.parking() : null; + const carros = alternatives.filter(el => el.item == itemShelving.itemFk); + return { + id: itemShelving.id, item: itemShelving.itemFk, - description: item ? item.longName || `${item.name} ${item.size}` : '', - visible: itemShelving.visible, + longName: item ? item.longName || `${item.name} ${item.size}` : '', + quantity: itemShelving.visible, stickers: Math.ceil(itemShelving.visible / itemShelving.packing), packing: itemShelving.packing, grouping: itemShelving.grouping, code: parking ? parking.code : '', - id: itemShelving.id, priority: shelving ? shelving.priority : 0, - isChecked: itemShelving.isChecked + isChecked: itemShelving.isChecked, + carros }; }); } + return itemShelvings; }; }; From d2769f4c2190ab55b22a1cf0e7dcf5d41a5d22df Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Dec 2023 11:38:30 +0100 Subject: [PATCH 012/150] refs #6276 return fixed --- modules/item/back/methods/item-shelving/return.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/back/methods/item-shelving/return.js b/modules/item/back/methods/item-shelving/return.js index 6e0f80824..346fe8bdf 100644 --- a/modules/item/back/methods/item-shelving/return.js +++ b/modules/item/back/methods/item-shelving/return.js @@ -13,7 +13,7 @@ module.exports = Self => { }, http: { path: `/return`, - verb: 'POST' + verb: 'GET' } }); From 7e57640758ebdc47403e98af56c69a8dfee960e5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Dec 2023 11:43:07 +0100 Subject: [PATCH 013/150] refs #6276 itemShelving_updateFromSale --- .../methods/item-shelving/updateFromSale.js | 51 +++++++++++++++++++ modules/item/back/models/item-shelving.js | 1 + 2 files changed, 52 insertions(+) create mode 100644 modules/item/back/methods/item-shelving/updateFromSale.js diff --git a/modules/item/back/methods/item-shelving/updateFromSale.js b/modules/item/back/methods/item-shelving/updateFromSale.js new file mode 100644 index 000000000..cd2012edb --- /dev/null +++ b/modules/item/back/methods/item-shelving/updateFromSale.js @@ -0,0 +1,51 @@ +module.exports = Self => { + Self.remoteMethod('updateFromSale', { + description: 'Returns a list of items and possible alternative locations', + accessType: 'WRITE', + accepts: [{ + arg: 'saleFk', + type: 'number', + required: true, + }], + http: { + path: `/updateFromSale`, + verb: 'POST' + } + }); + + Self.updateFromSale = async(saleFk, options) => { + const models = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const itemShelvingSale = await models.ItemShelvingSale.findOne({ + where: {saleFk} + }, myOptions); + + const itemShelving = await models.ItemShelving.findOne({ + where: { + id: itemShelvingSale.ItemShelvingFk + } + }); + const quantity = itemShelving.visible + itemShelvingSale.quantity; + + await itemShelving.updateAttributes( + {visible: quantity}, + myOptions + ); + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/item/back/models/item-shelving.js b/modules/item/back/models/item-shelving.js index e610aabec..4eb5374e8 100644 --- a/modules/item/back/models/item-shelving.js +++ b/modules/item/back/models/item-shelving.js @@ -3,4 +3,5 @@ module.exports = Self => { require('../methods/item-shelving/getInventory')(Self); require('../methods/item-shelving/makeMulti')(Self); require('../methods/item-shelving/return')(Self); + require('../methods/item-shelving/updateFromSale')(Self); }; From 660e77be5527dc01e4693fbdf97dd4d10af300a8 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Dec 2023 12:48:21 +0100 Subject: [PATCH 014/150] refs #6276 updateFromSale refactored --- .../item/back/methods/item-shelving/updateFromSale.js | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/modules/item/back/methods/item-shelving/updateFromSale.js b/modules/item/back/methods/item-shelving/updateFromSale.js index cd2012edb..b63b766c2 100644 --- a/modules/item/back/methods/item-shelving/updateFromSale.js +++ b/modules/item/back/methods/item-shelving/updateFromSale.js @@ -28,14 +28,11 @@ module.exports = Self => { try { const itemShelvingSale = await models.ItemShelvingSale.findOne({ - where: {saleFk} + where: {saleFk}, + include: {relation: 'itemShelving'} }, myOptions); - const itemShelving = await models.ItemShelving.findOne({ - where: { - id: itemShelvingSale.ItemShelvingFk - } - }); + const itemShelving = itemShelvingSale.itemShelving(); const quantity = itemShelving.visible + itemShelvingSale.quantity; await itemShelving.updateAttributes( From 4690dca4f955ceff7eb53ddf2e08e0d0d25622db Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Dec 2023 13:54:09 +0100 Subject: [PATCH 015/150] refs #6276 getItemPackingType --- .../methods/item-shelving/updateFromSale.js | 2 +- .../methods/operator/getItemPackingType.js | 28 +++++++++++++++++++ modules/worker/back/models/operator.js | 1 + modules/worker/back/models/operator.json | 6 ++++ 4 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 modules/worker/back/methods/operator/getItemPackingType.js diff --git a/modules/item/back/methods/item-shelving/updateFromSale.js b/modules/item/back/methods/item-shelving/updateFromSale.js index b63b766c2..2b9f49cae 100644 --- a/modules/item/back/methods/item-shelving/updateFromSale.js +++ b/modules/item/back/methods/item-shelving/updateFromSale.js @@ -1,6 +1,6 @@ module.exports = Self => { Self.remoteMethod('updateFromSale', { - description: 'Returns a list of items and possible alternative locations', + description: 'Update the visible items', accessType: 'WRITE', accepts: [{ arg: 'saleFk', diff --git a/modules/worker/back/methods/operator/getItemPackingType.js b/modules/worker/back/methods/operator/getItemPackingType.js new file mode 100644 index 000000000..6e2125b5b --- /dev/null +++ b/modules/worker/back/methods/operator/getItemPackingType.js @@ -0,0 +1,28 @@ +module.exports = Self => { + Self.remoteMethodCtx('getItemPackingType', { + description: 'Retrieve the operator items', + accessType: 'READ', + returns: { + type: 'string', + }, + http: { + path: `/getItemPackingType`, + verb: 'GET' + }, + }); + + Self.getItemPackingType = async ctx => { + const userId = 9 ?? ctx.req.accessToken.userId; + + const result = await Self.findOne({ + where: { + workerFk: userId + }, + include: { + relation: 'itemPackingType', + } + }); + const itemPackingType = result.itemPackingType(); + return itemPackingType?.description; + }; +}; diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index 5e8870130..b9ea481a7 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -2,6 +2,7 @@ module.exports = Self => { require('../methods/operator/add')(Self); require('../methods/operator/getPrinter')(Self); require('../methods/operator/getAvailablePrinters')(Self); + require('../methods/operator/getItemPackingType')(Self); Self.observe('after save', async function(ctx) { const instance = ctx.data || ctx.instance; diff --git a/modules/worker/back/models/operator.json b/modules/worker/back/models/operator.json index 6da3945fc..a2f3ee01c 100644 --- a/modules/worker/back/models/operator.json +++ b/modules/worker/back/models/operator.json @@ -43,6 +43,12 @@ "type": "belongsTo", "model": "Printer", "foreignKey": "labelerFk" + }, + "itemPackingType": { + "type": "belongsTo", + "model": "ItemPackingType", + "foreignKey": "itemPackingTypeFk", + "primaryKey": "code" } } } From 1dfdd94584de25519d91324f09b34f93ab1fad61 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Dec 2023 13:56:43 +0100 Subject: [PATCH 016/150] refs #6276 fix getItemPackingType --- modules/worker/back/methods/operator/getItemPackingType.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/modules/worker/back/methods/operator/getItemPackingType.js b/modules/worker/back/methods/operator/getItemPackingType.js index 6e2125b5b..d28cd95fe 100644 --- a/modules/worker/back/methods/operator/getItemPackingType.js +++ b/modules/worker/back/methods/operator/getItemPackingType.js @@ -3,7 +3,7 @@ module.exports = Self => { description: 'Retrieve the operator items', accessType: 'READ', returns: { - type: 'string', + type: 'object', }, http: { path: `/getItemPackingType`, @@ -23,6 +23,9 @@ module.exports = Self => { } }); const itemPackingType = result.itemPackingType(); - return itemPackingType?.description; + + return { + description: itemPackingType?.description + }; }; }; From 8acd03f1159b70fdde9fd11c99d4b06dc6ca2a20 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 11 Dec 2023 13:01:34 +0100 Subject: [PATCH 017/150] refs #6276 saleTrackingReplace --- db/changes/235001/00-newWareHouse.sql | 3 +- .../methods/sale-tracking/updateTracking.js | 100 ++++++++++++++++++ modules/ticket/back/model-config.json | 3 + modules/ticket/back/models/sale-buy.json | 33 ++++++ modules/ticket/back/models/sale-tracking.js | 1 + modules/ticket/back/models/sale-tracking.json | 3 + 6 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 modules/ticket/back/methods/sale-tracking/updateTracking.js create mode 100644 modules/ticket/back/models/sale-buy.json diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index c6f595400..f563ce40c 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -5,4 +5,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'), ('MachineWorker','add','READ','ALLOW','ROLE','employee'), ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'), - ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file + ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'), + ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file diff --git a/modules/ticket/back/methods/sale-tracking/updateTracking.js b/modules/ticket/back/methods/sale-tracking/updateTracking.js new file mode 100644 index 000000000..1f499022e --- /dev/null +++ b/modules/ticket/back/methods/sale-tracking/updateTracking.js @@ -0,0 +1,100 @@ +module.exports = Self => { + Self.remoteMethodCtx('updateTracking', { + description: 'Modify a saleTracking record and, if applicable, add a corresponding record in saleBuy.', + accessType: 'WRITE', + accepts: [ + { + arg: 'saleFk', + type: 'number', + required: true + }, + { + arg: 'originalQuantity', + type: 'number', + required: true + }, + { + arg: 'code', + type: 'string', + required: true + }, + { + arg: 'isChecked', + type: 'number', + required: true + }, + { + arg: 'buyFk', + type: 'number', + required: true + }, + { + arg: 'isScanned', + type: 'number', + }, + ], + http: { + path: `/updateTracking`, + verb: 'POST' + } + }); + + Self.updateTracking = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned, options) => { + const userId = ctx.req.accessToken.userId; + const models = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const state = await models.State.findOne({ + where: {code}, + }, myOptions); + + const attributes = { + saleFk, + isChecked, + originalQuantity, + workerFk: userId, + stateFk: state.id, + isScanned, + }; + + const saleTracking = await models.SaleTracking.findOne({ + where: attributes, + }, myOptions); + + if (!saleTracking) + await models.SaleTracking.create(attributes, myOptions); + + else + await saleTracking.updateAttributes(attributes, myOptions); + + let isBuy; + if (buyFk) { + isBuy = await models.Buy.findOne({ + where: { + id: buyFk, + itemOriginalFk: { + neq: null + } + } + }); + } + if (isBuy) + await models.SaleBuy.create({saleFk, buyFk}, myOptions); + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index 76a289cc3..db90b55e1 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -65,6 +65,9 @@ "SaleTracking": { "dataSource": "vn" }, + "SaleBuy": { + "dataSource": "vn" + }, "State": { "dataSource": "vn" }, diff --git a/modules/ticket/back/models/sale-buy.json b/modules/ticket/back/models/sale-buy.json new file mode 100644 index 000000000..5279e6787 --- /dev/null +++ b/modules/ticket/back/models/sale-buy.json @@ -0,0 +1,33 @@ +{ + "name": "SaleBuy", + "base": "VnModel", + "options": { + "mysql": { + "table": "saleBuy" + } + }, + "properties": { + "saleFk": { + "id": true, + "type": "number", + "forceId": false + }, + "buyFk": { + "type": "number" + }, + "created": { + "type": "date" + }, + "isChecked": { + "type": "number" + } + }, + "relations": { + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk" + } + } +} + \ No newline at end of file diff --git a/modules/ticket/back/models/sale-tracking.js b/modules/ticket/back/models/sale-tracking.js index 54a2b5a1a..4b513a716 100644 --- a/modules/ticket/back/models/sale-tracking.js +++ b/modules/ticket/back/models/sale-tracking.js @@ -3,4 +3,5 @@ module.exports = Self => { require('../methods/sale-tracking/listSaleTracking')(Self); require('../methods/sale-tracking/new')(Self); require('../methods/sale-tracking/delete')(Self); + require('../methods/sale-tracking/updateTracking')(Self); }; diff --git a/modules/ticket/back/models/sale-tracking.json b/modules/ticket/back/models/sale-tracking.json index 4a103ea15..5e512f844 100644 --- a/modules/ticket/back/models/sale-tracking.json +++ b/modules/ticket/back/models/sale-tracking.json @@ -26,6 +26,9 @@ }, "originalQuantity": { "type": "number" + }, + "isScanned": { + "type": "number" } }, "relations": { From 3109f7722e867b1f8c9101abe287ba31929aff57 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 12 Dec 2023 13:24:18 +0100 Subject: [PATCH 018/150] refs #6276 saleTracking_mark --- db/changes/235001/00-newWareHouse.sql | 3 +- loopback/locale/en.json | 3 +- loopback/locale/es.json | 3 +- .../ticket/back/methods/sale-tracking/mark.js | 102 ++++++++++++++++++ modules/ticket/back/models/sale-tracking.js | 1 + 5 files changed, 109 insertions(+), 3 deletions(-) create mode 100644 modules/ticket/back/methods/sale-tracking/mark.js diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index f563ce40c..13d5c87ad 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -6,4 +6,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('MachineWorker','add','READ','ALLOW','ROLE','employee'), ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'), ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'), - ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file + ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'), + ('SaleTracking','mark','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 7d5b5ed47..8ccb7a245 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -200,5 +200,6 @@ "Try again": "Try again", "keepPrice": "keepPrice", "Cannot past travels with entries": "Cannot past travels with entries", - "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}" + "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}", + "The notification subscription of this worker cant be modified": "The notification subscription of this worker cant be modified" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 01384efb4..ea8f99805 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -329,5 +329,6 @@ "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", "Cannot past travels with entries": "No se pueden pasar envíos con entradas", - "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}" + "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", + "The line could not be marked": "The line could not be marked" } \ No newline at end of file diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/mark.js new file mode 100644 index 000000000..f2cb96099 --- /dev/null +++ b/modules/ticket/back/methods/sale-tracking/mark.js @@ -0,0 +1,102 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('mark', { + description: 'Insert an itemShelvingSale and Modify a saleTracking record', + accessType: 'WRITE', + accepts: [ + { + arg: 'saleFk', + type: 'number', + required: true + }, + { + arg: 'originalQuantity', + type: 'number', + required: true + }, + { + arg: 'code', + type: 'string', + required: true + }, + { + arg: 'isChecked', + type: 'number', + required: true + }, + { + arg: 'buyFk', + type: 'number', + required: true + }, + { + arg: 'isScanned', + type: 'number', + }, + { + arg: 'quantity', + type: 'number', + required: true + }, + { + arg: 'itemShelvingFk', + type: 'number', + required: true + } + ], + http: { + path: `/mark`, + verb: 'POST' + } + }); + + Self.mark = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned, quantity, itemShelvingFk, options) => { + const userId = ctx.req.accessToken.userId; + const models = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + await models.ItemShelvingSale.create({ + itemShelvingFk, + saleFk, + quantity, + userFk: userId + }, myOptions); + + const itemShelving = await models.ItemShelving.findOne({ + where: { + id: itemShelvingFk + } + }, myOptions); + + if (itemShelving.visible) { + await itemShelving.updateAttributes({ + visible: itemShelving.visible - quantity} + , myOptions); + } + + await Self.updateAll( + {saleFk}, + {isChecked: 1}, + myOptions + ); + + await Self.updateTracking(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned, myOptions); + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw new UserError('The line could not be marked'); + } + }; +}; diff --git a/modules/ticket/back/models/sale-tracking.js b/modules/ticket/back/models/sale-tracking.js index 4b513a716..f284ec185 100644 --- a/modules/ticket/back/models/sale-tracking.js +++ b/modules/ticket/back/models/sale-tracking.js @@ -4,4 +4,5 @@ module.exports = Self => { require('../methods/sale-tracking/new')(Self); require('../methods/sale-tracking/delete')(Self); require('../methods/sale-tracking/updateTracking')(Self); + require('../methods/sale-tracking/mark')(Self); }; From f5ee3aff7ad7660c276de50df7fd20cb9d187702 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 12 Dec 2023 13:43:15 +0100 Subject: [PATCH 019/150] refs #6276 remove checking visible --- modules/ticket/back/methods/sale-tracking/mark.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/mark.js index f2cb96099..da637a7db 100644 --- a/modules/ticket/back/methods/sale-tracking/mark.js +++ b/modules/ticket/back/methods/sale-tracking/mark.js @@ -79,11 +79,9 @@ module.exports = Self => { } }, myOptions); - if (itemShelving.visible) { - await itemShelving.updateAttributes({ - visible: itemShelving.visible - quantity} - , myOptions); - } + await itemShelving.updateAttributes({ + visible: itemShelving.visible - quantity} + , myOptions); await Self.updateAll( {saleFk}, From 7b81630b8525be8f587085f12a45af96642a5c9c Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 12 Dec 2023 14:56:58 +0100 Subject: [PATCH 020/150] refs #6276 shelvingLog_add --- .../shelving/back/methods/shelving/addLog.js | 55 +++++++++++++++++++ modules/shelving/back/models/shelving.js | 1 + 2 files changed, 56 insertions(+) create mode 100644 modules/shelving/back/methods/shelving/addLog.js diff --git a/modules/shelving/back/methods/shelving/addLog.js b/modules/shelving/back/methods/shelving/addLog.js new file mode 100644 index 000000000..13f9075f1 --- /dev/null +++ b/modules/shelving/back/methods/shelving/addLog.js @@ -0,0 +1,55 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('addLog', { + description: 'Add a new log', + accessType: 'WRITE', + accepts: { + arg: 'code', + type: 'string', + required: true, + }, + http: { + path: '/addLog', + verb: 'POST' + } + }); + Self.addLog = async(ctx, code, options) => { + const userId = ctx.req.accessToken.userId; + const models = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const shelving = await Self.findOne({ + where: { + code + } + }, myOptions); + + if (!shelving) throw new UserError('Shelving not valid'); + + await models.ShelvingLog.create({ + changedModel: 'Shelving', + originFk: shelving.id, + changedModelId: shelving.id, + action: 'select', + userFk: userId + + }, myOptions); + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/shelving/back/models/shelving.js b/modules/shelving/back/models/shelving.js index 3e27f5863..bf611d2ba 100644 --- a/modules/shelving/back/models/shelving.js +++ b/modules/shelving/back/models/shelving.js @@ -1,3 +1,4 @@ module.exports = Self => { require('../methods/shelving/getSummary')(Self); + require('../methods/shelving/addLog')(Self); }; From 9e6fac9addd04b59a446178f518e4bcf48afa69a Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 12 Dec 2023 16:00:43 +0100 Subject: [PATCH 021/150] refs #6276 change to boolean --- modules/ticket/back/methods/sale-tracking/mark.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/mark.js index da637a7db..a5b8ece52 100644 --- a/modules/ticket/back/methods/sale-tracking/mark.js +++ b/modules/ticket/back/methods/sale-tracking/mark.js @@ -22,7 +22,7 @@ module.exports = Self => { }, { arg: 'isChecked', - type: 'number', + type: 'boolean', required: true }, { @@ -85,7 +85,7 @@ module.exports = Self => { await Self.updateAll( {saleFk}, - {isChecked: 1}, + {isChecked: true}, myOptions ); From 64c10f3b8e5d8b6f2d20ecd2132d25cf0f4a2609 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 13 Dec 2023 08:52:43 +0100 Subject: [PATCH 022/150] refs #6276 sectorCollection_getSales --- .../back/methods/item-shelving/getSale.js | 58 +++++++++++++++++++ modules/item/back/models/item-shelving.js | 1 + 2 files changed, 59 insertions(+) create mode 100644 modules/item/back/methods/item-shelving/getSale.js diff --git a/modules/item/back/methods/item-shelving/getSale.js b/modules/item/back/methods/item-shelving/getSale.js new file mode 100644 index 000000000..084f7351f --- /dev/null +++ b/modules/item/back/methods/item-shelving/getSale.js @@ -0,0 +1,58 @@ +module.exports = Self => { + Self.remoteMethod('getSale', { + description: 'Update the visible items', + accessType: 'WRITE', + accepts: [ + { + arg: 'sectorCollectionFk', + type: 'number', + required: true, + }, + { + arg: 'sectorFk', + type: 'number', + required: true + } + ], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getSale`, + verb: 'GET' + }, + }); + + Self.getSale = async(sectorCollectionFk, sectorFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') Object.assign(myOptions, options); + + const sales = await Self.rawSql('CALL vn.sectorCollection_getSale(?)', [sectorCollectionFk]); + + const itemShelvings = []; + for (let sale of sales) { + const [carros] = await Self.rawSql( + 'CALL vn.itemPlacementSupplyStockGetTargetList(?, ?)', + [sale.itemFk, sectorFk] + ); + + itemShelvings.push({ + id: sale.ticketFk, + itemFk: sale.itemFk, + longName: sale.longName, + packingType: sale.itemPackingTypeFk, + subName: sale.subName, + quantity: {saldo: sale.quantity}, + trabajador: sale.workerCode, + idMovimiento: sale.saleFk, + salesPersonFk: sale.salesPersonFk, + picked: sale.pickedQuantity, + carros + }); + } + + return itemShelvings; + }; +}; diff --git a/modules/item/back/models/item-shelving.js b/modules/item/back/models/item-shelving.js index 4eb5374e8..e349b9c34 100644 --- a/modules/item/back/models/item-shelving.js +++ b/modules/item/back/models/item-shelving.js @@ -4,4 +4,5 @@ module.exports = Self => { require('../methods/item-shelving/makeMulti')(Self); require('../methods/item-shelving/return')(Self); require('../methods/item-shelving/updateFromSale')(Self); + require('../methods/item-shelving/getSale')(Self); }; From a4c3d78e31d1581c3a28c3f9973c9b282957bdf9 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 13 Dec 2023 09:45:01 +0100 Subject: [PATCH 023/150] refs #6276 drop fixtures & fix getSale --- db/dump/fixtures.sql | 673 +----------------- .../back/methods/item-shelving/getSale.js | 2 +- 2 files changed, 2 insertions(+), 673 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index d3bb4257f..dd1d0951e 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3008,675 +3008,4 @@ INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) VALUES (1, 'Error in VAT calculation'), (2, 'Error in sales details'), - (3, 'Error in customer data'); - - -/* - Se necesitan, para hacer un simulacro de pedido, lo siguiente: - - - Warehouse 999 - - Sectores - - Normal 9991 - - Previa 9992 - - Altillo 9993 - - Parkings - - Normal A-01-1, A-02-2, B-03-3, B-04-4, C-05-5 - - Previa P-01-1, P-02-2, P-03-3 - - Altillo M-01-1, M-02-2, M-03-3 - - Shelvings - - Normal NAA, NBB, NCC, NDD, NEE - - Previa PAA, PBB, PCC - - Altillo MAA, MBB, MCC - - Items - * Normal - * Previa: - - Ticket - - Sales - -*/ - -INSERT IGNORE INTO intrastat - SET id = 44219999, - description = 'Manufacturas de madera', - taxClassFk = 1, - taxCodeFk = 1; - -INSERT IGNORE INTO warehouse - SET id = 999, - name = 'TestingWarehouse', - hasAvailable = TRUE, - isForTicket = TRUE, - isInventory = TRUE, - hasUbications = TRUE, - hasProduction = TRUE; - -INSERT IGNORE INTO sector - SET id = 9991, - description = 'NormalSector', - warehouseFk = 999, - isPreviousPreparedByPacking = FALSE, - code = 'NS', - isPreviousPrepared = FALSE, - isPackagingArea = FALSE, - sonFk = NULL, - isMain = TRUE, - itemPackingTypeFk = NULL; - -INSERT IGNORE INTO sector - SET id = 9992, - description = 'PreviousSector', - warehouseFk = 999, - isPreviousPreparedByPacking = FALSE, - code = 'PS', - isPreviousPrepared = TRUE, - isPackagingArea = FALSE, - sonFk = NULL, - isMain = TRUE, - itemPackingTypeFk = NULL; - -INSERT IGNORE INTO sector - SET id = 9993, - description = 'MezaninneSector', - warehouseFk = 999, - isPreviousPreparedByPacking = TRUE, - code = 'MS', - isPreviousPrepared = FALSE, - isPackagingArea = FALSE, - sonFk = 9991, - isMain = TRUE, - itemPackingTypeFk = NULL; - -REPLACE parking SET id = 9991011, sectorFk = 9991, code = 'A-01-1', pickingOrder = 1; -REPLACE parking SET id = 9991012, sectorFk = 9991, code = 'A-02-2', pickingOrder = 2; -REPLACE parking SET id = 9991013, sectorFk = 9991, code = 'A-03-3', pickingOrder = 3; -REPLACE parking SET id = 9991014, sectorFk = 9991, code = 'A-04-4', pickingOrder = 4; -REPLACE parking SET id = 9991015, sectorFk = 9991, code = 'A-05-5', pickingOrder = 5; - -REPLACE parking SET id = 9992011, sectorFk = 9992, code = 'P-01-1', pickingOrder = 6; -REPLACE parking SET id = 9992012, sectorFk = 9992, code = 'P-02-2', pickingOrder = 7; -REPLACE parking SET id = 9992013, sectorFk = 9992, code = 'P-03-3', pickingOrder = 8; - -REPLACE parking SET id = 9993011, sectorFk = 9993, code = 'M-01-1', pickingOrder = 9; -REPLACE parking SET id = 9993012, sectorFk = 9993, code = 'M-02-2', pickingOrder = 10; -REPLACE parking SET id = 9993013, sectorFk = 9993, code = 'M-03-3', pickingOrder = 11; - -REPLACE shelving SET code = 'NAA', parkingFk = 9991011, priority = 1; -REPLACE shelving SET code = 'NBB', parkingFk = 9991012, priority = 1; -REPLACE shelving SET code = 'NCC', parkingFk = 9991013, priority = 1; -REPLACE shelving SET code = 'NDD', parkingFk = 9991014, priority = 1; -REPLACE shelving SET code = 'NEE', parkingFk = 9991015, priority = 1; - -REPLACE shelving SET code = 'PAA', parkingFk = 9992011, priority = 1; -REPLACE shelving SET code = 'PBB', parkingFk = 9992012, priority = 1; -REPLACE shelving SET code = 'PCC', parkingFk = 9992013, priority = 1; - -REPLACE shelving SET code = 'MAA', parkingFk = 9993011, priority = 1; -REPLACE shelving SET code = 'MBB', parkingFk = 9993012, priority = 1; -REPLACE shelving SET code = 'MCC', parkingFk = 9993013, priority = 1; - -INSERT IGNORE INTO itemType - SET id = 999, - code = 'WOO', - name = 'Wood Objects', - categoryFk = 3, - workerFk = 103, - isInventory = TRUE, - life = 10, - density = 250, - itemPackingTypeFk = NULL, - temperatureFk = 'warm'; - -INSERT IGNORE INTO travel - SET id = 99, - shipped = CURDATE(), - landed = CURDATE(), - warehouseInFk = 999, - warehouseOutFk = 1, - isReceived = TRUE, - agencyFk = 1; - -REPLACE entry - SET id = 999, - supplierFk = 791, - isConfirmed = TRUE, - dated = CURDATE(), - travelFk = 99, - companyFk = 442; - -REPLACE ticket - SET id = 999999, - clientFk = 2, - warehouseFk = 999, - shipped = CURDATE(), - nickname = 'Cliente', - addressFk = 1, - companyFk = 442, - agencyModeFk = 10, - landed = CURDATE(); - -REPLACE collection - SET id = 10101010, - workerFk = 103; - -INSERT IGNORE INTO ticketCollection - SET id = 10101010, - ticketFk = 999999, - collectionFk = 10101010; - -REPLACE item - SET id = 999991, - name = 'Palito para pinchos', - `size` = 25, - stems = NULL, - category = 'EXT', - typeFk = 999, - longName = 'Palito para pinchos', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 6, - intrastatFk = 44219999; - -REPLACE buy - SET id = 9999991, - entryFk = 999, - itemFk = 999991, - quantity = 8, - buyingValue = 0.61, - stickers = 1, - packing = 20, - `grouping` = 1, - groupingMode = 1, - packageFk = 94, - price1 = 1, - price2 = 1, - price3 = 1, - minPrice = 1, - weight = 50; - -REPLACE sale - SET id = 99991, - itemFk = 999991, - ticketFk = 999999, - concept = 'Palito para pinchos', - quantity = 3, - price = 1, - discount = 0; - -REPLACE item - SET id = 999992, - name = 'Madera verde', - `size` = 10, - stems = NULL, - category = 'EXT', - typeFk = 999, - longName = 'Madera verde', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 50, - intrastatFk = 44219999; - -REPLACE buy - SET id = 9999992, - entryFk = 999, - itemFk = 999992, - quantity = 40, - buyingValue = 0.62, - stickers = 1, - packing = 40, - `grouping` = 5, - groupingMode = 1, - packageFk = 94, - price1 = 1, - price2 = 1, - price3 = 1, - minPrice = 1, - weight = 25; - -REPLACE sale - SET id = 99992, - itemFk = 999992, - ticketFk = 999999, - concept = 'Madera Verde', - quantity = 10, - price = 1, - discount = 0; - -REPLACE item - SET id = 999993, - name = 'Madera Roja/Morada', - `size` = 12, - stems = 2, - category = 'EXT', - typeFk = 999, - longName = 'Madera Roja/Morada', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 35, - intrastatFk = 44219999; - -REPLACE buy - SET id = 9999993, - entryFk = 999, - itemFk = 999993, - quantity = 20, - buyingValue = 0.63, - stickers = 2, - packing = 10, - `grouping` = 5, - groupingMode = 1, - packageFk = 94, - price1 = 1, - price2 = 1, - price3 = 1, - minPrice = 1, - weight = 25; - -REPLACE itemShelving - SET id = 9931, - itemFk = 999993, - shelvingFk = 'NCC', - visible = 10, - `grouping` = 5, - packing = 10; - -REPLACE sale - SET id = 99993, - itemFk = 999993, - ticketFk = 999999, - concept = 'Madera Roja/Morada', - quantity = 15, - price = 1, - discount = 0; - -REPLACE item - SET id = 999994, - name = 'Madera Naranja', - `size` = 18, - stems = 1, - category = 'EXT', - typeFk = 999, - longName = 'Madera Naranja', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 160, - intrastatFk = 44219999; - -REPLACE buy - SET id = 9999994, - entryFk = 999, - itemFk = 999994, - quantity = 20, - buyingValue = 0.64, - stickers = 1, - packing = 20, - `grouping` = 4, - groupingMode = 1, - packageFk = 94, - price1 = 1, - price2 = 1, - price3 = 1, - minPrice = 1, - weight = 25; - -REPLACE sale - SET id = 99994, - itemFk = 999994, - ticketFk = 999999, - concept = 'Madera Naranja', - quantity = 4, - price = 1, - discount = 0; - -REPLACE item - SET id = 999995, - name = 'Madera Amarilla', - `size` = 11, - stems = 5, - category = 'EXT', - typeFk = 999, - longName = 'Madera Amarilla', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 78, - intrastatFk = 44219999; - -REPLACE buy - SET id = 9999995, - entryFk = 999, - itemFk = 999995, - quantity = 4, - buyingValue = 0.65, - stickers = 1, - packing = 20, - `grouping` = 1, - groupingMode = 1, - packageFk = 94, - price1 = 1, - price2 = 1, - price3 = 1, - minPrice = 1, - weight = 35; - -REPLACE sale - SET id = 99995, - itemFk = 999995, - ticketFk = 999999, - concept = 'Madera Amarilla', - quantity = 5, - price = 1, - discount = 0; - --- Palito naranja -REPLACE item - SET id = 999998, - name = 'Palito naranja', - `size` = 11, - stems = 1, - category = 'EXT', - typeFk = 999, - longName = 'Palito naranja', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 78, - intrastatFk = 44219999; - -REPLACE buy - SET id = 9999998, - entryFk = 999, - itemFk = 999998, - quantity = 80, - buyingValue = 0.65, - stickers = 1, - packing = 200, - `grouping` = 30, - groupingMode = 1, - packageFk = 94, - price1 = 1, - price2 = 1, - price3 = 1, - minPrice = 1, - weight = 35; - -REPLACE sale - SET id = 99998, - itemFk = 999998, - ticketFk = 999999, - concept = 'Palito naranja', - quantity = 60, - price = 1, - discount = 0; - --- Palito amarillo -REPLACE item - SET id = 999999, - name = 'Palito amarillo', - `size` = 11, - stems = 1, - category = 'EXT', - typeFk = 999, - longName = 'Palito amarillo', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 78, - intrastatFk = 44219999; - -REPLACE buy - SET id = 9999999, - entryFk = 999, - itemFk = 999999, - quantity = 70, - buyingValue = 0.65, - stickers = 1, - packing = 500, - `grouping` = 10, - groupingMode = 1, - packageFk = 94, - price1 = 1, - price2 = 1, - price3 = 1, - minPrice = 1, - weight = 35; - -REPLACE sale - SET id = 99999, - itemFk = 999999, - ticketFk = 999999, - concept = 'Palito amarillo', - quantity = 50, - price = 1, - discount = 0; - --- Palito azul -REPLACE item - SET id = 1000000, - name = 'Palito azul', - `size` = 10, - stems = 1, - category = 'EXT', - typeFk = 999, - longName = 'Palito azul', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 78, - intrastatFk = 44219999; - -REPLACE buy - SET id = 10000000, - entryFk = 999, - itemFk = 1000000, - quantity = 75, - buyingValue = 0.65, - stickers = 2, - packing = 300, - `grouping` = 50, - groupingMode = 1, - packageFk = 94, - price1 = 1, - price2 = 1, - price3 = 1, - minPrice = 1, - weight = 35; - -REPLACE sale - SET id = 100000, - itemFk = 1000000, - ticketFk = 999999, - concept = 'Palito azul', - quantity = 50, - price = 1, - discount = 0; - --- Palito rojo -REPLACE item - SET id = 1000001, - name = 'Palito rojo', - `size` = 10, - stems = NULL, - category = 'EXT', - typeFk = 999, - longName = 'Palito rojo', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 78, - intrastatFk = 44219999; - -REPLACE buy - SET id = 10000001, - entryFk = 999, - itemFk = 1000001, - quantity = 12, - buyingValue = 0.65, - stickers = 2, - packing = 50, - `grouping` = 5, - groupingMode = 1, - packageFk = 94, - price1 = 1, - price2 = 1, - price3 = 1, - minPrice = 1, - weight = 35; - - -REPLACE sale - SET id = 100001, - itemFk = 1000001, - ticketFk = 999999, - concept = 'Palito rojo', - quantity = 10, - price = 1, - discount = 0; - --- Previa -INSERT IGNORE INTO item - SET id = 999996, - name = 'Bolas de madera', - `size` = 2, - stems = 4, - category = 'EXT', - typeFk = 999, - longName = 'Bolas de madera', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 20, - intrastatFk = 44219999; - -REPLACE buy - SET id = 9999996, - entryFk = 999, - itemFk = 999996, - quantity = 5, - buyingValue = 3, - stickers = 1, - packing = 5, - `grouping` = 2, - groupingMode = 1, - packageFk = 94, - price1 = 7, - price2 = 7, - price3 = 7, - minPrice = 7, - weight = 80; - -REPLACE sale - SET id = 99996, - itemFk = 999996, - ticketFk = 999999, - concept = 'Bolas de madera', - quantity = 4, - price = 7, - discount = 0, - isPicked = TRUE; - -INSERT IGNORE INTO item - SET id = 999997, - name = 'Palitos de polo MIX', - `size` = 14, - stems = NULL, - category = 'EXT', - typeFk = 999, - longName = 'Palitos de polo MIX', - itemPackingTypeFk = NULL, - originFk = 1, - weightByPiece = 20, - intrastatFk = 44219999; - -REPLACE buy - SET id = 9999997, - entryFk = 999, - itemFk = 999997, - quantity = 100, - buyingValue = 3.2, - stickers = 1, - packing = 100, - `grouping` = 5, - groupingMode = 1, - packageFk = 94, - price1 = 7, - price2 = 7, - price3 = 7, - minPrice = 7, - weight = 80; - -REPLACE sale - SET id = 99997, - itemFk = 999997, - ticketFk = 999999, - concept = 'Palitos de polo MIX', - quantity = 5, - price = 7, - discount = 0; - --- Ubicación -DELETE ish.* - FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector s ON s.id = p.sectorFk - JOIN warehouse w ON w.id = s.warehouseFk - WHERE w.name = 'TestingWarehouse'; - -REPLACE vn.itemShelving -(id, itemFk, shelvingFk, visible, created, `grouping`, packing, packagingFk, userFk, isChecked) -VALUES - (9911, 999991, 'NAA', 8, '2023-09-20', 1, 20, NULL, 103, NULL), - (9912, 999998, 'NAA', 80, '2023-09-20', 10, 30, NULL, 103, NULL), - (9913, 1000001, 'NAA', 6, '2023-09-20', 3, 50, NULL, 103, NULL), - (9914, 1000000, 'NBB', 50, '2023-09-18', 25, 500, NULL, 103, NULL), - (9915, 999993, 'NBB', 25, '2023-09-18', NULL, 10, NULL, 103, NULL), - (9916, 999999, 'NBB', 30, '2023-09-18', 10, 500, NULL, 103, NULL), - (9917, 999993, 'NCC', 25, '2023-09-20', 5, 10, NULL, 103, NULL), - (9918, 999997, 'NCC', 10, '2023-09-20', NULL, 100, NULL, 103, NULL), - (9919, 999999, 'NCC', 40, '2023-09-20', 10, 500, NULL, 103, NULL), - (9920, 999995, 'NDD', 10, '2023-09-19', NULL, 20, NULL, 103, NULL), - (9921, 999994, 'NDD', 48, '2023-09-19', 4, 20, NULL, 103, NULL), - (9922, 1000001, 'NEE', 6, '2023-09-21', 3, 50, NULL, 103, NULL), - (9923, 999992, 'NEE', 50, '2023-09-21', NULL, 1, NULL, 103, NULL), - (9924, 1000000, 'NEE', 25, '2023-09-21', 25, 500, NULL, 103, NULL), - (9925, 999996, 'PAA', 5, '2023-09-27', 1, 5, NULL, 103, NULL), - (9926, 999997, 'PCC', 10, '2023-09-27', 5, 100, NULL, 103, NULL); - --- Previous for Bolas de madera -INSERT IGNORE INTO sectorCollection - SET id = 99, - userFk = 1, - sectorFk = 9992; - -INSERT IGNORE INTO saleGroup - SET id = 999, - userFk = 1, - parkingFk = 9992011, - sectorFk = 9992; - -INSERT IGNORE INTO sectorCollectionSaleGroup - SET id = 9999, - sectorCollectionFk = 99, - saleGroupFk = 999; - -REPLACE saleGroupDetail - SET id = 99991, - saleFk = 99996, - saleGroupFk = 999; - -REPLACE saleTracking - SET saleFk = 99996, - isChecked = TRUE, - workerFk = 103, - stateFk = 28; - -INSERT IGNORE INTO itemShelvingSale - SET id = 991, - itemShelvingFk = 9962, - saleFk = 99996, - quantity = 5, - userFk = 1; - - -CALL itemShelvingSale_reserveByCollection(10101010); - -UPDATE vn.collection - SET workerFk=9 - WHERE id=10101010; - -INSERT INTO `vn`.`machineWorkerConfig` (id, maxHours) - VALUES (1, 12) \ No newline at end of file + (3, 'Error in customer data'); \ No newline at end of file diff --git a/modules/item/back/methods/item-shelving/getSale.js b/modules/item/back/methods/item-shelving/getSale.js index 084f7351f..826ac03e1 100644 --- a/modules/item/back/methods/item-shelving/getSale.js +++ b/modules/item/back/methods/item-shelving/getSale.js @@ -29,7 +29,7 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const sales = await Self.rawSql('CALL vn.sectorCollection_getSale(?)', [sectorCollectionFk]); + const [sales] = await Self.rawSql('CALL vn.sectorCollection_getSale(?)', [sectorCollectionFk]); const itemShelvings = []; for (let sale of sales) { From 8d61473d4f7fe0e2471f1b9d1a5c075785dd64f8 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 13 Dec 2023 11:43:19 +0100 Subject: [PATCH 024/150] refs #6276 fixtures & itemBarcode_delete --- db/changes/235001/00-newWareHouse.sql | 3 +- db/dump/fixtures.sql | 655 +++++++++++++++++- .../item/back/methods/item-barcode/delete.js | 34 + modules/item/back/models/item-barcode.js | 1 + 4 files changed, 691 insertions(+), 2 deletions(-) create mode 100644 modules/item/back/methods/item-barcode/delete.js diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index 13d5c87ad..57e3398ff 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -7,4 +7,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'), ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'), ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'), - ('SaleTracking','mark','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file + ('SaleTracking','mark','WRITE','ALLOW','ROLE','employee'), + ('ItemBarcode','deleteByItemAndCode','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index dd1d0951e..40264e987 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3008,4 +3008,657 @@ INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) VALUES (1, 'Error in VAT calculation'), (2, 'Error in sales details'), - (3, 'Error in customer data'); \ No newline at end of file + (3, 'Error in customer data'); + + +-- NEW WAREHOUSE + +UPDATE vn.packaging + SET id='--' + WHERE id='pallet 100'; + +INSERT IGNORE INTO vn.intrastat + SET id = 44219999, + description = 'Manufacturas de madera', + taxClassFk = 1, + taxCodeFk = 1; + +INSERT IGNORE INTO vn.warehouse + SET id = 999, + name = 'TestingWarehouse', + hasAvailable = TRUE, + isForTicket = TRUE, + isInventory = TRUE, + hasUbications = TRUE, + hasProduction = TRUE; + +INSERT IGNORE INTO vn.sector + SET id = 9991, + description = 'NormalSector', + warehouseFk = 999, + isPreviousPreparedByPacking = FALSE, + code = 'NS', + isPreviousPrepared = FALSE, + isPackagingArea = FALSE, + sonFk = NULL, + isMain = TRUE, + itemPackingTypeFk = NULL; + +INSERT IGNORE INTO vn.sector + SET id = 9992, + description = 'PreviousSector', + warehouseFk = 999, + isPreviousPreparedByPacking = FALSE, + code = 'PS', + isPreviousPrepared = TRUE, + isPackagingArea = FALSE, + sonFk = NULL, + isMain = TRUE, + itemPackingTypeFk = NULL; + +INSERT IGNORE INTO vn.sector + SET id = 9993, + description = 'MezaninneSector', + warehouseFk = 999, + isPreviousPreparedByPacking = TRUE, + code = 'MS', + isPreviousPrepared = FALSE, + isPackagingArea = FALSE, + sonFk = 9991, + isMain = TRUE, + itemPackingTypeFk = NULL; + +REPLACE vn.parking SET id = 9991011, sectorFk = 9991, code = 'A-01-1', pickingOrder = 1; +REPLACE vn.parking SET id = 9991012, sectorFk = 9991, code = 'A-02-2', pickingOrder = 2; +REPLACE vn.parking SET id = 9991013, sectorFk = 9991, code = 'A-03-3', pickingOrder = 3; +REPLACE vn.parking SET id = 9991014, sectorFk = 9991, code = 'A-04-4', pickingOrder = 4; +REPLACE vn.parking SET id = 9991015, sectorFk = 9991, code = 'A-05-5', pickingOrder = 5; + +REPLACE vn.parking SET id = 9992011, sectorFk = 9992, code = 'P-01-1', pickingOrder = 6; +REPLACE vn.parking SET id = 9992012, sectorFk = 9992, code = 'P-02-2', pickingOrder = 7; +REPLACE vn.parking SET id = 9992013, sectorFk = 9992, code = 'P-03-3', pickingOrder = 8; + +REPLACE vn.parking SET id = 9993011, sectorFk = 9993, code = 'M-01-1', pickingOrder = 9; +REPLACE vn.parking SET id = 9993012, sectorFk = 9993, code = 'M-02-2', pickingOrder = 10; +REPLACE vn.parking SET id = 9993013, sectorFk = 9993, code = 'M-03-3', pickingOrder = 11; + +REPLACE vn.shelving SET code = 'NAA', parkingFk = 9991011, priority = 1; +REPLACE vn.shelving SET code = 'NBB', parkingFk = 9991012, priority = 1; +REPLACE vn.shelving SET code = 'NCC', parkingFk = 9991013, priority = 1; +REPLACE vn.shelving SET code = 'NDD', parkingFk = 9991014, priority = 1; +REPLACE vn.shelving SET code = 'NEE', parkingFk = 9991015, priority = 1; + +REPLACE vn.shelving SET code = 'PAA', parkingFk = 9992011, priority = 1; +REPLACE vn.shelving SET code = 'PBB', parkingFk = 9992012, priority = 1; +REPLACE vn.shelving SET code = 'PCC', parkingFk = 9992013, priority = 1; + +REPLACE vn.shelving SET code = 'MAA', parkingFk = 9993011, priority = 1; +REPLACE vn.shelving SET code = 'MBB', parkingFk = 9993012, priority = 1; +REPLACE vn.shelving SET code = 'MCC', parkingFk = 9993013, priority = 1; + +INSERT IGNORE INTO vn.itemType + SET id = 999, + code = 'WOO', + name = 'Wood Objects', + categoryFk = 3, + workerFk = 103, + isInventory = TRUE, + life = 10, + density = 250, + itemPackingTypeFk = NULL, + temperatureFk = 'warm'; + +INSERT IGNORE INTO vn.travel + SET id = 99, + shipped = CURDATE(), + landed = CURDATE(), + warehouseInFk = 999, + warehouseOutFk = 1, + isReceived = TRUE, + agencyFk = 1; + +REPLACE vn.entry + SET id = 999, + supplierFk = 791, + isConfirmed = TRUE, + dated = CURDATE(), + travelFk = 99, + companyFk = 442; + +REPLACE vn.ticket + SET id = 999999, + clientFk = 2, + warehouseFk = 999, + shipped = CURDATE(), + nickname = 'Cliente', + addressFk = 1, + companyFk = 442, + agencyModeFk = 10, + landed = CURDATE(); + +REPLACE vn.collection + SET id = 10101010, + workerFk = 9; + +INSERT IGNORE INTO vn.ticketCollection + SET id = 10101010, + ticketFk = 999999, + collectionFk = 10101010; + +REPLACE vn.item + SET id = 999991, + name = 'Palito para pinchos', + `size` = 25, + stems = NULL, + category = 'EXT', + typeFk = 999, + longName = 'Palito para pinchos', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 6, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 9999991, + entryFk = 999, + itemFk = 999991, + quantity = 8, + buyingValue = 0.61, + stickers = 1, + packing = 20, + `grouping` = 1, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 50; + +REPLACE vn.sale + SET id = 99991, + itemFk = 999991, + ticketFk = 999999, + concept = 'Palito para pinchos', + quantity = 3, + price = 1, + discount = 0; + +REPLACE vn.item + SET id = 999992, + name = 'Madera verde', + `size` = 10, + stems = NULL, + category = 'EXT', + typeFk = 999, + longName = 'Madera verde', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 50, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 9999992, + entryFk = 999, + itemFk = 999992, + quantity = 40, + buyingValue = 0.62, + stickers = 1, + packing = 40, + `grouping` = 5, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 25; + +REPLACE vn.sale + SET id = 99992, + itemFk = 999992, + ticketFk = 999999, + concept = 'Madera Verde', + quantity = 10, + price = 1, + discount = 0; + +REPLACE vn.item + SET id = 999993, + name = 'Madera Roja/Morada', + `size` = 12, + stems = 2, + category = 'EXT', + typeFk = 999, + longName = 'Madera Roja/Morada', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 35, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 9999993, + entryFk = 999, + itemFk = 999993, + quantity = 20, + buyingValue = 0.63, + stickers = 2, + packing = 10, + `grouping` = 5, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 25; + +REPLACE vn.itemShelving + SET id = 9931, + itemFk = 999993, + shelvingFk = 'NCC', + visible = 10, + `grouping` = 5, + packing = 10; + +REPLACE vn.sale + SET id = 99993, + itemFk = 999993, + ticketFk = 999999, + concept = 'Madera Roja/Morada', + quantity = 15, + price = 1, + discount = 0; + +REPLACE vn.item + SET id = 999994, + name = 'Madera Naranja', + `size` = 18, + stems = 1, + category = 'EXT', + typeFk = 999, + longName = 'Madera Naranja', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 160, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 9999994, + entryFk = 999, + itemFk = 999994, + quantity = 20, + buyingValue = 0.64, + stickers = 1, + packing = 20, + `grouping` = 4, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 25; + +REPLACE vn.sale + SET id = 99994, + itemFk = 999994, + ticketFk = 999999, + concept = 'Madera Naranja', + quantity = 4, + price = 1, + discount = 0; + +REPLACE vn.item + SET id = 999995, + name = 'Madera Amarilla', + `size` = 11, + stems = 5, + category = 'EXT', + typeFk = 999, + longName = 'Madera Amarilla', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 9999995, + entryFk = 999, + itemFk = 999995, + quantity = 4, + buyingValue = 0.65, + stickers = 1, + packing = 20, + `grouping` = 1, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + +REPLACE vn.sale + SET id = 99995, + itemFk = 999995, + ticketFk = 999999, + concept = 'Madera Amarilla', + quantity = 5, + price = 1, + discount = 0; + +-- Palito naranja +REPLACE vn.item + SET id = 999998, + name = 'Palito naranja', + `size` = 11, + stems = 1, + category = 'EXT', + typeFk = 999, + longName = 'Palito naranja', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 9999998, + entryFk = 999, + itemFk = 999998, + quantity = 80, + buyingValue = 0.65, + stickers = 1, + packing = 200, + `grouping` = 30, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + +REPLACE vn.sale + SET id = 99998, + itemFk = 999998, + ticketFk = 999999, + concept = 'Palito naranja', + quantity = 60, + price = 1, + discount = 0; + +-- Palito amarillo +REPLACE vn.item + SET id = 999999, + name = 'Palito amarillo', + `size` = 11, + stems = 1, + category = 'EXT', + typeFk = 999, + longName = 'Palito amarillo', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 9999999, + entryFk = 999, + itemFk = 999999, + quantity = 70, + buyingValue = 0.65, + stickers = 1, + packing = 500, + `grouping` = 10, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + +REPLACE vn.sale + SET id = 99999, + itemFk = 999999, + ticketFk = 999999, + concept = 'Palito amarillo', + quantity = 50, + price = 1, + discount = 0; + +-- Palito azul +REPLACE vn.item + SET id = 1000000, + name = 'Palito azul', + `size` = 10, + stems = 1, + category = 'EXT', + typeFk = 999, + longName = 'Palito azul', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 10000000, + entryFk = 999, + itemFk = 1000000, + quantity = 75, + buyingValue = 0.65, + stickers = 2, + packing = 300, + `grouping` = 50, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + +REPLACE vn.sale + SET id = 100000, + itemFk = 1000000, + ticketFk = 999999, + concept = 'Palito azul', + quantity = 50, + price = 1, + discount = 0; + +-- Palito rojo +REPLACE vn.item + SET id = 1000001, + name = 'Palito rojo', + `size` = 10, + stems = NULL, + category = 'EXT', + typeFk = 999, + longName = 'Palito rojo', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 78, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 10000001, + entryFk = 999, + itemFk = 1000001, + quantity = 12, + buyingValue = 0.65, + stickers = 2, + packing = 50, + `grouping` = 5, + groupingMode = 1, + packageFk = 94, + price1 = 1, + price2 = 1, + price3 = 1, + minPrice = 1, + weight = 35; + + +REPLACE vn.sale + SET id = 100001, + itemFk = 1000001, + ticketFk = 999999, + concept = 'Palito rojo', + quantity = 10, + price = 1, + discount = 0; + +-- Previa +INSERT IGNORE INTO vn.item + SET id = 999996, + name = 'Bolas de madera', + `size` = 2, + stems = 4, + category = 'EXT', + typeFk = 999, + longName = 'Bolas de madera', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 20, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 9999996, + entryFk = 999, + itemFk = 999996, + quantity = 5, + buyingValue = 3, + stickers = 1, + packing = 5, + `grouping` = 2, + groupingMode = 1, + packageFk = 94, + price1 = 7, + price2 = 7, + price3 = 7, + minPrice = 7, + weight = 80; + +REPLACE vn.sale + SET id = 99996, + itemFk = 999996, + ticketFk = 999999, + concept = 'Bolas de madera', + quantity = 4, + price = 7, + discount = 0, + isPicked = TRUE; + +INSERT IGNORE INTO vn.item + SET id = 999997, + name = 'Palitos de polo MIX', + `size` = 14, + stems = NULL, + category = 'EXT', + typeFk = 999, + longName = 'Palitos de polo MIX', + itemPackingTypeFk = NULL, + originFk = 1, + weightByPiece = 20, + intrastatFk = 44219999; + +REPLACE vn.buy + SET id = 9999997, + entryFk = 999, + itemFk = 999997, + quantity = 100, + buyingValue = 3.2, + stickers = 1, + packing = 100, + `grouping` = 5, + groupingMode = 1, + packageFk = 94, + price1 = 7, + price2 = 7, + price3 = 7, + minPrice = 7, + weight = 80; + +REPLACE vn.sale + SET id = 99997, + itemFk = 999997, + ticketFk = 999999, + concept = 'Palitos de polo MIX', + quantity = 5, + price = 7, + discount = 0; + +USE vn; +DELETE ish.* FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.warehouse w ON w.id = s.warehouseFk + WHERE w.name = 'TestingWarehouse'; + +REPLACE vn.itemShelving +(id, itemFk, shelvingFk, visible, created, `grouping`, packing, packagingFk, userFk, isChecked) +VALUES + (9911, 999991, 'NAA', 8, '2023-09-20', 1, 20, NULL, 103, NULL), + (9912, 999998, 'NAA', 80, '2023-09-20', 10, 30, NULL, 103, NULL), + (9913, 1000001, 'NAA', 6, '2023-09-20', 3, 50, NULL, 103, NULL), + (9914, 1000000, 'NBB', 50, '2023-09-18', 25, 500, NULL, 103, NULL), + (9915, 999993, 'NBB', 25, '2023-09-18', NULL, 10, NULL, 103, NULL), + (9916, 999999, 'NBB', 30, '2023-09-18', 10, 500, NULL, 103, NULL), + (9917, 999993, 'NCC', 25, '2023-09-20', 5, 10, NULL, 103, NULL), + (9918, 999997, 'NCC', 10, '2023-09-20', NULL, 100, NULL, 103, NULL), + (9919, 999999, 'NCC', 40, '2023-09-20', 10, 500, NULL, 103, NULL), + (9920, 999995, 'NDD', 10, '2023-09-19', NULL, 20, NULL, 103, NULL), + (9921, 999994, 'NDD', 48, '2023-09-19', 4, 20, NULL, 103, NULL), + (9922, 1000001, 'NEE', 6, '2023-09-21', 3, 50, NULL, 103, NULL), + (9923, 999992, 'NEE', 50, '2023-09-21', NULL, 1, NULL, 103, NULL), + (9924, 1000000, 'NEE', 25, '2023-09-21', 25, 500, NULL, 103, NULL), + (9925, 999996, 'PAA', 5, '2023-09-27', 1, 5, NULL, 103, NULL), + (9926, 999997, 'PCC', 10, '2023-09-27', 5, 100, NULL, 103, NULL); + +-- Previous for Bolas de madera +INSERT IGNORE INTO vn.sectorCollection + SET id = 99, + userFk = 1, + sectorFk = 9992; + +INSERT IGNORE INTO vn.saleGroup + SET id = 999, + userFk = 1, + parkingFk = 9992011, + sectorFk = 9992; + +INSERT IGNORE INTO vn.sectorCollectionSaleGroup + SET id = 9999, + sectorCollectionFk = 99, + saleGroupFk = 999; + +REPLACE vn.saleGroupDetail + SET id = 99991, + saleFk = 99996, + saleGroupFk = 999; + +REPLACE vn.saleTracking + SET saleFk = 99996, + isChecked = TRUE, + workerFk = 103, + stateFk = 28; + +INSERT IGNORE INTO vn.itemShelvingSale + SET id = 991, + itemShelvingFk = 9962, + saleFk = 99996, + quantity = 5, + userFk = 1; + +UPDATE vn.ticket + SET zoneFk=1 + WHERE id=999999; + +UPDATE vn.collection + SET workerFk=9 + WHERE id=10101010; + +UPDATE vn.sale + SET isPicked =FALSE; \ No newline at end of file diff --git a/modules/item/back/methods/item-barcode/delete.js b/modules/item/back/methods/item-barcode/delete.js new file mode 100644 index 000000000..b27782b1b --- /dev/null +++ b/modules/item/back/methods/item-barcode/delete.js @@ -0,0 +1,34 @@ +module.exports = Self => { + Self.remoteMethod('delete', { + description: 'Delete an ItemBarcode by itemFk and code', + accessType: 'READ', + accepts: [ + { + arg: 'barcode', + type: 'string', + required: true, + }, + { + arg: 'itemFk', + type: 'number', + required: true, + } + ], + http: { + path: `/delete`, + verb: 'DELETE' + } + }); + + Self.delete = async(barcode, itemFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + await Self.destroyAll({ + code: barcode, + itemFk + }, myOptions); + }; +}; diff --git a/modules/item/back/models/item-barcode.js b/modules/item/back/models/item-barcode.js index b608a7fe9..616d973e1 100644 --- a/modules/item/back/models/item-barcode.js +++ b/modules/item/back/models/item-barcode.js @@ -1,5 +1,6 @@ module.exports = Self => { require('../methods/item-barcode/toItem')(Self); + require('../methods/item-barcode/delete')(Self); Self.validatesUniquenessOf('code', { message: `Barcode must be unique` From 36a9b0eee447157f49f3a0571f581f7a5122c485 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 13 Dec 2023 16:00:07 +0100 Subject: [PATCH 025/150] refs #6276 collectionAddItem --- back/methods/collection/addItem.js | 60 +++++++++++++++++++++++++++ back/models/collection.js | 1 + db/changes/235001/00-newWareHouse.sql | 3 +- modules/ticket/back/models/sale.js | 5 ++- 4 files changed, 66 insertions(+), 3 deletions(-) create mode 100644 back/methods/collection/addItem.js diff --git a/back/methods/collection/addItem.js b/back/methods/collection/addItem.js new file mode 100644 index 000000000..4538a479c --- /dev/null +++ b/back/methods/collection/addItem.js @@ -0,0 +1,60 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.remoteMethodCtx('addItem', { + description: 'Add a collection', + accessType: 'WRITE', + accepts: [ + { + arg: 'code', + type: 'string', + required: true + }, + { + arg: 'quantity', + type: 'number', + required: true + }, + { + arg: 'ticketFk', + type: 'number', + required: true + }, + { + arg: 'warehouseFk', + type: 'number', + required: true + }, + ], + http: { + path: `/addItem`, + verb: 'POST' + }, + }); + + Self.addItem = async(ctx, code, quantity, ticketFk, warehouseFk, options) => { + const models = Self.app.models; + const myOptions = {}; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [code, warehouseFk]); + + if (!item.available) throw new UserError('We do not have availability for the selected item'); + + await models.Ticket.addSale(ctx, ticketFk, item.id, quantity, myOptions); + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/back/models/collection.js b/back/models/collection.js index a0d34712f..0d5be170b 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -5,4 +5,5 @@ module.exports = Self => { require('../methods/collection/previousLabel')(Self); require('../methods/collection/getTickets')(Self); require('../methods/collection/assignCollection')(Self); + require('../methods/collection/addItem')(Self); }; diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index 57e3398ff..8437d8e15 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -8,4 +8,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'), ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'), ('SaleTracking','mark','WRITE','ALLOW','ROLE','employee'), - ('ItemBarcode','deleteByItemAndCode','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file + ('ItemBarcode','deleteByItemAndCode','WRITE','ALLOW','ROLE','employee'), + ('Collection','addItem','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index 3589eac4b..d6f06d744 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -71,7 +71,8 @@ module.exports = Self => { }, ctx.options); if (item.family == 'EMB') return; - if (await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*')) return; + const isInPreparing = await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*'); + if (!ctx.isNEwInstance && isInPreparing) return; await models.Sale.rawSql(`CALL catalog_calcFromItem(?,?,?,?)`, [ ticket.landed, @@ -89,7 +90,7 @@ module.exports = Self => { if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; - if (newQuantity < item.minQuantity && newQuantity != available) + if (newQuantity < item.minQuantity && newQuantity != available && !isInPreparing) throw new UserError('The amount cannot be less than the minimum'); if (ctx.isNewInstance || isReduction) return; From 779cbd2c0aaf4ca3a5708880386cedbf41c05fa7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 18 Dec 2023 11:43:15 +0100 Subject: [PATCH 026/150] refs #6276 collection_getTickets --- .../getSalesFromTicketOrCollection.js | 146 ++++++++++++++++++ back/models/collection.js | 1 + 2 files changed, 147 insertions(+) create mode 100644 back/methods/collection/getSalesFromTicketOrCollection.js diff --git a/back/methods/collection/getSalesFromTicketOrCollection.js b/back/methods/collection/getSalesFromTicketOrCollection.js new file mode 100644 index 000000000..d806782d9 --- /dev/null +++ b/back/methods/collection/getSalesFromTicketOrCollection.js @@ -0,0 +1,146 @@ +module.exports = Self => { + Self.remoteMethodCtx('getSalesFromTicketOrCollection', { + description: 'Get sales from ticket or collection', + accessType: 'READ', + accepts: [ + { + arg: 'collectionOrTicketFk', + type: 'number', + required: true + }, + { + arg: 'sectorFk', + type: 'number', + required: true + }, + { + arg: 'printFk', + type: 'number', + required: true + }, + { + arg: 'source', + type: 'string', + required: true + }, + + ], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/getSalesFromTicketOrCollection`, + verb: 'GET' + }, + }); + + Self.getSalesFromTicketOrCollection = async(ctx, collectionOrTicketFk, sectorFk, printFk, source, options) => { + const models = Self.app.models; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const [collectionOrTicket] = await Self.rawSql('SELECT vn.ticket_get(?) as id', [collectionOrTicketFk]); + + const [tickets] = await Self.rawSql('CALL vn.collection_getTickets(?)', [collectionOrTicket.id]); + + if (source == 'PRECHECKER' || source == 'ON_CHECKING') { + await Self.rawSql( + 'CALL vn.ticketStateToday_setState(?,?)', + [collectionOrTicket.id, source] + ); + } + + const [sales] = await Self.rawSql('CALL vn.sale_getFromTicketOrCollection(?)', [collectionOrTicket.id]); + + const isPicker = source == 'CHECKER'; + const [placements] = await Self.rawSql( + 'CALL vn.collectionPlacement_get(?, ?)', [collectionOrTicket.id, isPicker] + ); + + if (printFk == 1) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [collectionOrTicket.id]); + + if (tickets.length) await sendRocketTickets(tickets); + + return getCollection(collectionOrTicket.id, tickets, sales, placements); + + async function sendRocketTickets(tickets) { + for (let ticket of tickets) { + let observations = ticket.observaciones.split(' '); + + for (let observation of observations) { + const salesMan = ticket.salesPersonFk; + + if (!observation.startsWith('#') && !observation.startsWith('@')) return; + + await models.Chat.send(ctx, + observation, + `El ticket ${ticket.ticketFk} del comercial ${salesMan} está en preparación.(mensaje creado automáticamente)` + ); + } + } + } + + async function getCollection(id, tickets, sales, placements) { + const collection = { + collectionFk: id, + tickets: [], + }; + for (let ticket of tickets) { + const {ticketFk} = ticket; + ticket.sales = []; + + const barcodes = await getBarcodes(ticketFk); + await Self.rawSql( + 'CALL util.log_add(?, ?, ?, ?, ?, ?, ?, ?)', + ['vn', 'ticket', 'Ticket', ticketFk, ticketFk, 'select', null, null] + ); + + for (let sale of sales) { + if (sale.ticketFk == ticketFk) { + sale.placements = placements.filter(placement => + placement.saleFk == sale.saleFk && placement.order + ); + + sale.barcodes = []; + for (const barcode of barcodes) { + if (barcode.movementId) { + if (barcode.code) { + sale.barcodes.push(barcode.code); + sale.barcodes.push(`0 ${barcode.code}`); + } + + if (barcode.id) { + sale.barcodes.push(barcode.id); + sale.barcodes.push(`0 ${barcode.id}`); + } + } + } + + ticket.sales.push(sale); + } + } + collection.tickets.push(ticket); + } + + return collection; + } + + async function getBarcodes(ticketId) { + const query = + `SELECT s.id movementId, + b.code, + c.id + FROM vn.sale s + LEFT JOIN vn.itemBarcode b ON b.itemFk = s.itemFk + LEFT JOIN vn.buy c ON c.itemFk = s.itemFk + LEFT JOIN vn.entry e ON e.id = c.entryFk + LEFT JOIN vn.travel tr ON tr.id = e.travelFk + WHERE s.ticketFk = ? + AND tr.landed >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)`; + return Self.rawSql(query, [ticketId]); + } + }; +}; diff --git a/back/models/collection.js b/back/models/collection.js index 0d5be170b..98a199fbd 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -6,4 +6,5 @@ module.exports = Self => { require('../methods/collection/getTickets')(Self); require('../methods/collection/assignCollection')(Self); require('../methods/collection/addItem')(Self); + require('../methods/collection/getSalesFromTicketOrCollection')(Self); }; From 92b4908b35ff666ed4bbe3ca1b867663ab499c6c Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 2 Jan 2024 09:42:41 +0100 Subject: [PATCH 027/150] fix conflicts: refs #6276 --- loopback/locale/es.json | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 1dbb394ab..819ee1740 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -330,10 +330,6 @@ "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", "Cannot past travels with entries": "No se pueden pasar envíos con entradas", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", -<<<<<<< HEAD - "The line could not be marked": "The line could not be marked" -} -======= + "The line could not be marked": "The line could not be marked", "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada" } ->>>>>>> 0101dcda3ac950c1add6c3c426c4f745389805c1 From 365e05d560195c67c2e16af1b02f1dd4093961b8 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 2 Jan 2024 12:21:25 +0100 Subject: [PATCH 028/150] =?UTF-8?q?refs=20#6276:mdify=20back=20silex?= =?UTF-8?q?=E2=86=92salix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/changes/235001/00-newWareHouse.sql | 4 +++- modules/worker/back/methods/operator/getPrinter.js | 7 ++++--- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index 8437d8e15..b7d5f8a59 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -9,4 +9,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'), ('SaleTracking','mark','WRITE','ALLOW','ROLE','employee'), ('ItemBarcode','deleteByItemAndCode','WRITE','ALLOW','ROLE','employee'), - ('Collection','addItem','WRITE','ALLOW','ROLE','employee'); \ No newline at end of file + ('Collection','addItem','WRITE','ALLOW','ROLE','employee'); + ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'); + \ No newline at end of file diff --git a/modules/worker/back/methods/operator/getPrinter.js b/modules/worker/back/methods/operator/getPrinter.js index c46734517..31fbff7b5 100644 --- a/modules/worker/back/methods/operator/getPrinter.js +++ b/modules/worker/back/methods/operator/getPrinter.js @@ -7,7 +7,7 @@ module.exports = Self => { verb: 'GET' }, returns: { - type: 'object', + type: ['object'], }, }); @@ -30,10 +30,11 @@ module.exports = Self => { if (operator) { const printer = operator.printer(); - return { + console.log({ id: printer.id, name: printer.name - }; + }); + return Array.isArray(printer) ? printer : [printer]; } }; }; From 924fe12a9344641db09792fa546fc18a005b63ac Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 2 Jan 2024 12:44:12 +0100 Subject: [PATCH 029/150] add root: refs #6276 --- modules/worker/back/methods/operator/getPrinter.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/modules/worker/back/methods/operator/getPrinter.js b/modules/worker/back/methods/operator/getPrinter.js index 31fbff7b5..88e7d8090 100644 --- a/modules/worker/back/methods/operator/getPrinter.js +++ b/modules/worker/back/methods/operator/getPrinter.js @@ -8,6 +8,7 @@ module.exports = Self => { }, returns: { type: ['object'], + root: true }, }); @@ -30,11 +31,8 @@ module.exports = Self => { if (operator) { const printer = operator.printer(); - console.log({ - id: printer.id, - name: printer.name - }); return Array.isArray(printer) ? printer : [printer]; } + return []; }; }; From bce8feb552b19e93aeb6541ff0db24f11cf44aa8 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 3 Jan 2024 10:41:44 +0100 Subject: [PATCH 030/150] refs #6276 add maxHours --- db/dump/fixtures.sql | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 08225213c..96bde7e83 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3666,4 +3666,7 @@ UPDATE vn.collection WHERE id=10101010; UPDATE vn.sale - SET isPicked =FALSE; \ No newline at end of file + SET isPicked =FALSE; + +INSERT INTO machineWorkerConfig(maxHours) + VALUES(12); \ No newline at end of file From 0b5ffcc81cb95691bf89bc8298705ff5b295e3c4 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 3 Jan 2024 12:50:53 +0100 Subject: [PATCH 031/150] =?UTF-8?q?refs=20#6276:modify=20back=20silex?= =?UTF-8?q?=E2=86=92salix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- back/methods/collection/addItem.js | 2 +- back/methods/machine-worker/updateInTime.js | 2 +- db/changes/235001/00-newWareHouse.sql | 8 ++++++-- loopback/locale/es.json | 6 ++++-- modules/item/back/methods/item-shelving/makeMulti.js | 2 +- modules/item/back/methods/item-shelving/return.js | 2 +- modules/item/back/methods/item/card.js | 2 +- .../ticket/back/methods/expedition-pallet/getPallet.js | 1 + 8 files changed, 16 insertions(+), 9 deletions(-) diff --git a/back/methods/collection/addItem.js b/back/methods/collection/addItem.js index 4538a479c..d3afbd71b 100644 --- a/back/methods/collection/addItem.js +++ b/back/methods/collection/addItem.js @@ -6,7 +6,7 @@ module.exports = Self => { accepts: [ { arg: 'code', - type: 'string', + type: 'number', required: true }, { diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index 917733686..3fdb484dd 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -50,7 +50,7 @@ module.exports = Self => { }); if (machineWorker) { await machineWorker.updateAttributes({ - inTime: new Date(Date.now()) + outTime: new Date(Date.now()) }, myOptions); } diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index b7d5f8a59..c088a8730 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -9,6 +9,10 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'), ('SaleTracking','mark','WRITE','ALLOW','ROLE','employee'), ('ItemBarcode','deleteByItemAndCode','WRITE','ALLOW','ROLE','employee'), - ('Collection','addItem','WRITE','ALLOW','ROLE','employee'); - ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'); + ('Collection','addItem','WRITE','ALLOW','ROLE','employee'), + ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('MobileAppVersionControl', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'), + ('Collection', 'addItem', 'WRITE', 'ALLOW', 'ROLE', 'production'), + ('MachineWorker', 'updateInTime', 'WRITE', 'ALLOW', 'ROLE', 'production');; \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 819ee1740..fb3335eb2 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -331,5 +331,7 @@ "Cannot past travels with entries": "No se pueden pasar envíos con entradas", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", "The line could not be marked": "The line could not be marked", - "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada" -} + "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada", + "No hay tickets para sacar": "No hay tickets para sacar", + "There is no zone for these parameters 999999": "There is no zone for these parameters 999999" +} \ No newline at end of file diff --git a/modules/item/back/methods/item-shelving/makeMulti.js b/modules/item/back/methods/item-shelving/makeMulti.js index d4b451760..e4393e4de 100644 --- a/modules/item/back/methods/item-shelving/makeMulti.js +++ b/modules/item/back/methods/item-shelving/makeMulti.js @@ -4,7 +4,7 @@ module.exports = Self => { accessType: 'WRITE', accepts: [{ arg: 'shelvingFk', - type: 'number', + type: 'string', required: true, }, { diff --git a/modules/item/back/methods/item-shelving/return.js b/modules/item/back/methods/item-shelving/return.js index 346fe8bdf..27bc39a50 100644 --- a/modules/item/back/methods/item-shelving/return.js +++ b/modules/item/back/methods/item-shelving/return.js @@ -62,7 +62,7 @@ module.exports = Self => { return { id: itemShelving.id, - item: itemShelving.itemFk, + itemFk: itemShelving.itemFk, longName: item ? item.longName || `${item.name} ${item.size}` : '', quantity: itemShelving.visible, stickers: Math.ceil(itemShelving.visible / itemShelving.packing), diff --git a/modules/item/back/methods/item/card.js b/modules/item/back/methods/item/card.js index 6d861b394..41d134f3b 100644 --- a/modules/item/back/methods/item/card.js +++ b/modules/item/back/methods/item/card.js @@ -44,7 +44,7 @@ module.exports = Self => { let itemInfo; if (result.length) { itemInfo = {...result[0]}; - itemInfo.barcodes = barcodes.map(barcode => barcode.code); + itemInfo.barcodes = barcodes; } return itemInfo; diff --git a/modules/ticket/back/methods/expedition-pallet/getPallet.js b/modules/ticket/back/methods/expedition-pallet/getPallet.js index 09775a6fa..22cbbc210 100644 --- a/modules/ticket/back/methods/expedition-pallet/getPallet.js +++ b/modules/ticket/back/methods/expedition-pallet/getPallet.js @@ -16,6 +16,7 @@ module.exports = Self => { }, returns: { type: 'object', + root: true }, }); From e354de4ff5c8625fe8463fe64e124f4de0703e11 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 4 Jan 2024 10:09:41 +0100 Subject: [PATCH 032/150] fix: updateInTime refs #6276 --- back/methods/machine-worker/updateInTime.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index 3fdb484dd..278d1d08d 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -42,7 +42,7 @@ module.exports = Self => { const machineWorker = await models.MachineWorker.findOne({ where: { workerFk: userId, - inTime: {gte: new Date(Date.now() - maxHours * 60 * 60 * 1000)}, + inTime: {gte: Date.vnNew() - (maxHours * 60 * 60 * 1000)}, outTimed: null, machineFk: machine.id, } @@ -50,7 +50,7 @@ module.exports = Self => { }); if (machineWorker) { await machineWorker.updateAttributes({ - outTime: new Date(Date.now()) + outTime: Date.now() }, myOptions); } From 384d9ec803c7c038570f6fe076a14761fecd9bf1 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 4 Jan 2024 12:27:02 +0100 Subject: [PATCH 033/150] fix: updateTracking refs #6276 --- modules/ticket/back/methods/sale-tracking/updateTracking.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/sale-tracking/updateTracking.js b/modules/ticket/back/methods/sale-tracking/updateTracking.js index 1f499022e..c6f051f9a 100644 --- a/modules/ticket/back/methods/sale-tracking/updateTracking.js +++ b/modules/ticket/back/methods/sale-tracking/updateTracking.js @@ -20,7 +20,7 @@ module.exports = Self => { }, { arg: 'isChecked', - type: 'number', + type: 'boolean', required: true }, { From da8057e4c7196dd0dfefbe08962944fe1443a8e7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 4 Jan 2024 12:35:00 +0100 Subject: [PATCH 034/150] fix: updateTracking refs #6276 --- modules/ticket/back/methods/sale-tracking/updateTracking.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/sale-tracking/updateTracking.js b/modules/ticket/back/methods/sale-tracking/updateTracking.js index c6f051f9a..453b0b0c6 100644 --- a/modules/ticket/back/methods/sale-tracking/updateTracking.js +++ b/modules/ticket/back/methods/sale-tracking/updateTracking.js @@ -30,7 +30,7 @@ module.exports = Self => { }, { arg: 'isScanned', - type: 'number', + type: 'boolean', }, ], http: { @@ -64,7 +64,7 @@ module.exports = Self => { originalQuantity, workerFk: userId, stateFk: state.id, - isScanned, + isScanned: isScanned === undefined ? null : isScanned, }; const saleTracking = await models.SaleTracking.findOne({ From 3ebf0a30a9c3561ac25fff794eed142ebb47dceb Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 4 Jan 2024 12:44:44 +0100 Subject: [PATCH 035/150] refactor: drop getItemPackingType refs #6276 --- .../methods/operator/getItemPackingType.js | 31 ------------------- 1 file changed, 31 deletions(-) delete mode 100644 modules/worker/back/methods/operator/getItemPackingType.js diff --git a/modules/worker/back/methods/operator/getItemPackingType.js b/modules/worker/back/methods/operator/getItemPackingType.js deleted file mode 100644 index d28cd95fe..000000000 --- a/modules/worker/back/methods/operator/getItemPackingType.js +++ /dev/null @@ -1,31 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('getItemPackingType', { - description: 'Retrieve the operator items', - accessType: 'READ', - returns: { - type: 'object', - }, - http: { - path: `/getItemPackingType`, - verb: 'GET' - }, - }); - - Self.getItemPackingType = async ctx => { - const userId = 9 ?? ctx.req.accessToken.userId; - - const result = await Self.findOne({ - where: { - workerFk: userId - }, - include: { - relation: 'itemPackingType', - } - }); - const itemPackingType = result.itemPackingType(); - - return { - description: itemPackingType?.description - }; - }; -}; From 2eca02d74f2a202c5c331fa881956413e7ab727f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 4 Jan 2024 12:57:46 +0100 Subject: [PATCH 036/150] refactor: drop getItemPackingType refs #6276 --- modules/worker/back/models/operator.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index b9ea481a7..5e8870130 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -2,7 +2,6 @@ module.exports = Self => { require('../methods/operator/add')(Self); require('../methods/operator/getPrinter')(Self); require('../methods/operator/getAvailablePrinters')(Self); - require('../methods/operator/getItemPackingType')(Self); Self.observe('after save', async function(ctx) { const instance = ctx.data || ctx.instance; From ad89363db5d707a5d1903a11aa7ba43bc04a49ad Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 4 Jan 2024 13:11:39 +0100 Subject: [PATCH 037/150] fix: mark refs #6276 --- modules/ticket/back/methods/sale-tracking/mark.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/mark.js index a5b8ece52..327421673 100644 --- a/modules/ticket/back/methods/sale-tracking/mark.js +++ b/modules/ticket/back/methods/sale-tracking/mark.js @@ -32,7 +32,7 @@ module.exports = Self => { }, { arg: 'isScanned', - type: 'number', + type: 'boolean', }, { arg: 'quantity', From 8a5da43503f774c26b26817e45388679cec38dd7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 4 Jan 2024 16:00:25 +0100 Subject: [PATCH 038/150] refactor: sectorCollection_getSale refs #6276 --- db/changes/235001/00-newWareHouse.sql | 3 ++- modules/item/back/models/item-shelving.js | 1 - .../back/methods/sale/getFromSectorCollection.js} | 10 +++++----- modules/ticket/back/models/sale.js | 1 + 4 files changed, 8 insertions(+), 7 deletions(-) rename modules/{item/back/methods/item-shelving/getSale.js => ticket/back/methods/sale/getFromSectorCollection.js} (84%) diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index c088a8730..60d2658b0 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -14,5 +14,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('MobileAppVersionControl', '*', 'READ', 'ALLOW', 'ROLE', 'production'), ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'), ('Collection', 'addItem', 'WRITE', 'ALLOW', 'ROLE', 'production'), - ('MachineWorker', 'updateInTime', 'WRITE', 'ALLOW', 'ROLE', 'production');; + ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Collection', 'addItem', 'WRITE', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file diff --git a/modules/item/back/models/item-shelving.js b/modules/item/back/models/item-shelving.js index e349b9c34..4eb5374e8 100644 --- a/modules/item/back/models/item-shelving.js +++ b/modules/item/back/models/item-shelving.js @@ -4,5 +4,4 @@ module.exports = Self => { require('../methods/item-shelving/makeMulti')(Self); require('../methods/item-shelving/return')(Self); require('../methods/item-shelving/updateFromSale')(Self); - require('../methods/item-shelving/getSale')(Self); }; diff --git a/modules/item/back/methods/item-shelving/getSale.js b/modules/ticket/back/methods/sale/getFromSectorCollection.js similarity index 84% rename from modules/item/back/methods/item-shelving/getSale.js rename to modules/ticket/back/methods/sale/getFromSectorCollection.js index 826ac03e1..9e4f24fbb 100644 --- a/modules/item/back/methods/item-shelving/getSale.js +++ b/modules/ticket/back/methods/sale/getFromSectorCollection.js @@ -1,7 +1,7 @@ module.exports = Self => { - Self.remoteMethod('getSale', { - description: 'Update the visible items', - accessType: 'WRITE', + Self.remoteMethod('getFromSectorCollection', { + description: 'Get sales from sector collection', + accessType: 'READ', accepts: [ { arg: 'sectorCollectionFk', @@ -19,12 +19,12 @@ module.exports = Self => { root: true }, http: { - path: `/getSale`, + path: `/getFromSectorCollection`, verb: 'GET' }, }); - Self.getSale = async(sectorCollectionFk, sectorFk, options) => { + Self.getFromSectorCollection = async(sectorCollectionFk, sectorFk, options) => { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index d6f06d744..7cac50a13 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -13,6 +13,7 @@ module.exports = Self => { require('../methods/sale/canEdit')(Self); require('../methods/sale/usesMana')(Self); require('../methods/sale/clone')(Self); + require('../methods/sale/getFromSectorCollection')(Self); Self.validatesPresenceOf('concept', { message: `Concept cannot be blank` From 9afc3840c76886dc5dd3645343703f892e07fa80 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 9 Jan 2024 11:22:11 +0100 Subject: [PATCH 039/150] fix: refs #6276 machineWorker_add --- back/methods/machine-worker/add.js | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/back/methods/machine-worker/add.js b/back/methods/machine-worker/add.js index 65eb5d297..92d0df78e 100644 --- a/back/methods/machine-worker/add.js +++ b/back/methods/machine-worker/add.js @@ -37,27 +37,16 @@ module.exports = Self => { if (!machine) throw new Error(`plate ${plate} does not exist`); - const twelveHoursAgo = Date.vnNew(); - twelveHoursAgo.setHours(twelveHoursAgo.getHours() - 12); - - const isRegistered = await models.MachineWorker.findOne({ - where: { - and: [ - {machineFk: machine.id}, - {workerFk: userId}, - {outTime: {gte: twelveHoursAgo}} - ] - } - }, myOptions); - - if (!isRegistered) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); - else { await models.MachineWorker.updateAll( - {or: [{workerFk: userId}, {machineFk: machine.id}]}, + { + or: [{workerFk: userId}, {machineFk: machine.id}], + and: [{outTime: null }] + }, {outTime: Date.vnNew()}, myOptions ); - } + + await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); if (tx) await tx.commit(); } catch (e) { From 7a9f2bd79cea197dc60bf6d192f503e65fa666d5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 9 Jan 2024 11:23:54 +0100 Subject: [PATCH 040/150] refactor: refs #6276 align rows --- back/methods/machine-worker/add.js | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/back/methods/machine-worker/add.js b/back/methods/machine-worker/add.js index 92d0df78e..c6fdd620e 100644 --- a/back/methods/machine-worker/add.js +++ b/back/methods/machine-worker/add.js @@ -37,14 +37,14 @@ module.exports = Self => { if (!machine) throw new Error(`plate ${plate} does not exist`); - await models.MachineWorker.updateAll( - { - or: [{workerFk: userId}, {machineFk: machine.id}], - and: [{outTime: null }] - }, - {outTime: Date.vnNew()}, - myOptions - ); + await models.MachineWorker.updateAll( + { + or: [{workerFk: userId}, {machineFk: machine.id}], + and: [{outTime: null }] + }, + {outTime: Date.vnNew()}, + myOptions + ); await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); From fafc25ed1943e2a0880182c82e651bd783f3ec19 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 16 Jan 2024 14:50:09 +0100 Subject: [PATCH 041/150] refactor: refs #6276 sectorCollection_getSale --- .../methods/sale/getFromSectorCollection.js | 29 +++++++++++++++++-- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/modules/ticket/back/methods/sale/getFromSectorCollection.js b/modules/ticket/back/methods/sale/getFromSectorCollection.js index 9e4f24fbb..9a1b52ed8 100644 --- a/modules/ticket/back/methods/sale/getFromSectorCollection.js +++ b/modules/ticket/back/methods/sale/getFromSectorCollection.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('getFromSectorCollection', { + Self.remoteMethodCtx('getFromSectorCollection', { description: 'Get sales from sector collection', accessType: 'READ', accepts: [ @@ -24,12 +24,35 @@ module.exports = Self => { }, }); - Self.getFromSectorCollection = async(sectorCollectionFk, sectorFk, options) => { + Self.getFromSectorCollection = async(ctx, sectorCollectionFk, sectorFk, options) => { const myOptions = {}; + const userId = ctx.req.accessToken.userId; if (typeof options == 'object') Object.assign(myOptions, options); - const [sales] = await Self.rawSql('CALL vn.sectorCollection_getSale(?)', [sectorCollectionFk]); + const sales = await Self.rawSql( + `SELECT s.ticketFk, + s.itemFk, + i.longName, + itemPackingTypeFk, + subName, + s.quantity, + w.code workerCode, + sgd.saleFk, + iss.quantity pickedQuantity, + c.salesPersonFk + FROM vn.sale s + JOIN item i ON i.id = s.itemFk + JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sgd.saleGroupFk + JOIN saleTracking st ON st.saleFk = s.id + JOIN state stt ON stt.id = st.stateFk AND stt.code = 'PREVIOUS_PREPARATION' + JOIN worker w ON w.id = st.workerFk + JOIN ticket t ON t.id= s.ticketFk + JOIN client c ON c.id=t.clientFk + LEFT JOIN itemShelvingSaleSum iss ON iss.saleFk = s.id + WHERE scsg.sectorCollectionFk = ? + AND st.workerFk = ?;`, [sectorCollectionFk, userId]); const itemShelvings = []; for (let sale of sales) { From 2fbea6f9dd0525891ca31e83d4f83535df5a1b2b Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 16 Jan 2024 15:43:34 +0100 Subject: [PATCH 042/150] feat: refs #6276 wip machineWorke_update --- back/methods/machine-worker/updateInTime.js | 23 +++++++++++++-------- loopback/locale/es.json | 7 ++++--- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index 278d1d08d..0ae968b83 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('updateInTime', { description: 'Updates the corresponding registry if the worker has been registered in the last few hours', @@ -34,25 +35,29 @@ module.exports = Self => { fields: ['id', 'plate'], where: {plate} }, myOptions); - if (!machine) throw new Error(`plate ${plate} does not exist`); const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); - - const machineWorker = await models.MachineWorker.findOne({ + const machineWorker = await Self.findOne({ where: { - workerFk: userId, - inTime: {gte: Date.vnNew() - (maxHours * 60 * 60 * 1000)}, - outTimed: null, machineFk: machine.id, + outTime: null, } + }, myOptions); - }); if (machineWorker) { + const hoursDifference = (Date.vnNew() - machineWorker.inTime) / (60 * 60 * 1000); + const isHimSelf = userId == machineWorker.workerFk; + + if (maxHours > hoursDifference && !isHimSelf) throw new UserError('Esta máquina ya está en uso.'); + await machineWorker.updateAttributes({ - outTime: Date.now() + outTime: Date.vnNew() }, myOptions); - } + + if (!isHimSelf) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); + } else + await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); if (tx) await tx.commit(); } catch (e) { diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 698303a26..5d57b1968 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -72,7 +72,7 @@ "The secret can't be blank": "La contraseña no puede estar en blanco", "We weren't able to send this SMS": "No hemos podido enviar el SMS", "This client can't be invoiced": "Este cliente no puede ser facturado", - "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", + "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", "This ticket can't be invoiced": "Este ticket no puede ser facturado", "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", "This ticket can not be modified": "Este ticket no puede ser modificado", @@ -339,5 +339,6 @@ "The alias cant be modified": "Este alias de correo no puede ser modificado", "No tickets to invoice": "No hay tickets para facturar", "No hay tickets para sacar": "No hay tickets para sacar", - "There is no zone for these parameters 999999": "There is no zone for these parameters 999999" -} + "There is no zone for these parameters 999999": "There is no zone for these parameters 999999", + "Esta máquina ya está en uso.": "Esta máquina ya está en uso." +} \ No newline at end of file From 53a10dda58698f72539aa351cc638470fa5e8c9b Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 17 Jan 2024 08:17:55 +0100 Subject: [PATCH 043/150] feat: refs #6276 machineWorke_update --- back/methods/machine-worker/add.js | 57 --------------------- back/methods/machine-worker/updateInTime.js | 8 +-- back/models/machine-worker.js | 1 - db/changes/235001/00-newWareHouse.sql | 1 - 4 files changed, 4 insertions(+), 63 deletions(-) delete mode 100644 back/methods/machine-worker/add.js diff --git a/back/methods/machine-worker/add.js b/back/methods/machine-worker/add.js deleted file mode 100644 index c6fdd620e..000000000 --- a/back/methods/machine-worker/add.js +++ /dev/null @@ -1,57 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('add', { - description: 'Insert log if the worker has not logged anything in the last 12 hours', - accessType: 'READ', - accepts: [ - { - arg: 'plate', - type: 'string', - } - ], - http: { - path: `/add`, - verb: 'POST' - } - }); - - Self.add = async(ctx, plate, options) => { - const models = Self.app.models; - const userId = ctx.req.accessToken.userId; - - let tx; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - const machine = await models.Machine.findOne({ - fields: ['id', 'plate'], - where: {plate} - }, myOptions); - - if (!machine) throw new Error(`plate ${plate} does not exist`); - - await models.MachineWorker.updateAll( - { - or: [{workerFk: userId}, {machineFk: machine.id}], - and: [{outTime: null }] - }, - {outTime: Date.vnNew()}, - myOptions - ); - - await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); - - if (tx) await tx.commit(); - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index 0ae968b83..5065373a2 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -35,9 +35,8 @@ module.exports = Self => { fields: ['id', 'plate'], where: {plate} }, myOptions); - if (!machine) throw new Error(`plate ${plate} does not exist`); + if (!machine) throw new Error(`plate ${plate} does not exist.`); - const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); const machineWorker = await Self.findOne({ where: { machineFk: machine.id, @@ -46,10 +45,11 @@ module.exports = Self => { }, myOptions); if (machineWorker) { - const hoursDifference = (Date.vnNew() - machineWorker.inTime) / (60 * 60 * 1000); + const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); + const hoursDifference = (Date.vnNow() - machineWorker.inTime.getTime()) / (60 * 60 * 1000); const isHimSelf = userId == machineWorker.workerFk; - if (maxHours > hoursDifference && !isHimSelf) throw new UserError('Esta máquina ya está en uso.'); + if (maxHours > hoursDifference && !isHimSelf) throw new UserError('This machine is already in use.'); await machineWorker.updateAttributes({ outTime: Date.vnNew() diff --git a/back/models/machine-worker.js b/back/models/machine-worker.js index b44cb1fb6..cbc5fd53e 100644 --- a/back/models/machine-worker.js +++ b/back/models/machine-worker.js @@ -1,4 +1,3 @@ module.exports = Self => { require('../methods/machine-worker/updateInTime')(Self); - require('../methods/machine-worker/add')(Self); }; diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/235001/00-newWareHouse.sql index 60d2658b0..1b1ec263f 100644 --- a/db/changes/235001/00-newWareHouse.sql +++ b/db/changes/235001/00-newWareHouse.sql @@ -3,7 +3,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'employee'), ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'), ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'), - ('MachineWorker','add','READ','ALLOW','ROLE','employee'), ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'), ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'), ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'), From 6a78123fca12c382651327d2e74226260735b315 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 17 Jan 2024 09:01:48 +0100 Subject: [PATCH 044/150] fix: refs #6276 machineWorke_update --- back/methods/machine-worker/updateInTime.js | 3 ++- loopback/locale/es.json | 3 ++- modules/ticket/back/methods/ticket/specs/setDeleted.spec.js | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index 5065373a2..705bcdd92 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -55,7 +55,8 @@ module.exports = Self => { outTime: Date.vnNew() }, myOptions); - if (!isHimSelf) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); + if (maxHours <= hoursDifference) + await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); } else await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 5d57b1968..babb4bd2a 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -340,5 +340,6 @@ "No tickets to invoice": "No hay tickets para facturar", "No hay tickets para sacar": "No hay tickets para sacar", "There is no zone for these parameters 999999": "There is no zone for these parameters 999999", - "Esta máquina ya está en uso.": "Esta máquina ya está en uso." + "Esta máquina ya está en uso.": "Esta máquina ya está en uso.", + "This machine is already in use.": "This machine is already in use." } \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js index 43bc2c2d9..0dcd2762c 100644 --- a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js @@ -57,7 +57,7 @@ describe('ticket setDeleted()', () => { `SELECT COUNT(*) numberRows FROM vn.sectorCollection`, [], options); - expect(sectorCollection.numberRows).toEqual(0); + expect(sectorCollection.numberRows).toEqual(1); await tx.rollback(); } catch (e) { From 90b1e8d664b58c17cc2345adb6ba6ceb531e4aac Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 17 Jan 2024 10:18:13 +0100 Subject: [PATCH 045/150] fix: refs #6276 backend tests --- db/dump/fixtures.sql | 7 +++++-- modules/entry/back/methods/entry/specs/filter.spec.js | 4 ++-- .../ticket/back/methods/sale-tracking/specs/delete.spec.js | 2 +- .../back/methods/travel/specs/extraCommunityFilter.spec.js | 2 +- modules/travel/back/methods/travel/specs/filter.spec.js | 2 +- 5 files changed, 10 insertions(+), 7 deletions(-) diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 50168ccea..2b04327cf 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3047,9 +3047,12 @@ INSERT INTO `vn`.`clientSms` (`id`, `clientFk`, `smsFk`, `ticketFk`) -- NEW WAREHOUSE -UPDATE vn.packaging +/* UPDATE vn.packaging SET id='--' - WHERE id='pallet 100'; + WHERE id='pallet 100'; */ +INSERT INTO vn.packaging + VALUES('--', 2745600.00, 100.00, 120.00, 220.00, 0.00, 1, '2001-01-01 00:00:00.000', NULL, NULL, NULL, 0.00, 16, 0.00, 0, NULL, 0.00, NULL, NULL, 0, NULL, 0, 0); + INSERT IGNORE INTO vn.intrastat SET id = 44219999, diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index dcad13320..28763bc81 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -37,7 +37,7 @@ describe('Entry filter()', () => { const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(8); + expect(result.length).toEqual(9); await tx.rollback(); } catch (e) { @@ -81,7 +81,7 @@ describe('Entry filter()', () => { const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(7); + expect(result.length).toEqual(8); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/sale-tracking/specs/delete.spec.js b/modules/ticket/back/methods/sale-tracking/specs/delete.spec.js index a8bcf5692..e23c12a61 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/delete.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/delete.spec.js @@ -11,7 +11,7 @@ describe('sale-tracking delete()', () => { const saleTrackingsBefore = await models.SaleTracking.find(null, options); const saleFk = 1; - const stateCode = 'PREPARED'; + const stateCode = ['PREPARED']; const result = await models.SaleTracking.delete(saleFk, stateCode, options); const itemShelvingsAfter = await models.ItemShelvingSale.find(null, options); diff --git a/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js index 599851b55..1ce55cc91 100644 --- a/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js +++ b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js @@ -79,7 +79,7 @@ describe('Travel extraCommunityFilter()', () => { const result = await app.models.Travel.extraCommunityFilter(ctx, filter); - expect(result.length).toEqual(8); + expect(result.length).toEqual(9); }); it('should return the travel matching "cargoSupplierFk"', async() => { diff --git a/modules/travel/back/methods/travel/specs/filter.spec.js b/modules/travel/back/methods/travel/specs/filter.spec.js index 1a6ee895c..6cb366938 100644 --- a/modules/travel/back/methods/travel/specs/filter.spec.js +++ b/modules/travel/back/methods/travel/specs/filter.spec.js @@ -80,6 +80,6 @@ describe('Travel filter()', () => { const result = await app.models.Travel.filter(ctx); - expect(result.length).toEqual(5); + expect(result.length).toEqual(6); }); }); From e69ec2c8561ae508e037a25585da5430ae2a067d Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 17 Jan 2024 12:07:22 +0100 Subject: [PATCH 046/150] feat: refs #6276 test expeditionPallet_get --- loopback/locale/en.json | 3 +- loopback/locale/es.json | 4 +-- .../methods/expedition-pallet/getPallet.js | 14 ++++++--- .../expedition-pallet/specs/getPallet.spec.js | 31 +++++++++++++++++++ 4 files changed, 45 insertions(+), 7 deletions(-) create mode 100644 modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js diff --git a/loopback/locale/en.json b/loopback/locale/en.json index ba9acecae..391034126 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -204,5 +204,6 @@ "The notification subscription of this worker cant be modified": "The notification subscription of this worker cant be modified", "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}", "Incorrect pin": "Incorrect pin.", - "The notification subscription of this worker cant be modified": "The notification subscription of this worker cant be modified" + "This machine is already in use.": "This machine is already in use.", + "This pallet does not exist": "This pallet does not exist" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index babb4bd2a..b273f7506 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -340,6 +340,6 @@ "No tickets to invoice": "No hay tickets para facturar", "No hay tickets para sacar": "No hay tickets para sacar", "There is no zone for these parameters 999999": "There is no zone for these parameters 999999", - "Esta máquina ya está en uso.": "Esta máquina ya está en uso.", - "This machine is already in use.": "This machine is already in use." + "This machine is already in use.": "Esta máquina ya está en uso.", + "This pallet does not exist": "Este palet no existe" } \ No newline at end of file diff --git a/modules/ticket/back/methods/expedition-pallet/getPallet.js b/modules/ticket/back/methods/expedition-pallet/getPallet.js index 22cbbc210..340dc02b0 100644 --- a/modules/ticket/back/methods/expedition-pallet/getPallet.js +++ b/modules/ticket/back/methods/expedition-pallet/getPallet.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('getPallet', { + Self.remoteMethodCtx('getPallet', { description: 'Get pallet', accessType: 'READ', accepts: [ @@ -20,7 +20,13 @@ module.exports = Self => { }, }); - Self.getPallet = async expeditionFk => { + Self.getPallet = async(ctx, expeditionFk, options) => { + const myOptions = {}; + const $t = ctx.req.__; + + if (typeof options == 'object') + Object.assign(myOptions, options); + try { const pallet = await Self.findOne({ fields: ['truckFk'], @@ -35,7 +41,7 @@ module.exports = Self => { } } ], - }); + }, myOptions); if (pallet) { const truck = pallet.expeditionTruck(); @@ -46,7 +52,7 @@ module.exports = Self => { }; } - throw new UserError('palletDoesNotExist'); + throw new UserError($t('This pallet does not exist')); } catch (e) { return {message: e.message}; } diff --git a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js new file mode 100644 index 000000000..8ffc7d8c2 --- /dev/null +++ b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js @@ -0,0 +1,31 @@ +const {models} = require('vn-loopback/server/server'); + +fdescribe('expeditonPallet getPallet()', () => { + beforeAll(async() => { + ctx = { + accessToken: {userId: 9}, + req: { + headers: {origin: 'http://localhost'}, + __: value => value + } + }; + }); + + it('should obtain the pallet data', async() => { + const pallet = await models.ExpeditionPallet.getPallet(ctx, 1); + + expect(pallet).toBeDefined(); + expect(pallet.truckFk).toEqual(1); + expect(pallet.description).toEqual('BEST TRUCK IN FLEET'); + }); + + it('should throw an error when the pallet does not exist', async() => { + try { + await models.ExpeditionPallet.getPallet(ctx, 1); + } catch (e) { + const error = e; + + expect(error.message).toEqual('This pallet does not exist'); + } + }); +}); From bf13e85ecc4435df9c2ba99f32cc4f59e961f420 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 17 Jan 2024 12:14:38 +0100 Subject: [PATCH 047/150] fix: refs #6276 getFromSectorCollection --- .../back/methods/expedition-pallet/specs/getPallet.spec.js | 2 +- modules/ticket/back/methods/sale/getFromSectorCollection.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js index 8ffc7d8c2..8a451c917 100644 --- a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js +++ b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('expeditonPallet getPallet()', () => { +describe('expeditonPallet getPallet()', () => { beforeAll(async() => { ctx = { accessToken: {userId: 9}, diff --git a/modules/ticket/back/methods/sale/getFromSectorCollection.js b/modules/ticket/back/methods/sale/getFromSectorCollection.js index 9a1b52ed8..323474cb4 100644 --- a/modules/ticket/back/methods/sale/getFromSectorCollection.js +++ b/modules/ticket/back/methods/sale/getFromSectorCollection.js @@ -67,7 +67,8 @@ module.exports = Self => { longName: sale.longName, packingType: sale.itemPackingTypeFk, subName: sale.subName, - quantity: {saldo: sale.quantity}, + quantity: sale.quantity, + saldo: sale.quantity, trabajador: sale.workerCode, idMovimiento: sale.saleFk, salesPersonFk: sale.salesPersonFk, From 1fbb84ae9fc424ca03fc491f9db97600a1b8d147 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 17 Jan 2024 12:58:57 +0100 Subject: [PATCH 048/150] fix: refs #6276 itemShelving_return --- db/dump/fixtures.sql | 3 --- .../item/back/methods/item-shelving/return.js | 4 ++-- .../item-shelving/specs/return.spec.js | 19 +++++++++++++++++++ .../expedition-pallet/specs/getPallet.spec.js | 2 +- 4 files changed, 22 insertions(+), 6 deletions(-) create mode 100644 modules/item/back/methods/item-shelving/specs/return.spec.js diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 2b04327cf..bab0149e1 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3047,9 +3047,6 @@ INSERT INTO `vn`.`clientSms` (`id`, `clientFk`, `smsFk`, `ticketFk`) -- NEW WAREHOUSE -/* UPDATE vn.packaging - SET id='--' - WHERE id='pallet 100'; */ INSERT INTO vn.packaging VALUES('--', 2745600.00, 100.00, 120.00, 220.00, 0.00, 1, '2001-01-01 00:00:00.000', NULL, NULL, NULL, 0.00, 16, 0.00, 0, NULL, 0.00, NULL, NULL, 0, NULL, 0, 0); diff --git a/modules/item/back/methods/item-shelving/return.js b/modules/item/back/methods/item-shelving/return.js index 27bc39a50..61d695c48 100644 --- a/modules/item/back/methods/item-shelving/return.js +++ b/modules/item/back/methods/item-shelving/return.js @@ -50,7 +50,7 @@ module.exports = Self => { let itemShelvings = await models.ItemShelving.find(filterItemShelvings, myOptions); - const alternatives = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)', [shelvingFk]); + const [alternatives] = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)', [shelvingFk]); if (itemShelvings) { itemShelvings = itemShelvings.map(itemShelving => { @@ -58,7 +58,7 @@ module.exports = Self => { const shelving = itemShelving.shelving(); const parking = shelving ? shelving.parking() : null; - const carros = alternatives.filter(el => el.item == itemShelving.itemFk); + const carros = alternatives.filter(el => el.itemFk == itemShelving.itemFk); return { id: itemShelving.id, diff --git a/modules/item/back/methods/item-shelving/specs/return.spec.js b/modules/item/back/methods/item-shelving/specs/return.spec.js new file mode 100644 index 000000000..35676a6ac --- /dev/null +++ b/modules/item/back/methods/item-shelving/specs/return.spec.js @@ -0,0 +1,19 @@ +const {models} = require('vn-loopback/server/server'); + +describe('itemShelving return()', () => { + beforeAll(async() => { + ctx = { + accessToken: {userId: 9}, + req: { + headers: {origin: 'http://localhost'}, + } + }; + }); + + it('should return a list of items and alternative locations', async() => { + const itemShelvings = await models.itemShelving.return('HEJ'); + + expect(itemShelvings).toBeDefined(); + // WIP + }); +}); diff --git a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js index 8a451c917..84bb9f93a 100644 --- a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js +++ b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js @@ -21,7 +21,7 @@ describe('expeditonPallet getPallet()', () => { it('should throw an error when the pallet does not exist', async() => { try { - await models.ExpeditionPallet.getPallet(ctx, 1); + await models.ExpeditionPallet.getPallet(ctx, 600); } catch (e) { const error = e; From 6be2f07c2278a7b49977b05217adf0f30d05b11d Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 17 Jan 2024 13:57:57 +0100 Subject: [PATCH 049/150] fix: refs #6276 assignCollection --- back/methods/collection/assignCollection.js | 1 + back/methods/collection/spec/assignCollection.spec.js | 0 2 files changed, 1 insertion(+) create mode 100644 back/methods/collection/spec/assignCollection.spec.js diff --git a/back/methods/collection/assignCollection.js b/back/methods/collection/assignCollection.js index e63e6c1d0..3384b325a 100644 --- a/back/methods/collection/assignCollection.js +++ b/back/methods/collection/assignCollection.js @@ -9,6 +9,7 @@ module.exports = Self => { }, returns: { type: ['object'], + root: true }, }); diff --git a/back/methods/collection/spec/assignCollection.spec.js b/back/methods/collection/spec/assignCollection.spec.js new file mode 100644 index 000000000..e69de29bb From c0398d17bf5465689e404b4cd3a603bb034a8b10 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 17 Jan 2024 14:21:50 +0100 Subject: [PATCH 050/150] feat: refs #6276 test itemShelving_return --- .../item/back/methods/item-shelving/return.js | 31 ++++--------------- .../item-shelving/specs/return.spec.js | 21 ++++++++++--- 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/modules/item/back/methods/item-shelving/return.js b/modules/item/back/methods/item-shelving/return.js index 61d695c48..aa44ef5b5 100644 --- a/modules/item/back/methods/item-shelving/return.js +++ b/modules/item/back/methods/item-shelving/return.js @@ -25,7 +25,7 @@ module.exports = Self => { Object.assign(myOptions, options); const filterItemShelvings = { - fields: ['id', 'visible', 'itemFk', 'packing', 'grouping', 'isChecked', 'shelvingFk'], + fields: ['id', 'visible', 'itemFk', 'shelvingFk'], where: {shelvingFk}, include: [ { @@ -34,47 +34,28 @@ module.exports = Self => { fields: ['longName', 'name', 'size'] } }, - { - relation: 'shelving', - scope: { - include: { - fields: ['id', 'name', 'code'], - relation: 'parking', - } - - } - }, ] }; let itemShelvings = await models.ItemShelving.find(filterItemShelvings, myOptions); - - const [alternatives] = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)', [shelvingFk]); + const [alternatives] = await models.ItemShelving.rawSql( + 'CALL vn.itemShelving_getAlternatives(?)', [shelvingFk] + ); if (itemShelvings) { - itemShelvings = itemShelvings.map(itemShelving => { + return itemShelvings.map(itemShelving => { const item = itemShelving.item(); - const shelving = itemShelving.shelving(); - const parking = shelving ? shelving.parking() : null; - - const carros = alternatives.filter(el => el.itemFk == itemShelving.itemFk); + const carros = alternatives.filter(alternative => alternative.itemFk == itemShelving.itemFk); return { id: itemShelving.id, itemFk: itemShelving.itemFk, longName: item ? item.longName || `${item.name} ${item.size}` : '', quantity: itemShelving.visible, - stickers: Math.ceil(itemShelving.visible / itemShelving.packing), - packing: itemShelving.packing, - grouping: itemShelving.grouping, - code: parking ? parking.code : '', - priority: shelving ? shelving.priority : 0, - isChecked: itemShelving.isChecked, carros }; }); } - return itemShelvings; }; }; diff --git a/modules/item/back/methods/item-shelving/specs/return.spec.js b/modules/item/back/methods/item-shelving/specs/return.spec.js index 35676a6ac..996491992 100644 --- a/modules/item/back/methods/item-shelving/specs/return.spec.js +++ b/modules/item/back/methods/item-shelving/specs/return.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -describe('itemShelving return()', () => { +fdescribe('itemShelving return()', () => { beforeAll(async() => { ctx = { accessToken: {userId: 9}, @@ -11,9 +11,22 @@ describe('itemShelving return()', () => { }); it('should return a list of items and alternative locations', async() => { - const itemShelvings = await models.itemShelving.return('HEJ'); + const itemShelvings = await models.ItemShelving.return('PCC'); - expect(itemShelvings).toBeDefined(); - // WIP + expect(itemShelvings[0].itemFk).toEqual(999997); + expect(itemShelvings[0].quantity).toEqual(10); + expect(itemShelvings[0].carros.length).toEqual(1); + }); + + it('should return a list of items without alternatives', async() => { + const itemShelvings = await models.ItemShelving.return('HEJ'); + + expect(itemShelvings[0].carros.length).toEqual(0); + }); + + it('should return an empty list', async() => { + const itemShelvings = await models.ItemShelving.return('ZZP'); + + expect(itemShelvings.length).toEqual(0); }); }); From 8e5be5f5da73c2c447a13a9d959229455f477516 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 17 Jan 2024 15:26:04 +0100 Subject: [PATCH 051/150] feat: refs #6276 test itemBarcode_delete --- .../methods/item-barcode/specs/delete.spec.js | 22 +++++++++++++++++++ .../item-shelving/specs/return.spec.js | 11 ++++++---- .../expedition-pallet/specs/getPallet.spec.js | 6 +++-- 3 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 modules/item/back/methods/item-barcode/specs/delete.spec.js diff --git a/modules/item/back/methods/item-barcode/specs/delete.spec.js b/modules/item/back/methods/item-barcode/specs/delete.spec.js new file mode 100644 index 000000000..56377eb78 --- /dev/null +++ b/modules/item/back/methods/item-barcode/specs/delete.spec.js @@ -0,0 +1,22 @@ +const {models} = require('vn-loopback/server/server'); + +fdescribe('itemBarcode delete()', () => { + it('should delete a record by itemFk and code', async() => { + const tx = await models.ItemBarcode.beginTransaction({}); + const options = {transaction: tx}; + const itemFk = 1; + const code = 1111111111; + + try { + const itemsBarcodeBefore = await models.ItemBarcode.find({}, options); + await models.ItemBarcode.delete(code, itemFk, options); + const itemsBarcodeAfter = await models.ItemBarcode.find({}, options); + + expect(itemsBarcodeBefore.length).toBeGreaterThan(itemsBarcodeAfter.length); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/item/back/methods/item-shelving/specs/return.spec.js b/modules/item/back/methods/item-shelving/specs/return.spec.js index 996491992..e5ed0aa85 100644 --- a/modules/item/back/methods/item-shelving/specs/return.spec.js +++ b/modules/item/back/methods/item-shelving/specs/return.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('itemShelving return()', () => { +describe('itemShelving return()', () => { beforeAll(async() => { ctx = { accessToken: {userId: 9}, @@ -11,7 +11,8 @@ fdescribe('itemShelving return()', () => { }); it('should return a list of items and alternative locations', async() => { - const itemShelvings = await models.ItemShelving.return('PCC'); + const shelvingFk = 'PCC'; + const itemShelvings = await models.ItemShelving.return(shelvingFk); expect(itemShelvings[0].itemFk).toEqual(999997); expect(itemShelvings[0].quantity).toEqual(10); @@ -19,13 +20,15 @@ fdescribe('itemShelving return()', () => { }); it('should return a list of items without alternatives', async() => { - const itemShelvings = await models.ItemShelving.return('HEJ'); + const shelvingFk = 'HEJ'; + const itemShelvings = await models.ItemShelving.return(shelvingFk); expect(itemShelvings[0].carros.length).toEqual(0); }); it('should return an empty list', async() => { - const itemShelvings = await models.ItemShelving.return('ZZP'); + const shelvingFk = 'ZZP'; + const itemShelvings = await models.ItemShelving.return(shelvingFk); expect(itemShelvings.length).toEqual(0); }); diff --git a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js index 84bb9f93a..2fc79d459 100644 --- a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js +++ b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js @@ -12,7 +12,8 @@ describe('expeditonPallet getPallet()', () => { }); it('should obtain the pallet data', async() => { - const pallet = await models.ExpeditionPallet.getPallet(ctx, 1); + const palletId = 1; + const pallet = await models.ExpeditionPallet.getPallet(ctx, palletId); expect(pallet).toBeDefined(); expect(pallet.truckFk).toEqual(1); @@ -20,8 +21,9 @@ describe('expeditonPallet getPallet()', () => { }); it('should throw an error when the pallet does not exist', async() => { + const palletId = 600; try { - await models.ExpeditionPallet.getPallet(ctx, 600); + await models.ExpeditionPallet.getPallet(ctx, palletId); } catch (e) { const error = e; From 6f35c62cd55d5350f9dc8e8e8b52bda6b2d31a51 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 18 Jan 2024 11:51:21 +0100 Subject: [PATCH 052/150] feat: refs #6276 test collection_addItem --- back/methods/collection/addItem.js | 3 +- back/methods/collection/spec/addItem.spec.js | 56 +++++++++++++++++++ .../collection/spec/assignCollection.spec.js | 0 .../methods/item-barcode/specs/delete.spec.js | 2 +- 4 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 back/methods/collection/spec/addItem.spec.js delete mode 100644 back/methods/collection/spec/assignCollection.spec.js diff --git a/back/methods/collection/addItem.js b/back/methods/collection/addItem.js index d3afbd71b..26eb9cc27 100644 --- a/back/methods/collection/addItem.js +++ b/back/methods/collection/addItem.js @@ -34,6 +34,7 @@ module.exports = Self => { Self.addItem = async(ctx, code, quantity, ticketFk, warehouseFk, options) => { const models = Self.app.models; const myOptions = {}; + const $t = ctx.req.__; let tx; if (typeof options == 'object') @@ -47,7 +48,7 @@ module.exports = Self => { try { const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [code, warehouseFk]); - if (!item.available) throw new UserError('We do not have availability for the selected item'); + if (!item?.available) throw new UserError($t('We do not have availability for the selected item')); await models.Ticket.addSale(ctx, ticketFk, item.id, quantity, myOptions); diff --git a/back/methods/collection/spec/addItem.spec.js b/back/methods/collection/spec/addItem.spec.js new file mode 100644 index 000000000..58cc97610 --- /dev/null +++ b/back/methods/collection/spec/addItem.spec.js @@ -0,0 +1,56 @@ +const {models} = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); + +fdescribe('collection addItem()', () => { + const quantity = 3; + const ticketFk = 24; + const warehouseFk = 1; + beforeAll(async() => { + activeCtx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'http://localhost'}, + __: value => value + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); + + it('should add a new sale', async() => { + const tx = await models.Sale.beginTransaction({}); + + try { + const options = {transaction: tx}; + const code = '1111111111'; + + const salesBefore = await models.Sale.find(null, options); + await models.Collection.addItem(activeCtx, code, quantity, ticketFk, warehouseFk, options); + const salesAfter = await models.Sale.find(null, options); + + expect(salesAfter.length).toEqual(salesBefore.length + 1); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an error when the item is not available', async() => { + const code = '00000000000'; + const tx = await models.Sale.beginTransaction({}); + + try { + const options = {transaction: tx}; + + await models.Collection.addItem(activeCtx, code, quantity, ticketFk, warehouseFk, options); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + const error = e; + + expect(error.message).toEqual('We do not have availability for the selected item'); + } + }); +}); diff --git a/back/methods/collection/spec/assignCollection.spec.js b/back/methods/collection/spec/assignCollection.spec.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/modules/item/back/methods/item-barcode/specs/delete.spec.js b/modules/item/back/methods/item-barcode/specs/delete.spec.js index 56377eb78..094a351a3 100644 --- a/modules/item/back/methods/item-barcode/specs/delete.spec.js +++ b/modules/item/back/methods/item-barcode/specs/delete.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('itemBarcode delete()', () => { +describe('itemBarcode delete()', () => { it('should delete a record by itemFk and code', async() => { const tx = await models.ItemBarcode.beginTransaction({}); const options = {transaction: tx}; From c8bfb35cf663a49ac0f1423bd4caebf3e7f6d87d Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 18 Jan 2024 13:28:22 +0100 Subject: [PATCH 053/150] feat: refs #6276 test itemShelvingMake_multi --- back/methods/collection/addItem.js | 2 +- back/methods/collection/spec/addItem.spec.js | 2 +- loopback/locale/en.json | 3 +- loopback/locale/es.json | 3 +- .../back/methods/item-shelving/makeMulti.js | 4 +- .../item-shelving/specs/makeMulti.spec.js | 54 +++++++++++++++++++ 6 files changed, 62 insertions(+), 6 deletions(-) create mode 100644 modules/item/back/methods/item-shelving/specs/makeMulti.spec.js diff --git a/back/methods/collection/addItem.js b/back/methods/collection/addItem.js index 26eb9cc27..3b2a6921b 100644 --- a/back/methods/collection/addItem.js +++ b/back/methods/collection/addItem.js @@ -6,7 +6,7 @@ module.exports = Self => { accepts: [ { arg: 'code', - type: 'number', + type: 'string', required: true }, { diff --git a/back/methods/collection/spec/addItem.spec.js b/back/methods/collection/spec/addItem.spec.js index 58cc97610..199aae588 100644 --- a/back/methods/collection/spec/addItem.spec.js +++ b/back/methods/collection/spec/addItem.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); -fdescribe('collection addItem()', () => { +describe('collection addItem()', () => { const quantity = 3; const ticketFk = 24; const warehouseFk = 1; diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 391034126..e3d08326e 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -205,5 +205,6 @@ "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}", "Incorrect pin": "Incorrect pin.", "This machine is already in use.": "This machine is already in use.", - "This pallet does not exist": "This pallet does not exist" + "This pallet does not exist": "This pallet does not exist", + "We do not have availability for the selected item": "We do not have availability for the selected item" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index b273f7506..45de30904 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -341,5 +341,6 @@ "No hay tickets para sacar": "No hay tickets para sacar", "There is no zone for these parameters 999999": "There is no zone for these parameters 999999", "This machine is already in use.": "Esta máquina ya está en uso.", - "This pallet does not exist": "Este palet no existe" + "This pallet does not exist": "Este palet no existe", + "We do not have availability for the selected item": "No tenemos disponible el item seleccionado", } \ No newline at end of file diff --git a/modules/item/back/methods/item-shelving/makeMulti.js b/modules/item/back/methods/item-shelving/makeMulti.js index e4393e4de..7d1ee11a0 100644 --- a/modules/item/back/methods/item-shelving/makeMulti.js +++ b/modules/item/back/methods/item-shelving/makeMulti.js @@ -47,10 +47,10 @@ module.exports = Self => { }, 0); discardItems.push(item); - let [result] = await Self.rawSql('SELECT vn.itemPacking(?, ?)', [item, warehouseFk]); + const [result] = await Self.rawSql('SELECT vn.itemPacking(?, ?) itemPacking', [item, warehouseFk]); let packing; - if (result) packing = Object.values(result)[0]; + if (result) packing = result.itemPacking; if (!packing) packing = 1; quantity = quantity * packing; diff --git a/modules/item/back/methods/item-shelving/specs/makeMulti.spec.js b/modules/item/back/methods/item-shelving/specs/makeMulti.spec.js new file mode 100644 index 000000000..f64a815f2 --- /dev/null +++ b/modules/item/back/methods/item-shelving/specs/makeMulti.spec.js @@ -0,0 +1,54 @@ +const {models} = require('vn-loopback/server/server'); + +describe('item makeMulti()', () => { + const warehouseFk = 1; + + beforeAll(async() => { + ctx = { + accessToken: {userId: 9}, + req: { + headers: {origin: 'http://localhost'}, + } + }; + }); + + it('should add two new records', async() => { + const shelvingFk = 'ZPP'; + const items = [1, 1, 1, 2]; + const tx = await models.ItemShelving.beginTransaction({}); + const options = {transaction: tx}; + + try { + await models.ItemShelving.makeMulti(shelvingFk, items, warehouseFk, options); + const itemShelvings = await models.ItemShelving.find({where: {shelvingFk}}, options); + + expect(itemShelvings.length).toEqual(2); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should update the visible items', async() => { + const shelvingFk = 'GVC'; + const items = [2, 2]; + const tx = await models.ItemShelving.beginTransaction({}); + const options = {transaction: tx}; + try { + const {visible: itemsBefore} = await models.ItemShelving.findOne({ + where: {shelvingFk, itemFk: items[0]} + }, options); + await models.ItemShelving.makeMulti(shelvingFk, items, warehouseFk, options); + const {visible: itemsAfter} = await models.ItemShelving.findOne({ + where: {shelvingFk, itemFk: items[0]} + }, options); + + expect(itemsAfter).toEqual(itemsBefore + 2); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); From 19edd7868e630ee34f4655f63533136844c8b453 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 18 Jan 2024 14:18:21 +0100 Subject: [PATCH 054/150] feat: refs #6276 test getVersion --- .../specs/getVersion.spec.js | 29 +++++++++++++++++++ .../{235001 => 240601}/00-newWareHouse.sql | 0 db/dump/fixtures.sql | 8 +++-- 3 files changed, 34 insertions(+), 3 deletions(-) create mode 100644 back/methods/mobile-app-version-control/specs/getVersion.spec.js rename db/changes/{235001 => 240601}/00-newWareHouse.sql (100%) diff --git a/back/methods/mobile-app-version-control/specs/getVersion.spec.js b/back/methods/mobile-app-version-control/specs/getVersion.spec.js new file mode 100644 index 000000000..e0c517387 --- /dev/null +++ b/back/methods/mobile-app-version-control/specs/getVersion.spec.js @@ -0,0 +1,29 @@ +const {models} = require('vn-loopback/server/server'); + +describe('mobileAppVersionControl getVersion()', () => { + const appName = 'delivery'; + beforeAll(async() => { + ctx = { + req: { + accessToken: {}, + headers: {origin: 'http://localhost'}, + } + }; + }); + + it('should get the version app', async() => { + ctx.req.accessToken.userId = 9; + const {version, versionBeta} = await models.MobileAppVersionControl.getVersion(ctx, appName); + + expect(version).toEqual('9.2'); + expect(versionBeta).toBeUndefined(); + }); + + it('should get the beta version app', async() => { + const {version, versionBeta} = await models.MobileAppVersionControl.getVersion(ctx, appName); + ctx.req.accessToken.userId = 66; + + expect(versionBeta).toBeDefined(); + expect(version).toBeUndefined(); + }); +}); diff --git a/db/changes/235001/00-newWareHouse.sql b/db/changes/240601/00-newWareHouse.sql similarity index 100% rename from db/changes/235001/00-newWareHouse.sql rename to db/changes/240601/00-newWareHouse.sql diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index bab0149e1..c0bd72912 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2716,10 +2716,10 @@ INSERT INTO `vn`.`chat` (`senderFk`, `recipient`, `dated`, `checkUserStatus`, `m (1101, '@PetterParker', util.VN_CURDATE(), 0, 'Second test message', 0, 'pending'); -INSERT INTO `vn`.`mobileAppVersionControl` (`appName`, `version`, `isVersionCritical`) +INSERT INTO `vn`.`mobileAppVersionControl` (`appName`, `version`, `isVersionCritical`,`versionBeta`) VALUES - ('delivery', '9.2', 0), - ('warehouse', '8.1', 0); + ('delivery', '9.2', 0,'9.7'), + ('warehouse', '8.1', 0,'8.3'); INSERT INTO `vn`.`machine` (`plate`, `maker`, `model`, `warehouseFk`, `departmentFk`, `type`, `use`, `productionYear`, `workerFk`, `companyFk`) VALUES @@ -3699,3 +3699,5 @@ UPDATE vn.sale INSERT INTO machineWorkerConfig(maxHours) VALUES(12); + +INSERT INTO workerAppTester(workerFk) VALUES(66) From b33594e0daccf5af6c5c59ce4ece657db45bc2aa Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 18 Jan 2024 14:35:51 +0100 Subject: [PATCH 055/150] fix: refs #6276 item_card & wip test --- modules/item/back/methods/item/card.js | 7 +++---- modules/item/back/methods/item/specs/card.spec.js | 12 ++++++++++++ 2 files changed, 15 insertions(+), 4 deletions(-) create mode 100644 modules/item/back/methods/item/specs/card.spec.js diff --git a/modules/item/back/methods/item/card.js b/modules/item/back/methods/item/card.js index 41d134f3b..dec6047a7 100644 --- a/modules/item/back/methods/item/card.js +++ b/modules/item/back/methods/item/card.js @@ -30,14 +30,13 @@ module.exports = Self => { const [result] = await Self.rawSql('CALL vn.item_getInfo(?, ?)', [itemFk, warehouseFk]); const barcodeItems = await Self.rawSql('SELECT vn.barcodeToItem(?) as realIdItem', [itemFk]); - const realIdItems = barcodeItems.map(barcodeItem => barcodeItem.realIdItem); + const [realIdItem] = barcodeItems.map(barcodeItem => barcodeItem.realIdItem); const barcodes = await models.ItemBarcode.find({ fields: ['code'], where: { - realIdItem: { - inq: realIdItems - } + itemFk: realIdItem + } }); diff --git a/modules/item/back/methods/item/specs/card.spec.js b/modules/item/back/methods/item/specs/card.spec.js new file mode 100644 index 000000000..433384261 --- /dev/null +++ b/modules/item/back/methods/item/specs/card.spec.js @@ -0,0 +1,12 @@ +const {models} = require('vn-loopback/server/server'); + +fdescribe('item card()', () => { + const itemFk = 1; + const warehouseFk = 1; + it('WIP: should get something', async() => { + const card = await models.Item.card(itemFk, warehouseFk); + + expect(card).toBeDefined(); + expect(card.barcodes); + }); +}); From 34420375cdc3ea3bc6e1adc8fd821bf5b6dc8155 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 18 Jan 2024 15:03:17 +0100 Subject: [PATCH 056/150] feat: refs #6276 test item_updateFromSale --- .../specs/updateFromSale.spec.js | 22 +++++++++++++++++++ .../item/back/methods/item/specs/card.spec.js | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 modules/item/back/methods/item-shelving/specs/updateFromSale.spec.js diff --git a/modules/item/back/methods/item-shelving/specs/updateFromSale.spec.js b/modules/item/back/methods/item-shelving/specs/updateFromSale.spec.js new file mode 100644 index 000000000..dfa294000 --- /dev/null +++ b/modules/item/back/methods/item-shelving/specs/updateFromSale.spec.js @@ -0,0 +1,22 @@ +const {models} = require('vn-loopback/server/server'); + +describe('itemShelving updateFromSale()', () => { + it('should update the quantity', async() => { + const tx = await models.ItemBarcode.beginTransaction({}); + const options = {transaction: tx}; + const saleFk = 2; + const filter = {where: {itemFk: 4, shelvingFk: 'HEJ'} + }; + try { + const {visible: visibleBefore} = await models.ItemShelving.findOne(filter, options); + await models.ItemShelving.updateFromSale(saleFk, options); + const {visible: visibleAfter} = await models.ItemShelving.findOne(filter, options); + + expect(visibleAfter).toEqual(visibleBefore + 5); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/item/back/methods/item/specs/card.spec.js b/modules/item/back/methods/item/specs/card.spec.js index 433384261..725a4269d 100644 --- a/modules/item/back/methods/item/specs/card.spec.js +++ b/modules/item/back/methods/item/specs/card.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('item card()', () => { +describe('item card()', () => { const itemFk = 1; const warehouseFk = 1; it('WIP: should get something', async() => { From 5c0425b942eb9d27bd4e545dface76f32c24418e Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 19 Jan 2024 09:52:49 +0100 Subject: [PATCH 057/150] feat: refs #6276 test machineWorker_update --- .../machine-worker/specs/updateInTime.spec.js | 116 ++++++++++++++++++ back/methods/machine-worker/updateInTime.js | 10 +- db/dump/fixtures.sql | 10 +- loopback/locale/en.json | 1 + loopback/locale/es.json | 2 + .../item-shelving/specs/return.spec.js | 1 - modules/item/back/methods/item/card.js | 2 +- .../expedition-pallet/specs/getPallet.spec.js | 1 - 8 files changed, 136 insertions(+), 7 deletions(-) create mode 100644 back/methods/machine-worker/specs/updateInTime.spec.js diff --git a/back/methods/machine-worker/specs/updateInTime.spec.js b/back/methods/machine-worker/specs/updateInTime.spec.js new file mode 100644 index 000000000..aee1c9187 --- /dev/null +++ b/back/methods/machine-worker/specs/updateInTime.spec.js @@ -0,0 +1,116 @@ +const {models} = require('vn-loopback/server/server'); + +fdescribe('machineWorker updateInTime()', () => { + const itBoss = 104; + const davidCharles = 1106; + + beforeAll(async() => { + ctx = { + req: { + accessToken: {}, + headers: {origin: 'http://localhost'}, + __: value => value + } + }; + }); + + it('should throw an error if the plate does not exist', async() => { + const tx = await models.MachineWorker.beginTransaction({}); + const options = {transaction: tx}; + const plate = 'RE-123'; + ctx.req.accessToken.userId = 1106; + try { + await models.MachineWorker.updateInTime(ctx, plate, options); + await tx.rollback(); + } catch (e) { + const error = e; + + expect(error.message).toContain('the plate does not exist'); + await tx.rollback(); + } + }); + + it('should grab a machine where is not in use', async() => { + const tx = await models.MachineWorker.beginTransaction({}); + const options = {transaction: tx}; + const plate = 'RE-003'; + ctx.req.accessToken.userId = 1107; + try { + const totalBefore = await models.MachineWorker.find(null, options); + await models.MachineWorker.updateInTime(ctx, plate, options); + const totalAfter = await models.MachineWorker.find(null, options); + + expect(totalAfter.length).toEqual(totalBefore.length + 1); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } + }); + + describe('less than 12h', () => { + const plate = 'RE-001'; + it('should trow an error if it is not himself', async() => { + const tx = await models.MachineWorker.beginTransaction({}); + const options = {transaction: tx}; + ctx.req.accessToken.userId = davidCharles; + + try { + await models.MachineWorker.updateInTime(ctx, plate, options); + await tx.rollback(); + } catch (e) { + const error = e; + + expect(error.message).toContain('This machine is already in use'); + await tx.rollback(); + } + }); + + it('should set the out time if it is himself', async() => { + const tx = await models.MachineWorker.beginTransaction({}); + const options = {transaction: tx}; + ctx.req.accessToken.userId = itBoss; + + try { + const isNotParked = await models.MachineWorker.findOne({ + where: {workerFk: itBoss} + }, options); + await models.MachineWorker.updateInTime(ctx, plate, options); + const isParked = await models.MachineWorker.findOne({ + where: {workerFk: itBoss} + }, options); + + expect(isNotParked.outTime).toBeNull(); + expect(isParked.outTime).toBeDefined(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } + }); + }); + + describe('equal or more than 12h', () => { + const plate = 'RE-002'; + it('should set the out time and grab the machine', async() => { + const tx = await models.MachineWorker.beginTransaction({}); + const options = {transaction: tx}; + ctx.req.accessToken.userId = davidCharles; + const filter = { + where: {workerFk: davidCharles, machineFk: 2} + }; + try { + const isNotParked = await models.MachineWorker.findOne(filter, options); + const totalBefore = await models.MachineWorker.find(null, options); + await models.MachineWorker.updateInTime(ctx, plate, options); + const isParked = await models.MachineWorker.findOne(filter, options); + const totalAfter = await models.MachineWorker.find(null, options); + + expect(isNotParked.outTime).toBeNull(); + expect(isParked.outTime).toBeDefined(); + expect(totalAfter.length).toEqual(totalBefore.length + 1); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } + }); + }); +}); diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index 705bcdd92..eebb09990 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -18,6 +18,7 @@ module.exports = Self => { Self.updateInTime = async(ctx, plate, options) => { const models = Self.app.models; const userId = ctx.req.accessToken.userId; + const $t = ctx.req.__; let tx; const myOptions = {}; @@ -35,11 +36,13 @@ module.exports = Self => { fields: ['id', 'plate'], where: {plate} }, myOptions); - if (!machine) throw new Error(`plate ${plate} does not exist.`); + + if (!machine) + throw new Error($t('the plate does not exist', {plate})); const machineWorker = await Self.findOne({ where: { - machineFk: machine.id, + or: [{machineFk: machine.id}, {workerFk: userId}], outTime: null, } }, myOptions); @@ -49,7 +52,8 @@ module.exports = Self => { const hoursDifference = (Date.vnNow() - machineWorker.inTime.getTime()) / (60 * 60 * 1000); const isHimSelf = userId == machineWorker.workerFk; - if (maxHours > hoursDifference && !isHimSelf) throw new UserError('This machine is already in use.'); + if (maxHours > hoursDifference && !isHimSelf) + throw new UserError($t('This machine is already in use.')); await machineWorker.updateAttributes({ outTime: Date.vnNew() diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index c0bd72912..9fc4d4fb1 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3700,4 +3700,12 @@ UPDATE vn.sale INSERT INTO machineWorkerConfig(maxHours) VALUES(12); -INSERT INTO workerAppTester(workerFk) VALUES(66) +INSERT INTO workerAppTester(workerFk) VALUES(66); + +INSERT INTO `vn`.`machine` (`plate`, `maker`, `model`, `warehouseFk`, `departmentFk`, `type`, `use`, `productionYear`, `workerFk`, `companyFk`) + VALUES + ('RE-003', 'IRON', 'JPH-24', 60, 23, 'ELECTRIC TOW', 'Drag cars', 2020, 103, 442); + + +INSERT INTO machineWorker(workerFk,machineFk,inTimed) + VALUES (104,1,'2001-01-01 10:00:00.00.000'); \ No newline at end of file diff --git a/loopback/locale/en.json b/loopback/locale/en.json index e3d08326e..a6c3b4ee4 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -205,6 +205,7 @@ "It was not able to remove the next expeditions:": "It was not able to remove the next expeditions: {{expeditions}}", "Incorrect pin": "Incorrect pin.", "This machine is already in use.": "This machine is already in use.", + "the plate does not exist": "The plate {{plate}} does not exist", "This pallet does not exist": "This pallet does not exist", "We do not have availability for the selected item": "We do not have availability for the selected item" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 45de30904..e13a8dab9 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -341,6 +341,8 @@ "No hay tickets para sacar": "No hay tickets para sacar", "There is no zone for these parameters 999999": "There is no zone for these parameters 999999", "This machine is already in use.": "Esta máquina ya está en uso.", + "the plate does not exist": "La máquina {{plate}} no existe", "This pallet does not exist": "Este palet no existe", "We do not have availability for the selected item": "No tenemos disponible el item seleccionado", + "Esta máquina ya está en uso.": "Esta máquina ya está en uso." } \ No newline at end of file diff --git a/modules/item/back/methods/item-shelving/specs/return.spec.js b/modules/item/back/methods/item-shelving/specs/return.spec.js index e5ed0aa85..c8acd6ab9 100644 --- a/modules/item/back/methods/item-shelving/specs/return.spec.js +++ b/modules/item/back/methods/item-shelving/specs/return.spec.js @@ -3,7 +3,6 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving return()', () => { beforeAll(async() => { ctx = { - accessToken: {userId: 9}, req: { headers: {origin: 'http://localhost'}, } diff --git a/modules/item/back/methods/item/card.js b/modules/item/back/methods/item/card.js index dec6047a7..45c2ac36c 100644 --- a/modules/item/back/methods/item/card.js +++ b/modules/item/back/methods/item/card.js @@ -1,6 +1,6 @@ module.exports = Self => { Self.remoteMethod('card', { - description: 'Idk', + description: 'Get the data from an item', accessType: 'READ', http: { path: `/card`, diff --git a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js index 2fc79d459..497fe04bb 100644 --- a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js +++ b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js @@ -3,7 +3,6 @@ const {models} = require('vn-loopback/server/server'); describe('expeditonPallet getPallet()', () => { beforeAll(async() => { ctx = { - accessToken: {userId: 9}, req: { headers: {origin: 'http://localhost'}, __: value => value From b7ce6cac9c20ee77823fec60689546b58ef7b47c Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 19 Jan 2024 12:38:58 +0100 Subject: [PATCH 058/150] fix: refs #6276 machineWorker_update & tests --- .../machine-worker/specs/updateInTime.spec.js | 18 +++++++++++++++++- back/methods/machine-worker/updateInTime.js | 8 ++++++-- .../specs/getVersion.spec.js | 2 +- loopback/locale/en.json | 4 +++- loopback/locale/es.json | 3 ++- 5 files changed, 29 insertions(+), 6 deletions(-) diff --git a/back/methods/machine-worker/specs/updateInTime.spec.js b/back/methods/machine-worker/specs/updateInTime.spec.js index aee1c9187..f166214b0 100644 --- a/back/methods/machine-worker/specs/updateInTime.spec.js +++ b/back/methods/machine-worker/specs/updateInTime.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('machineWorker updateInTime()', () => { +describe('machineWorker updateInTime()', () => { const itBoss = 104; const davidCharles = 1106; @@ -65,6 +65,22 @@ fdescribe('machineWorker updateInTime()', () => { } }); + it('should throw an error if it is himself with a different machine', async() => { + const tx = await models.MachineWorker.beginTransaction({}); + const options = {transaction: tx}; + ctx.req.accessToken.userId = itBoss; + const plate = 'RE-003'; + try { + await models.MachineWorker.updateInTime(ctx, plate, options); + await tx.rollback(); + } catch (e) { + const error = e; + + expect(error.message).toEqual('You are already using a machine'); + await tx.rollback(); + } + }); + it('should set the out time if it is himself', async() => { const tx = await models.MachineWorker.beginTransaction({}); const options = {transaction: tx}; diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index eebb09990..706f1a80e 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -51,15 +51,19 @@ module.exports = Self => { const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); const hoursDifference = (Date.vnNow() - machineWorker.inTime.getTime()) / (60 * 60 * 1000); const isHimSelf = userId == machineWorker.workerFk; + const isSameMachine = machine.id == machineWorker.machineFk; - if (maxHours > hoursDifference && !isHimSelf) + if (hoursDifference < maxHours && !isHimSelf) throw new UserError($t('This machine is already in use.')); + if (hoursDifference < maxHours && isHimSelf && !isSameMachine) + throw new UserError($t('You are already using a machine')); + await machineWorker.updateAttributes({ outTime: Date.vnNew() }, myOptions); - if (maxHours <= hoursDifference) + if (hoursDifference >= maxHours) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); } else await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); diff --git a/back/methods/mobile-app-version-control/specs/getVersion.spec.js b/back/methods/mobile-app-version-control/specs/getVersion.spec.js index e0c517387..59d794ccf 100644 --- a/back/methods/mobile-app-version-control/specs/getVersion.spec.js +++ b/back/methods/mobile-app-version-control/specs/getVersion.spec.js @@ -20,8 +20,8 @@ describe('mobileAppVersionControl getVersion()', () => { }); it('should get the beta version app', async() => { - const {version, versionBeta} = await models.MobileAppVersionControl.getVersion(ctx, appName); ctx.req.accessToken.userId = 66; + const {version, versionBeta} = await models.MobileAppVersionControl.getVersion(ctx, appName); expect(versionBeta).toBeDefined(); expect(version).toBeUndefined(); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index a6c3b4ee4..b10ea2e71 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -207,5 +207,7 @@ "This machine is already in use.": "This machine is already in use.", "the plate does not exist": "The plate {{plate}} does not exist", "This pallet does not exist": "This pallet does not exist", - "We do not have availability for the selected item": "We do not have availability for the selected item" + "We do not have availability for the selected item": "We do not have availability for the selected item", + "You are already using a machine": "You are already using a machine" + } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index e13a8dab9..c704cb8fd 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -344,5 +344,6 @@ "the plate does not exist": "La máquina {{plate}} no existe", "This pallet does not exist": "Este palet no existe", "We do not have availability for the selected item": "No tenemos disponible el item seleccionado", - "Esta máquina ya está en uso.": "Esta máquina ya está en uso." + "You are already using a machine": "Ya estás usando una máquina.", + "Ya estás usando una máquina.": "Ya estás usando una máquina." } \ No newline at end of file From 817a6b1289cb27aeda9567dc56c831e7dc180739 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 19 Jan 2024 14:35:10 +0100 Subject: [PATCH 059/150] feat: refs #6276 test operator_add --- loopback/locale/en.json | 4 +-- loopback/locale/es.json | 3 +- modules/worker/back/methods/operator/add.js | 22 +++++++++++++-- .../back/methods/operator/spec/add.spec.js | 28 +++++++++++++++++++ 4 files changed, 51 insertions(+), 6 deletions(-) create mode 100644 modules/worker/back/methods/operator/spec/add.spec.js diff --git a/loopback/locale/en.json b/loopback/locale/en.json index b10ea2e71..c22aeb311 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -208,6 +208,6 @@ "the plate does not exist": "The plate {{plate}} does not exist", "This pallet does not exist": "This pallet does not exist", "We do not have availability for the selected item": "We do not have availability for the selected item", - "You are already using a machine": "You are already using a machine" - + "You are already using a machine": "You are already using a machine", + "This worker does not exist": "This worker does not exist" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index c704cb8fd..e5293d856 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -345,5 +345,6 @@ "This pallet does not exist": "Este palet no existe", "We do not have availability for the selected item": "No tenemos disponible el item seleccionado", "You are already using a machine": "Ya estás usando una máquina.", - "Ya estás usando una máquina.": "Ya estás usando una máquina." + "This worker does not exist": "Este trabajador no existe", + "Este trabajador no existe": "Este trabajador no existe" } \ No newline at end of file diff --git a/modules/worker/back/methods/operator/add.js b/modules/worker/back/methods/operator/add.js index eaf74e7b4..d330bc25b 100644 --- a/modules/worker/back/methods/operator/add.js +++ b/modules/worker/back/methods/operator/add.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('add', { description: 'Add a new operator', @@ -8,13 +9,28 @@ module.exports = Self => { } }); - Self.add = async ctx => { + Self.add = async(ctx, options) => { const userId = ctx.req.accessToken.userId; - const user = await Self.findById(userId); - if (!user) { + const myOptions = {}; + const $t = ctx.req.__; + let tx; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { await Self.create({ workerFk: userId }); + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw new UserError($t('This worker does not exist')); } }; }; diff --git a/modules/worker/back/methods/operator/spec/add.spec.js b/modules/worker/back/methods/operator/spec/add.spec.js new file mode 100644 index 000000000..c2b244ada --- /dev/null +++ b/modules/worker/back/methods/operator/spec/add.spec.js @@ -0,0 +1,28 @@ +const {models} = require('vn-loopback/server/server'); + +describe('operator add()', () => { + beforeAll(async() => { + ctx = { + req: { + accessToken: {userId: 100000}, + headers: {origin: 'http://localhost'}, + __: value => value + } + }; + }); + + it('should throw an error if the worker does not exist', async() => { + const tx = await models.Operator.beginTransaction({}); + const options = {transaction: tx}; + + try { + await models.Operator.add(ctx, options); + await tx.rollback(); + } catch (e) { + const error = e; + + expect(error.message).toEqual('This worker does not exist'); + await tx.rollback(); + } + }); +}); From 6e59a87f9c10ef74424aba63dcda25bd1adbb88b Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 19 Jan 2024 14:44:07 +0100 Subject: [PATCH 060/150] feat: refs #6276 test operator_add --- .../back/methods/operator/spec/add.spec.js | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/modules/worker/back/methods/operator/spec/add.spec.js b/modules/worker/back/methods/operator/spec/add.spec.js index c2b244ada..4d26e8ca9 100644 --- a/modules/worker/back/methods/operator/spec/add.spec.js +++ b/modules/worker/back/methods/operator/spec/add.spec.js @@ -1,10 +1,13 @@ const {models} = require('vn-loopback/server/server'); describe('operator add()', () => { + const itBoss = 104; + const noWorker = 100000; + beforeAll(async() => { ctx = { req: { - accessToken: {userId: 100000}, + accessToken: {}, headers: {origin: 'http://localhost'}, __: value => value } @@ -14,6 +17,7 @@ describe('operator add()', () => { it('should throw an error if the worker does not exist', async() => { const tx = await models.Operator.beginTransaction({}); const options = {transaction: tx}; + ctx.req.accessToken.userId = noWorker; try { await models.Operator.add(ctx, options); @@ -25,4 +29,25 @@ describe('operator add()', () => { await tx.rollback(); } }); + + it('should add a new operator successfully', async() => { + const tx = await models.Operator.beginTransaction({}); + const options = {transaction: tx}; + ctx.req.accessToken.userId = itBoss; + + try { + const operatorBefore = await models.Operator.find(null, options); + await models.Operator.add(ctx, options); + const operatorAfter = await models.Operator.find(null, options); + + const isOperator = await models.Operator.findOne(null, options); + + expect(operatorBefore.length).toEqual(operatorAfter.length - 1); + expect(isOperator).toBeDefined(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); From 428da6fe00c84168394f7fb71d2c4e7ee6051b03 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 19 Jan 2024 14:50:33 +0100 Subject: [PATCH 061/150] feat: refs #6276 drop worker_getPrinter --- .../back/methods/operator/getPrinter.js | 38 ------------------- 1 file changed, 38 deletions(-) delete mode 100644 modules/worker/back/methods/operator/getPrinter.js diff --git a/modules/worker/back/methods/operator/getPrinter.js b/modules/worker/back/methods/operator/getPrinter.js deleted file mode 100644 index 88e7d8090..000000000 --- a/modules/worker/back/methods/operator/getPrinter.js +++ /dev/null @@ -1,38 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('getPrinter', { - description: 'Gets user\'s printer', - accessType: 'READ', - http: { - path: `/getPrinter`, - verb: 'GET' - }, - returns: { - type: ['object'], - root: true - }, - }); - - Self.getPrinter = async ctx => { - const userId = ctx.req.accessToken.userId; - - const operator = await Self.findOne({ - include: [ - { - relation: 'printer', - scope: { - fields: ['id', 'name'], - } - } - ], - where: { - workerFk: userId - } - }); - - if (operator) { - const printer = operator.printer(); - return Array.isArray(printer) ? printer : [printer]; - } - return []; - }; -}; From d78e90687e51a0ad990b543f9b9161e45f9ae691 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 19 Jan 2024 14:51:03 +0100 Subject: [PATCH 062/150] fix: refs #6276 drop worker_getPrinter --- modules/worker/back/models/operator.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index 5e8870130..b4569d7f5 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -1,6 +1,5 @@ module.exports = Self => { require('../methods/operator/add')(Self); - require('../methods/operator/getPrinter')(Self); require('../methods/operator/getAvailablePrinters')(Self); Self.observe('after save', async function(ctx) { From f8faa958e66f29cf83f4de2ee14a0a7f164fd801 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 19 Jan 2024 14:53:41 +0100 Subject: [PATCH 063/150] feat: refs #6276 drop worker_getPrinter --- .../methods/operator/getAvailablePrinters.js | 39 ------------------- modules/worker/back/models/operator.js | 1 - 2 files changed, 40 deletions(-) delete mode 100644 modules/worker/back/methods/operator/getAvailablePrinters.js diff --git a/modules/worker/back/methods/operator/getAvailablePrinters.js b/modules/worker/back/methods/operator/getAvailablePrinters.js deleted file mode 100644 index 2e787da2b..000000000 --- a/modules/worker/back/methods/operator/getAvailablePrinters.js +++ /dev/null @@ -1,39 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('getAvailablePrinters', { - description: 'Retrieve available printers for an user', - accessType: 'READ', - http: { - path: `/getAvailabePrinters`, - verb: 'GET' - }, - returns: { - type: ['object'], - }, - }); - - Self.getAvailablePrinters = async ctx => { - const userId = ctx.req.accessToken.userId; - - const operators = await Self.find({ - fields: [], - where: { - workerFk: userId, - }, - - include: { - relation: 'printer', - scope: { - fields: ['id', 'name'] - }, - where: { - isLabeler: {neq: 0} - } - } - }); - if (operators.length) { - return operators.map(operator => { - return operator.printer(); - }); - } - }; -}; diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index b4569d7f5..442ac343f 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -1,6 +1,5 @@ module.exports = Self => { require('../methods/operator/add')(Self); - require('../methods/operator/getAvailablePrinters')(Self); Self.observe('after save', async function(ctx) { const instance = ctx.data || ctx.instance; From 89d18e29f0f338b776e6a437bbfb31fc76cd2172 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 22 Jan 2024 07:49:21 +0100 Subject: [PATCH 064/150] feat: refs #6276 test saleTrackingReplace (updateTracking) --- db/dump/fixtures.sql | 12 ++- .../specs/updateTracking.spec.js | 78 +++++++++++++++++++ .../methods/sale-tracking/updateTracking.js | 29 ++++--- modules/ticket/back/models/sale-buy.json | 8 +- 4 files changed, 109 insertions(+), 18 deletions(-) create mode 100644 modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 9fc4d4fb1..04846435f 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3697,15 +3697,19 @@ UPDATE vn.collection UPDATE vn.sale SET isPicked =FALSE; -INSERT INTO machineWorkerConfig(maxHours) +INSERT INTO vn.machineWorkerConfig(maxHours) VALUES(12); -INSERT INTO workerAppTester(workerFk) VALUES(66); +INSERT INTO vn.workerAppTester(workerFk) VALUES(66); INSERT INTO `vn`.`machine` (`plate`, `maker`, `model`, `warehouseFk`, `departmentFk`, `type`, `use`, `productionYear`, `workerFk`, `companyFk`) VALUES ('RE-003', 'IRON', 'JPH-24', 60, 23, 'ELECTRIC TOW', 'Drag cars', 2020, 103, 442); -INSERT INTO machineWorker(workerFk,machineFk,inTimed) - VALUES (104,1,'2001-01-01 10:00:00.00.000'); \ No newline at end of file +INSERT INTO vn.machineWorker(workerFk,machineFk,inTimed) + VALUES (104,1,'2001-01-01 10:00:00.00.000'); + +UPDATE vn.buy + SET itemOriginalFk = 1 + WHERE id = 1; \ No newline at end of file diff --git a/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js b/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js new file mode 100644 index 000000000..2756bc09e --- /dev/null +++ b/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js @@ -0,0 +1,78 @@ +const {models} = require('vn-loopback/server/server'); + +fdescribe('saleTracking updateTracking()', () => { + const saleFk = 1; + const originalQuantity = 10; + const code = 'PREPARED'; + const isChecked = true; + const buyFk = 1; + const isScanned = false; + + beforeAll(async() => { + ctx = { + req: { + accessToken: {userId: 104}, + headers: {origin: 'http://localhost'}, + } + }; + }); + + it('should add a new saleTracking and saleBuy', async() => { + const tx = await models.SaleTracking.beginTransaction({}); + const options = {transaction: tx}; + + try { + const saleTrackingBefore = await models.SaleTracking.find(null, options); + const saleBuyBefore = await models.SaleBuy.find(null, options); + await models.SaleTracking.updateTracking( + ctx, + saleFk, + originalQuantity, + code, + isChecked, + buyFk, + isScanned, + options + ); + + const saleTrackingAfter = await models.SaleTracking.find(null, options); + const saleBuyAfter = await models.SaleBuy.find(null, options); + + expect(saleTrackingAfter.length).toEqual(saleTrackingBefore.length + 1); + expect(saleBuyAfter.length).toEqual(saleBuyBefore.length + 1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should only update a saleTracking', async() => { + const tx = await models.SaleTracking.beginTransaction({}); + const options = {transaction: tx}; + const saleFk = 2; + + try { + const saleTrackingBefore = await models.SaleTracking.find(null, options); + await models.SaleTracking.updateTracking( + ctx, + saleFk, + originalQuantity, + code, + isChecked, + buyFk, + isScanned, + options + ); + const saleTrackingAfter = await models.SaleTracking.find(null, options); + + expect(saleTrackingAfter.length).toEqual(saleTrackingBefore.length + 1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/ticket/back/methods/sale-tracking/updateTracking.js b/modules/ticket/back/methods/sale-tracking/updateTracking.js index 453b0b0c6..7cb2b4a58 100644 --- a/modules/ticket/back/methods/sale-tracking/updateTracking.js +++ b/modules/ticket/back/methods/sale-tracking/updateTracking.js @@ -39,7 +39,7 @@ module.exports = Self => { } }); - Self.updateTracking = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned, options) => { + Self.updateTracking = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned = null, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; const myOptions = {}; @@ -58,24 +58,31 @@ module.exports = Self => { where: {code}, }, myOptions); - const attributes = { + const uniqueAttributes = { saleFk, + workerFk: userId, + stateFk: state?.id, + }; + const attributes = { isChecked, originalQuantity, - workerFk: userId, - stateFk: state.id, - isScanned: isScanned === undefined ? null : isScanned, + isScanned }; const saleTracking = await models.SaleTracking.findOne({ - where: attributes, + where: uniqueAttributes, }, myOptions); - if (!saleTracking) - await models.SaleTracking.create(attributes, myOptions); - - else - await saleTracking.updateAttributes(attributes, myOptions); + if (!saleTracking) { + await models.SaleTracking.create({ + ...uniqueAttributes, + ...attributes + }, myOptions); + } else { + await saleTracking.updateAttributes({ + ...attributes + }, myOptions); + } let isBuy; if (buyFk) { diff --git a/modules/ticket/back/models/sale-buy.json b/modules/ticket/back/models/sale-buy.json index 5279e6787..60ff2bef4 100644 --- a/modules/ticket/back/models/sale-buy.json +++ b/modules/ticket/back/models/sale-buy.json @@ -17,9 +17,6 @@ }, "created": { "type": "date" - }, - "isChecked": { - "type": "number" } }, "relations": { @@ -27,6 +24,11 @@ "type": "belongsTo", "model": "Sale", "foreignKey": "saleFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" } } } From f04724a61f6a9c924de9ec4998486651435b8d50 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 22 Jan 2024 07:58:18 +0100 Subject: [PATCH 065/150] feat: refs #6276 new test added --- loopback/locale/en.json | 4 ++- loopback/locale/es.json | 3 +- .../specs/updateTracking.spec.js | 28 ++++++++++++++++++- .../methods/sale-tracking/updateTracking.js | 3 ++ 4 files changed, 35 insertions(+), 3 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index c22aeb311..0f1be5776 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -209,5 +209,7 @@ "This pallet does not exist": "This pallet does not exist", "We do not have availability for the selected item": "We do not have availability for the selected item", "You are already using a machine": "You are already using a machine", - "This worker does not exist": "This worker does not exist" + "This worker does not exist": "This worker does not exist", + "this state does not exist": "This state does not exist" + } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index e5293d856..158d351df 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -346,5 +346,6 @@ "We do not have availability for the selected item": "No tenemos disponible el item seleccionado", "You are already using a machine": "Ya estás usando una máquina.", "This worker does not exist": "Este trabajador no existe", - "Este trabajador no existe": "Este trabajador no existe" + "this state does not exist": "Este estado no existe", + "Este estado no existe": "Este estado no existe" } \ No newline at end of file diff --git a/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js b/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js index 2756bc09e..a58a69fe7 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('saleTracking updateTracking()', () => { +describe('saleTracking updateTracking()', () => { const saleFk = 1; const originalQuantity = 10; const code = 'PREPARED'; @@ -13,10 +13,36 @@ fdescribe('saleTracking updateTracking()', () => { req: { accessToken: {userId: 104}, headers: {origin: 'http://localhost'}, + __: value => value } }; }); + it('should add a new saleTracking and saleBuy', async() => { + const tx = await models.SaleTracking.beginTransaction({}); + const options = {transaction: tx}; + const code = 'FAKESTATE'; + try { + await models.SaleTracking.updateTracking( + ctx, + saleFk, + originalQuantity, + code, + isChecked, + buyFk, + isScanned, + options + ); + + await tx.rollback(); + } catch (e) { + const error = e; + + expect(error.message).toEqual('this state does not exist'); + await tx.rollback(); + } + }); + it('should add a new saleTracking and saleBuy', async() => { const tx = await models.SaleTracking.beginTransaction({}); const options = {transaction: tx}; diff --git a/modules/ticket/back/methods/sale-tracking/updateTracking.js b/modules/ticket/back/methods/sale-tracking/updateTracking.js index 7cb2b4a58..81eef28b4 100644 --- a/modules/ticket/back/methods/sale-tracking/updateTracking.js +++ b/modules/ticket/back/methods/sale-tracking/updateTracking.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('updateTracking', { description: 'Modify a saleTracking record and, if applicable, add a corresponding record in saleBuy.', @@ -42,6 +43,7 @@ module.exports = Self => { Self.updateTracking = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned = null, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; + const $t = ctx.req.__; const myOptions = {}; let tx; @@ -58,6 +60,7 @@ module.exports = Self => { where: {code}, }, myOptions); + if (!state) throw new UserError($t('this state does not exist')); const uniqueAttributes = { saleFk, workerFk: userId, From ed713e762b1f346d4c05088c51277c6e9493ab0e Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 22 Jan 2024 12:36:52 +0100 Subject: [PATCH 066/150] feat: refs #6276 test saleTracking_mark --- .vscode/settings.json | 3 +- loopback/locale/en.json | 4 +- loopback/locale/es.json | 5 +- loopback/server/connectors/vn-mysql.js | 8 +- .../ticket/back/methods/sale-tracking/mark.js | 24 +++--- .../methods/sale-tracking/specs/mark.spec.js | 76 +++++++++++++++++++ .../specs/updateTracking.spec.js | 2 +- 7 files changed, 100 insertions(+), 22 deletions(-) create mode 100644 modules/ticket/back/methods/sale-tracking/specs/mark.spec.js diff --git a/.vscode/settings.json b/.vscode/settings.json index 03479d27a..76b039f61 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -18,5 +18,6 @@ "salix", "fdescribe", "Loggable" - ] + ], + "CodeGPT.apiKey": "CodeGPT Plus Beta" } diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 0f1be5776..6b48fcb98 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -210,6 +210,8 @@ "We do not have availability for the selected item": "We do not have availability for the selected item", "You are already using a machine": "You are already using a machine", "This worker does not exist": "This worker does not exist", - "this state does not exist": "This state does not exist" + "this state does not exist": "This state does not exist", + "The line could not be marked": "The line could not be marked" + } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 158d351df..9d6404dac 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -331,7 +331,6 @@ "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", "Cannot past travels with entries": "No se pueden pasar envíos con entradas", "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", - "The line could not be marked": "The line could not be marked", "This claim has been updated": "La reclamación con Id: {{claimId}}, ha sido actualizada", "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada", "Incorrect pin": "Pin incorrecto.", @@ -347,5 +346,7 @@ "You are already using a machine": "Ya estás usando una máquina.", "This worker does not exist": "Este trabajador no existe", "this state does not exist": "Este estado no existe", - "Este estado no existe": "Este estado no existe" + "Este estado no existe": "Este estado no existe", + "The line could not be marked": "No se ha podido marcar la línea", + "No se ha podido marcar la línea": "No se ha podido marcar la línea" } \ No newline at end of file diff --git a/loopback/server/connectors/vn-mysql.js b/loopback/server/connectors/vn-mysql.js index 1f7169501..7c086ff9b 100644 --- a/loopback/server/connectors/vn-mysql.js +++ b/loopback/server/connectors/vn-mysql.js @@ -268,14 +268,8 @@ class VnMySQL extends MySQL { arguments, model, ctx, opts, cb); } - isLoggable(model) { - const Model = this.getModelDefinition(model).model; - const {settings} = Model.definition; - return settings?.mixins?.Loggable; - } - invokeMethod(method, args, model, ctx, opts, cb) { - if (!this.isLoggable(model)) + if (!opts?.httpCtx) return super[method].apply(this, args); this.invokeMethodP(method, [...args], model, ctx, opts) diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/mark.js index 327421673..0ca674e39 100644 --- a/modules/ticket/back/methods/sale-tracking/mark.js +++ b/modules/ticket/back/methods/sale-tracking/mark.js @@ -54,6 +54,7 @@ module.exports = Self => { Self.mark = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned, quantity, itemShelvingFk, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; + const $t = ctx.req.__; const myOptions = {}; let tx; @@ -73,15 +74,9 @@ module.exports = Self => { userFk: userId }, myOptions); - const itemShelving = await models.ItemShelving.findOne({ - where: { - id: itemShelvingFk - } - }, myOptions); + const itemShelving = await models.ItemShelving.findById(itemShelvingFk, myOptions); - await itemShelving.updateAttributes({ - visible: itemShelving.visible - quantity} - , myOptions); + await itemShelving.updateAttributes({visible: itemShelving.visible - quantity}, myOptions); await Self.updateAll( {saleFk}, @@ -89,12 +84,21 @@ module.exports = Self => { myOptions ); - await Self.updateTracking(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned, myOptions); + await Self.updateTracking(ctx, saleFk, originalQuantity, code, isChecked, null, isScanned, myOptions); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); - throw new UserError('The line could not be marked'); + throw new UserError($t('The line could not be marked')); } + + const buy = await models.Buy.findOne({ + where: { + id: buyFk, + itemOriginalFk: {neq: null} + } + }); + + if (buy) await models.SaleBuy.create({saleFk, buyFk}); }; }; diff --git a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js new file mode 100644 index 000000000..dfc790b91 --- /dev/null +++ b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js @@ -0,0 +1,76 @@ +const {models} = require('vn-loopback/server/server'); +fdescribe('saleTracking mark()', () => { + const saleFk = 1; + const originalQuantity = 10; + const code = 'PREPARED'; + const isChecked = true; + const buyFk = 1; + const isScanned = false; + const quantity = 1; + const itemShelvingFk = 1; + + beforeAll(async() => { + ctx = { + req: { + accessToken: {userId: 104}, + headers: {origin: 'http://localhost'}, + __: value => value + } + }; + }); + + it('should throw an error if the line was not able to be marked', async() => { + const tx = await models.SaleTracking.beginTransaction({}); + const options = {transaction: tx}; + const code = 'FAKESTATE'; + try { + await models.SaleTracking.mark( + ctx, + saleFk, + originalQuantity, + code, + isChecked, + buyFk, + isScanned, + quantity, + itemShelvingFk, + options + ); + + await tx.rollback(); + } catch (e) { + const error = e; + + expect(error.message).toEqual('The line could not be marked'); + await tx.rollback(); + } + }); + + it('should add an itemShelvingSale and Modify a saleTracking', async() => { + const tx = await models.SaleTracking.beginTransaction({}); + const options = {transaction: tx}; + try { + const itemShelvingSaleBefore = await models.ItemShelvingSale.find({}, options); + await models.SaleTracking.mark( + ctx, + saleFk, + originalQuantity, + code, + isChecked, + buyFk, + isScanned, + quantity, + itemShelvingFk, + options + ); + const itemShelvingSaleAfter = await models.ItemShelvingSale.find({}, options); + const saleTracking = await models.SaleTracking.findOne({where: {saleFk, isChecked: false}}, options); + + expect(itemShelvingSaleAfter.length).toEqual(itemShelvingSaleBefore.length + 1); + expect(saleTracking.isChecked).toBeFalse(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + } + }); +}); diff --git a/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js b/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js index a58a69fe7..44bd1a60a 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/updateTracking.spec.js @@ -18,7 +18,7 @@ describe('saleTracking updateTracking()', () => { }; }); - it('should add a new saleTracking and saleBuy', async() => { + it('should throw an error if the state does not exist', async() => { const tx = await models.SaleTracking.beginTransaction({}); const options = {transaction: tx}; const code = 'FAKESTATE'; From e3899b2cf70fd28ecd3c40e17ec58576b81dc177 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 22 Jan 2024 13:32:50 +0100 Subject: [PATCH 067/150] refactor: refs #6276 saleTracking_mark --- modules/ticket/back/methods/sale-tracking/mark.js | 14 +++++--------- .../back/methods/sale-tracking/specs/mark.spec.js | 2 +- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/mark.js index 0ca674e39..c8c73b935 100644 --- a/modules/ticket/back/methods/sale-tracking/mark.js +++ b/modules/ticket/back/methods/sale-tracking/mark.js @@ -86,19 +86,15 @@ module.exports = Self => { await Self.updateTracking(ctx, saleFk, originalQuantity, code, isChecked, null, isScanned, myOptions); + try { + const buy = await models.Buy.findById(buyFk, myOptions); + if (buy.itemOriginalFk) await models.SaleBuy.create({saleFk, buyFk}, myOptions); + } catch (e) {} + if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); throw new UserError($t('The line could not be marked')); } - - const buy = await models.Buy.findOne({ - where: { - id: buyFk, - itemOriginalFk: {neq: null} - } - }); - - if (buy) await models.SaleBuy.create({saleFk, buyFk}); }; }; diff --git a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js index dfc790b91..49e4ec6e5 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js @@ -1,5 +1,5 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('saleTracking mark()', () => { +describe('saleTracking mark()', () => { const saleFk = 1; const originalQuantity = 10; const code = 'PREPARED'; From efb8bc46c668b1646f4de1830bf4673e03f6c327 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 22 Jan 2024 15:13:49 +0100 Subject: [PATCH 068/150] refactor: refs #6276 saleTracking_mark --- loopback/locale/en.json | 5 +-- loopback/locale/es.json | 3 +- .../ticket/back/methods/sale-tracking/mark.js | 9 ++++- .../methods/sale-tracking/specs/mark.spec.js | 40 ++++++++++++++++++- .../methods/sale/getFromSectorCollection.js | 9 +++-- 5 files changed, 57 insertions(+), 9 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 6b48fcb98..24c28a927 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -211,7 +211,6 @@ "You are already using a machine": "You are already using a machine", "This worker does not exist": "This worker does not exist", "this state does not exist": "This state does not exist", - "The line could not be marked": "The line could not be marked" - - + "The line could not be marked": "The line could not be marked", + "The sale can not be tracked": "The sale can not be tracked" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 9d6404dac..25fbbda70 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -348,5 +348,6 @@ "this state does not exist": "Este estado no existe", "Este estado no existe": "Este estado no existe", "The line could not be marked": "No se ha podido marcar la línea", - "No se ha podido marcar la línea": "No se ha podido marcar la línea" + "No se ha podido marcar la línea": "No se ha podido marcar la línea", + "The sale can not be tracked": "La línea no puede ser rastreada" } \ No newline at end of file diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/mark.js index c8c73b935..dc288ba93 100644 --- a/modules/ticket/back/methods/sale-tracking/mark.js +++ b/modules/ticket/back/methods/sale-tracking/mark.js @@ -89,10 +89,17 @@ module.exports = Self => { try { const buy = await models.Buy.findById(buyFk, myOptions); if (buy.itemOriginalFk) await models.SaleBuy.create({saleFk, buyFk}, myOptions); - } catch (e) {} + } catch (e) { + throw new UserError($t('The sale can not be tracked')); + } if (tx) await tx.commit(); } catch (e) { + if (e.message == $t('The sale can not be tracked')) { + if (tx) tx.commit(); + throw e; + } + if (tx) await tx.rollback(); throw new UserError($t('The line could not be marked')); } diff --git a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js index 49e4ec6e5..353a39c49 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js @@ -1,5 +1,5 @@ const {models} = require('vn-loopback/server/server'); -describe('saleTracking mark()', () => { +fdescribe('saleTracking mark()', () => { const saleFk = 1; const originalQuantity = 10; const code = 'PREPARED'; @@ -46,6 +46,44 @@ describe('saleTracking mark()', () => { } }); + it('should throw an error if there are duplicate salebuys', async() => { + const tx = await models.SaleTracking.beginTransaction({}); + const options = {transaction: tx}; + try { + await models.SaleTracking.mark( + ctx, + saleFk, + originalQuantity, + code, + isChecked, + buyFk, + isScanned, + quantity, + itemShelvingFk, + options + ); + + await models.SaleTracking.mark( + ctx, + saleFk, + originalQuantity, + code, + isChecked, + buyFk, + isScanned, + quantity, + itemShelvingFk, + options + ); + await tx.rollback(); + } catch (e) { + const error = e; + + expect(error.message).toEqual('The sale can not be tracked'); + await tx.rollback(); + } + }); + it('should add an itemShelvingSale and Modify a saleTracking', async() => { const tx = await models.SaleTracking.beginTransaction({}); const options = {transaction: tx}; diff --git a/modules/ticket/back/methods/sale/getFromSectorCollection.js b/modules/ticket/back/methods/sale/getFromSectorCollection.js index 323474cb4..a56966887 100644 --- a/modules/ticket/back/methods/sale/getFromSectorCollection.js +++ b/modules/ticket/back/methods/sale/getFromSectorCollection.js @@ -30,7 +30,9 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const sales = await Self.rawSql( + const sales = await Self.rawSql('CALL sectorCollection_getSale(?)', [sectorCollectionFk], myOptions); + + /* const sales = await Self.rawSql( `SELECT s.ticketFk, s.itemFk, i.longName, @@ -52,13 +54,14 @@ module.exports = Self => { JOIN client c ON c.id=t.clientFk LEFT JOIN itemShelvingSaleSum iss ON iss.saleFk = s.id WHERE scsg.sectorCollectionFk = ? - AND st.workerFk = ?;`, [sectorCollectionFk, userId]); + AND st.workerFk = ?;`, [sectorCollectionFk, userId]); */ const itemShelvings = []; for (let sale of sales) { const [carros] = await Self.rawSql( 'CALL vn.itemPlacementSupplyStockGetTargetList(?, ?)', - [sale.itemFk, sectorFk] + [sale.itemFk, sectorFk], + myOptions ); itemShelvings.push({ From dcf6232c1403c2621e8a854bd15a5ab4c0e12392 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 23 Jan 2024 08:39:30 +0100 Subject: [PATCH 069/150] feat: refs #6276 test sale_getFromSectorCollection --- db/dump/fixtures.sql | 9 +++--- loopback/locale/es.json | 3 +- .../methods/sale-tracking/specs/mark.spec.js | 2 +- .../methods/sale/getFromSectorCollection.js | 28 ++----------------- .../specs/getFromSectorCollection.spec.js | 23 +++++++++++++++ 5 files changed, 32 insertions(+), 33 deletions(-) create mode 100644 modules/ticket/back/methods/sale/specs/getFromSectorCollection.spec.js diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 04846435f..e536e694d 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3707,9 +3707,8 @@ INSERT INTO `vn`.`machine` (`plate`, `maker`, `model`, `warehouseFk`, `departmen ('RE-003', 'IRON', 'JPH-24', 60, 23, 'ELECTRIC TOW', 'Drag cars', 2020, 103, 442); -INSERT INTO vn.machineWorker(workerFk,machineFk,inTimed) - VALUES (104,1,'2001-01-01 10:00:00.00.000'); +INSERT INTO vn.machineWorker(workerFk,machineFk,inTimed) VALUES (104,1,'2001-01-01 10:00:00.00.000'); -UPDATE vn.buy - SET itemOriginalFk = 1 - WHERE id = 1; \ No newline at end of file +UPDATE vn.buy SET itemOriginalFk = 1 WHERE id = 1; + +UPDATE vn.saleTracking SET stateFk = 26 WHERE id = 5; \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 25fbbda70..91374a34e 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -349,5 +349,6 @@ "Este estado no existe": "Este estado no existe", "The line could not be marked": "No se ha podido marcar la línea", "No se ha podido marcar la línea": "No se ha podido marcar la línea", - "The sale can not be tracked": "La línea no puede ser rastreada" + "The sale can not be tracked": "La línea no puede ser rastreada", + "La línea no puede ser rastreada": "La línea no puede ser rastreada" } \ No newline at end of file diff --git a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js index 353a39c49..d981aeea5 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js @@ -1,5 +1,5 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('saleTracking mark()', () => { +describe('saleTracking mark()', () => { const saleFk = 1; const originalQuantity = 10; const code = 'PREPARED'; diff --git a/modules/ticket/back/methods/sale/getFromSectorCollection.js b/modules/ticket/back/methods/sale/getFromSectorCollection.js index a56966887..c8925c3a9 100644 --- a/modules/ticket/back/methods/sale/getFromSectorCollection.js +++ b/modules/ticket/back/methods/sale/getFromSectorCollection.js @@ -25,36 +25,12 @@ module.exports = Self => { }); Self.getFromSectorCollection = async(ctx, sectorCollectionFk, sectorFk, options) => { - const myOptions = {}; const userId = ctx.req.accessToken.userId; + const myOptions = {userId}; if (typeof options == 'object') Object.assign(myOptions, options); - const sales = await Self.rawSql('CALL sectorCollection_getSale(?)', [sectorCollectionFk], myOptions); - - /* const sales = await Self.rawSql( - `SELECT s.ticketFk, - s.itemFk, - i.longName, - itemPackingTypeFk, - subName, - s.quantity, - w.code workerCode, - sgd.saleFk, - iss.quantity pickedQuantity, - c.salesPersonFk - FROM vn.sale s - JOIN item i ON i.id = s.itemFk - JOIN saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sgd.saleGroupFk - JOIN saleTracking st ON st.saleFk = s.id - JOIN state stt ON stt.id = st.stateFk AND stt.code = 'PREVIOUS_PREPARATION' - JOIN worker w ON w.id = st.workerFk - JOIN ticket t ON t.id= s.ticketFk - JOIN client c ON c.id=t.clientFk - LEFT JOIN itemShelvingSaleSum iss ON iss.saleFk = s.id - WHERE scsg.sectorCollectionFk = ? - AND st.workerFk = ?;`, [sectorCollectionFk, userId]); */ + const [sales] = await Self.rawSql('CALL sectorCollection_getSale(?)', [sectorCollectionFk], myOptions); const itemShelvings = []; for (let sale of sales) { diff --git a/modules/ticket/back/methods/sale/specs/getFromSectorCollection.spec.js b/modules/ticket/back/methods/sale/specs/getFromSectorCollection.spec.js new file mode 100644 index 000000000..1501426e4 --- /dev/null +++ b/modules/ticket/back/methods/sale/specs/getFromSectorCollection.spec.js @@ -0,0 +1,23 @@ +const {models} = require('vn-loopback/server/server'); + +describe('sale getFromSectorCollection()', () => { + const sectorCollectionFk = 1; + const sectorFk = 1; + + beforeAll(async() => { + ctx = { + req: { + headers: {origin: 'http://localhost'}, + accessToken: {userId: 40} + } + }; + }); + + it('should find an item and a shelving', async() => { + const options = {}; + const itemShelvings = await models.Sale.getFromSectorCollection(ctx, sectorCollectionFk, sectorFk, options); + + expect(itemShelvings.length).toEqual(1); + expect(itemShelvings[0].carros.length).toEqual(1); + }); +}); From 799237e14caaea96ba135910651e6e5f2cffc4c7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 23 Jan 2024 09:09:55 +0100 Subject: [PATCH 070/150] feat: refs #6276 test shelving_addLog --- loopback/locale/en.json | 4 +- loopback/locale/es.json | 3 +- .../shelving/back/methods/shelving/addLog.js | 3 +- .../methods/shelving/specs/addLog.spec.js | 46 +++++++++++++++++++ 4 files changed, 53 insertions(+), 3 deletions(-) create mode 100644 modules/shelving/back/methods/shelving/specs/addLog.spec.js diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 24c28a927..dc3a4afae 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -212,5 +212,7 @@ "This worker does not exist": "This worker does not exist", "this state does not exist": "This state does not exist", "The line could not be marked": "The line could not be marked", - "The sale can not be tracked": "The sale can not be tracked" + "The sale can not be tracked": "The sale can not be tracked", + "Shelving not valid": "Shelving not valid" + } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 91374a34e..32266e9ce 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -350,5 +350,6 @@ "The line could not be marked": "No se ha podido marcar la línea", "No se ha podido marcar la línea": "No se ha podido marcar la línea", "The sale can not be tracked": "La línea no puede ser rastreada", - "La línea no puede ser rastreada": "La línea no puede ser rastreada" + "Shelving not valid": "Carro no válido", + "Carro no válido": "Carro no válido" } \ No newline at end of file diff --git a/modules/shelving/back/methods/shelving/addLog.js b/modules/shelving/back/methods/shelving/addLog.js index 13f9075f1..fe6d8b8da 100644 --- a/modules/shelving/back/methods/shelving/addLog.js +++ b/modules/shelving/back/methods/shelving/addLog.js @@ -16,6 +16,7 @@ module.exports = Self => { }); Self.addLog = async(ctx, code, options) => { const userId = ctx.req.accessToken.userId; + const $t = ctx.req.__; const models = Self.app.models; const myOptions = {}; let tx; @@ -35,7 +36,7 @@ module.exports = Self => { } }, myOptions); - if (!shelving) throw new UserError('Shelving not valid'); + if (!shelving) throw new UserError($t('Shelving not valid')); await models.ShelvingLog.create({ changedModel: 'Shelving', diff --git a/modules/shelving/back/methods/shelving/specs/addLog.spec.js b/modules/shelving/back/methods/shelving/specs/addLog.spec.js new file mode 100644 index 000000000..d538c24ec --- /dev/null +++ b/modules/shelving/back/methods/shelving/specs/addLog.spec.js @@ -0,0 +1,46 @@ +const {models} = require('vn-loopback/server/server'); + +describe('shelving addLog()', () => { + beforeAll(async() => { + ctx = { + req: { + headers: {origin: 'http://localhost'}, + accessToken: {userId: 66}, + __: value => value + } + }; + }); + + it('should add a log', async() => { + const tx = await models.SaleTracking.beginTransaction({}); + const options = {transaction: tx}; + const code = 'AA6'; + + try { + const shelvingLogsBefore = await models.ShelvingLog.find(null, options); + await models.Shelving.addLog(ctx, code, options); + const shelvingLogsAfter = await models.ShelvingLog.find(null, options); + + expect(shelvingLogsAfter.length).toEqual(shelvingLogsBefore.length + 1); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an error when the code does not exist', async() => { + const tx = await models.SaleTracking.beginTransaction({}); + const options = {transaction: tx}; + const code = 'DXI345'; + + try { + await models.Shelving.addLog(ctx, code, options); + + await tx.rollback(); + } catch (e) { + expect(e.message).toEqual('Shelving not valid'); + await tx.rollback(); + } + }); +}); From 08dd37e9e44fc1824bb3c383c38fd90746da55ff Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 23 Jan 2024 12:13:23 +0100 Subject: [PATCH 071/150] feat: refs #6276 test sectorCollection_getSales --- .../getSalesFromTicketOrCollection.js | 66 ++++++++++--------- .../getSalesFromTicketOrCollection.spec.js | 35 ++++++++++ db/dump/fixtures.sql | 4 +- loopback/locale/es.json | 3 +- 4 files changed, 76 insertions(+), 32 deletions(-) create mode 100644 back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js diff --git a/back/methods/collection/getSalesFromTicketOrCollection.js b/back/methods/collection/getSalesFromTicketOrCollection.js index d806782d9..68de62bd8 100644 --- a/back/methods/collection/getSalesFromTicketOrCollection.js +++ b/back/methods/collection/getSalesFromTicketOrCollection.js @@ -7,18 +7,11 @@ module.exports = Self => { arg: 'collectionOrTicketFk', type: 'number', required: true - }, - { - arg: 'sectorFk', - type: 'number', + }, { + arg: 'print', + type: 'boolean', required: true - }, - { - arg: 'printFk', - type: 'number', - required: true - }, - { + }, { arg: 'source', type: 'string', required: true @@ -35,36 +28,34 @@ module.exports = Self => { }, }); - Self.getSalesFromTicketOrCollection = async(ctx, collectionOrTicketFk, sectorFk, printFk, source, options) => { + Self.getSalesFromTicketOrCollection = async(ctx, collectionOrTicketFk, print, source, options) => { + const userId = ctx.req.accessToken.userId; const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId}; if (typeof options == 'object') Object.assign(myOptions, options); - const [collectionOrTicket] = await Self.rawSql('SELECT vn.ticket_get(?) as id', [collectionOrTicketFk]); + const [{id}] = await Self.rawSql('SELECT vn.ticket_get(?) as id', + [collectionOrTicketFk], + myOptions); - const [tickets] = await Self.rawSql('CALL vn.collection_getTickets(?)', [collectionOrTicket.id]); + const [tickets] = await Self.rawSql('CALL vn.collection_getTickets(?)', [id], myOptions); - if (source == 'PRECHECKER' || source == 'ON_CHECKING') { - await Self.rawSql( - 'CALL vn.ticketStateToday_setState(?,?)', - [collectionOrTicket.id, source] - ); - } - - const [sales] = await Self.rawSql('CALL vn.sale_getFromTicketOrCollection(?)', [collectionOrTicket.id]); + await setState(source, id, myOptions); + const [sales] = await Self.rawSql('CALL vn.sale_getFromTicketOrCollection(?)', + [id], myOptions); const isPicker = source == 'CHECKER'; - const [placements] = await Self.rawSql( - 'CALL vn.collectionPlacement_get(?, ?)', [collectionOrTicket.id, isPicker] + const [placements] = await Self.rawSql('CALL vn.collectionPlacement_get(?, ?)', + [id, isPicker], myOptions ); - if (printFk == 1) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [collectionOrTicket.id]); + if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); if (tickets.length) await sendRocketTickets(tickets); - return getCollection(collectionOrTicket.id, tickets, sales, placements); + return getCollection(id, tickets, sales, placements, myOptions); async function sendRocketTickets(tickets) { for (let ticket of tickets) { @@ -83,7 +74,7 @@ module.exports = Self => { } } - async function getCollection(id, tickets, sales, placements) { + async function getCollection(id, tickets, sales, placements, options) { const collection = { collectionFk: id, tickets: [], @@ -95,7 +86,8 @@ module.exports = Self => { const barcodes = await getBarcodes(ticketFk); await Self.rawSql( 'CALL util.log_add(?, ?, ?, ?, ?, ?, ?, ?)', - ['vn', 'ticket', 'Ticket', ticketFk, ticketFk, 'select', null, null] + ['vn', 'ticket', 'Ticket', ticketFk, ticketFk, 'select', null, null], + options ); for (let sale of sales) { @@ -106,7 +98,7 @@ module.exports = Self => { sale.barcodes = []; for (const barcode of barcodes) { - if (barcode.movementId) { + if (barcode.movementId == sale.saleFk) { if (barcode.code) { sale.barcodes.push(barcode.code); sale.barcodes.push(`0 ${barcode.code}`); @@ -142,5 +134,19 @@ module.exports = Self => { AND tr.landed >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)`; return Self.rawSql(query, [ticketId]); } + + async function setState(source, id, options) { + let state; + if (source == 'PRECHECKER') state = 'PREVIOUS_CONTROL'; + else if (source == 'CHECKER') state = 'ON_CHECKING'; + + if (state) { + await Self.rawSql( + 'CALL vn.ticketStateToday_setState(?,?)', + [id, source], + options + ); + } + } }; }; diff --git a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js new file mode 100644 index 000000000..8937b99e0 --- /dev/null +++ b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js @@ -0,0 +1,35 @@ +const {models} = require('vn-loopback/server/server'); + +fdescribe('collection getSalesFromTicketOrCollection()', () => { + const collectionOrTicketFk = 999999; + const print = true; + const source = 'CHECKER'; + + beforeAll(() => { + ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'http://localhost'}, + } + }; + }); + + it('should return a collection with tickets, placements and barcodes settled correctly', async() => { + const options = {}; + const collection = await models.Collection.getSalesFromTicketOrCollection(ctx, + collectionOrTicketFk, print, source, options); + + const [firstTicket] = collection.tickets; + const [firstSale] = firstTicket.sales; + const [firstPlacement] = firstSale.placements; + + expect(collection.tickets.length).toBeGreaterThan(0); + expect(collection.collectionFk).toEqual(firstTicket.ticketFk); + + expect(firstSale.ticketFk).toEqual(firstTicket.ticketFk); + expect(firstSale.placements.length).toBeGreaterThan(0); + expect(firstSale.barcodes.length).toBeGreaterThan(0); + + expect(firstSale.saleFk).toEqual(firstPlacement.saleFk); + }); +}); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index e536e694d..0485f9eec 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3711,4 +3711,6 @@ INSERT INTO vn.machineWorker(workerFk,machineFk,inTimed) VALUES (104,1,'2001-01- UPDATE vn.buy SET itemOriginalFk = 1 WHERE id = 1; -UPDATE vn.saleTracking SET stateFk = 26 WHERE id = 5; \ No newline at end of file +UPDATE vn.saleTracking SET stateFk = 26 WHERE id = 5; + +INSERT INTO vn.report (name) VALUES ('LabelCollection') \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 32266e9ce..222df46d6 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -351,5 +351,6 @@ "No se ha podido marcar la línea": "No se ha podido marcar la línea", "The sale can not be tracked": "La línea no puede ser rastreada", "Shelving not valid": "Carro no válido", - "Carro no válido": "Carro no válido" + "Carro no válido": "Carro no válido", + "printerNotExists": "printerNotExists" } \ No newline at end of file From ae89d59bde5d8e3c11c4d38bf9cec41094e642fc Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 23 Jan 2024 15:58:09 +0100 Subject: [PATCH 072/150] feat: refs #6276 WIP test sectorCollection_getSales --- .../getSalesFromTicketOrCollection.spec.js | 50 ++++++++++++++----- db/dump/fixtures.sql | 2 +- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js index 8937b99e0..6417fca93 100644 --- a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js +++ b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('collection getSalesFromTicketOrCollection()', () => { +describe('collection getSalesFromTicketOrCollection()', () => { const collectionOrTicketFk = 999999; const print = true; const source = 'CHECKER'; @@ -15,21 +15,45 @@ fdescribe('collection getSalesFromTicketOrCollection()', () => { }); it('should return a collection with tickets, placements and barcodes settled correctly', async() => { - const options = {}; - const collection = await models.Collection.getSalesFromTicketOrCollection(ctx, - collectionOrTicketFk, print, source, options); + const tx = await models.Collection.beginTransaction({}); + const options = {transaction: tx}; + try { + const collection = await models.Collection.getSalesFromTicketOrCollection(ctx, + collectionOrTicketFk, print, source, options); - const [firstTicket] = collection.tickets; - const [firstSale] = firstTicket.sales; - const [firstPlacement] = firstSale.placements; + const [firstTicket] = collection.tickets; + const [firstSale] = firstTicket.sales; + const [firstPlacement] = firstSale.placements; - expect(collection.tickets.length).toBeGreaterThan(0); - expect(collection.collectionFk).toEqual(firstTicket.ticketFk); + expect(collection.tickets.length).toBeTruthy(); + expect(collection.collectionFk).toEqual(firstTicket.ticketFk); - expect(firstSale.ticketFk).toEqual(firstTicket.ticketFk); - expect(firstSale.placements.length).toBeGreaterThan(0); - expect(firstSale.barcodes.length).toBeGreaterThan(0); + expect(firstSale.ticketFk).toEqual(firstTicket.ticketFk); + expect(firstSale.placements.length).toBeTruthy(); + expect(firstSale.barcodes.length).toBeTruthy(); - expect(firstSale.saleFk).toEqual(firstPlacement.saleFk); + expect(firstSale.saleFk).toEqual(firstPlacement.saleFk); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should print a sticker', async() => { + const tx = await models.Collection.beginTransaction({}); + const options = {transaction: tx}; + try { + const printQueueBefore = await models.Collection.rawSql('SELECT * FROM printQueue', [], options); + await models.Collection.getSalesFromTicketOrCollection(ctx, + collectionOrTicketFk, print, source, options); + const printQueueAfter = await models.Collection.rawSql('SELECT * FROM printQueue', [], options); + + expect(printQueueAfter.length).toEqual(printQueueBefore.length + 1); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 0485f9eec..2cdc6fbe0 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -3713,4 +3713,4 @@ UPDATE vn.buy SET itemOriginalFk = 1 WHERE id = 1; UPDATE vn.saleTracking SET stateFk = 26 WHERE id = 5; -INSERT INTO vn.report (name) VALUES ('LabelCollection') \ No newline at end of file +INSERT INTO vn.report (name) VALUES ('LabelCollection'); \ No newline at end of file From e849f0b6e2000896aa8782a2add236cba7cdad06 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 24 Jan 2024 11:20:08 +0100 Subject: [PATCH 073/150] fix: refs #6276 sectorCollection_getSales --- .../getSalesFromTicketOrCollection.js | 28 ++++++++++++++++--- .../getSalesFromTicketOrCollection.spec.js | 19 +++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/back/methods/collection/getSalesFromTicketOrCollection.js b/back/methods/collection/getSalesFromTicketOrCollection.js index 68de62bd8..50fe21875 100644 --- a/back/methods/collection/getSalesFromTicketOrCollection.js +++ b/back/methods/collection/getSalesFromTicketOrCollection.js @@ -92,9 +92,29 @@ module.exports = Self => { for (let sale of sales) { if (sale.ticketFk == ticketFk) { - sale.placements = placements.filter(placement => - placement.saleFk == sale.saleFk && placement.order - ); + sale.placements = []; + for (const salePlacement of placements) { + let placement; + if (salePlacement.saleFk == sale.saleFk && salePlacement.order) { + placement = { + saleFk: salePlacement.saleFk, + itemFk: salePlacement.itemFk, + placement: salePlacement.placement, + shelving: salePlacement.shelving, + created: salePlacement.created, + visible: salePlacement.visible, + order: salePlacement.order, + grouping: salePlacement.grouping, + priority: salePlacement.priority, + saleOrder: salePlacement.saleOrder, + isPreviousPrepared: salePlacement.isPreviousPrepared, + itemShelvingSaleFk: salePlacement.itemShelvingSaleFk, + ticketFk: salePlacement.ticketFk, + id: salePlacement.id + }; + sale.placements.push(placement); + } + } sale.barcodes = []; for (const barcode of barcodes) { @@ -143,7 +163,7 @@ module.exports = Self => { if (state) { await Self.rawSql( 'CALL vn.ticketStateToday_setState(?,?)', - [id, source], + [id, state], options ); } diff --git a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js index 6417fca93..02532b4b0 100644 --- a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js +++ b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js @@ -56,4 +56,23 @@ describe('collection getSalesFromTicketOrCollection()', () => { throw e; } }); + + it('should add a ticketTracking', async() => { + const collectionOrTicketFk = 23; + + const tx = await models.Collection.beginTransaction({}); + const options = {transaction: tx}; + try { + const ticketTrackingBefore = await models.TicketTracking.find(null, options); + await models.Collection.getSalesFromTicketOrCollection(ctx, + collectionOrTicketFk, print, source, options); + const ticketTrackingAfter = await models.TicketTracking.find(null, options); + + expect(ticketTrackingAfter.length).toEqual(ticketTrackingBefore.length + 1); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); From e527780622444504516b9724baa168beab345a98 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 24 Jan 2024 11:24:49 +0100 Subject: [PATCH 074/150] fix: refs #6276 drop suitcase sectorCollection_getSales --- .../getSalesFromTicketOrCollection.spec.js | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js index 02532b4b0..6417fca93 100644 --- a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js +++ b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js @@ -56,23 +56,4 @@ describe('collection getSalesFromTicketOrCollection()', () => { throw e; } }); - - it('should add a ticketTracking', async() => { - const collectionOrTicketFk = 23; - - const tx = await models.Collection.beginTransaction({}); - const options = {transaction: tx}; - try { - const ticketTrackingBefore = await models.TicketTracking.find(null, options); - await models.Collection.getSalesFromTicketOrCollection(ctx, - collectionOrTicketFk, print, source, options); - const ticketTrackingAfter = await models.TicketTracking.find(null, options); - - expect(ticketTrackingAfter.length).toEqual(ticketTrackingBefore.length + 1); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); }); From 02e38eb71182aa80650c307708dea732b9f8365a Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 25 Jan 2024 08:13:47 +0100 Subject: [PATCH 075/150] fix: refs #6276 fix tests --- back/methods/collection/addItem.js | 2 +- .../getSalesFromTicketOrCollection.js | 183 +++++++++--------- .../getSalesFromTicketOrCollection.spec.js | 29 ++- .../back/methods/item-shelving/makeMulti.js | 9 +- .../item/back/methods/item-shelving/return.js | 4 +- .../methods/sale-tracking/updateTracking.js | 2 +- 6 files changed, 124 insertions(+), 105 deletions(-) diff --git a/back/methods/collection/addItem.js b/back/methods/collection/addItem.js index 3b2a6921b..1317662b4 100644 --- a/back/methods/collection/addItem.js +++ b/back/methods/collection/addItem.js @@ -46,7 +46,7 @@ module.exports = Self => { } try { - const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [code, warehouseFk]); + const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [code, warehouseFk], myOptions); if (!item?.available) throw new UserError($t('We do not have availability for the selected item')); diff --git a/back/methods/collection/getSalesFromTicketOrCollection.js b/back/methods/collection/getSalesFromTicketOrCollection.js index 50fe21875..8fbc0f55b 100644 --- a/back/methods/collection/getSalesFromTicketOrCollection.js +++ b/back/methods/collection/getSalesFromTicketOrCollection.js @@ -56,92 +56,92 @@ module.exports = Self => { if (tickets.length) await sendRocketTickets(tickets); return getCollection(id, tickets, sales, placements, myOptions); + }; + async function sendRocketTickets(tickets) { + for (let ticket of tickets) { + let observations = ticket.observaciones.split(' '); - async function sendRocketTickets(tickets) { - for (let ticket of tickets) { - let observations = ticket.observaciones.split(' '); + for (let observation of observations) { + const salesMan = ticket.salesPersonFk; - for (let observation of observations) { - const salesMan = ticket.salesPersonFk; + if (!observation.startsWith('#') && !observation.startsWith('@')) return; - if (!observation.startsWith('#') && !observation.startsWith('@')) return; - - await models.Chat.send(ctx, - observation, - `El ticket ${ticket.ticketFk} del comercial ${salesMan} está en preparación.(mensaje creado automáticamente)` - ); - } - } - } - - async function getCollection(id, tickets, sales, placements, options) { - const collection = { - collectionFk: id, - tickets: [], - }; - for (let ticket of tickets) { - const {ticketFk} = ticket; - ticket.sales = []; - - const barcodes = await getBarcodes(ticketFk); - await Self.rawSql( - 'CALL util.log_add(?, ?, ?, ?, ?, ?, ?, ?)', - ['vn', 'ticket', 'Ticket', ticketFk, ticketFk, 'select', null, null], - options + await models.Chat.send(ctx, + observation, + `El ticket ${ticket.ticketFk} del comercial ${salesMan} está en preparación.(mensaje creado automáticamente)` ); - - for (let sale of sales) { - if (sale.ticketFk == ticketFk) { - sale.placements = []; - for (const salePlacement of placements) { - let placement; - if (salePlacement.saleFk == sale.saleFk && salePlacement.order) { - placement = { - saleFk: salePlacement.saleFk, - itemFk: salePlacement.itemFk, - placement: salePlacement.placement, - shelving: salePlacement.shelving, - created: salePlacement.created, - visible: salePlacement.visible, - order: salePlacement.order, - grouping: salePlacement.grouping, - priority: salePlacement.priority, - saleOrder: salePlacement.saleOrder, - isPreviousPrepared: salePlacement.isPreviousPrepared, - itemShelvingSaleFk: salePlacement.itemShelvingSaleFk, - ticketFk: salePlacement.ticketFk, - id: salePlacement.id - }; - sale.placements.push(placement); - } - } - - sale.barcodes = []; - for (const barcode of barcodes) { - if (barcode.movementId == sale.saleFk) { - if (barcode.code) { - sale.barcodes.push(barcode.code); - sale.barcodes.push(`0 ${barcode.code}`); - } - - if (barcode.id) { - sale.barcodes.push(barcode.id); - sale.barcodes.push(`0 ${barcode.id}`); - } - } - } - - ticket.sales.push(sale); - } - } - collection.tickets.push(ticket); } + } + } - return collection; + async function getCollection(id, tickets, sales, placements, options) { + const collection = { + collectionFk: id, + tickets: [], + }; + for (let ticket of tickets) { + const {ticketFk} = ticket; + ticket.sales = []; + + const barcodes = await getBarcodes(ticketFk); + await Self.rawSql( + 'CALL util.log_add(?, ?, ?, ?, ?, ?, ?, ?)', + ['vn', 'ticket', 'Ticket', ticketFk, ticketFk, 'select', null, null], + options + ); + + for (let sale of sales) { + if (sale.ticketFk == ticketFk) { + sale.placements = []; + for (const salePlacement of placements) { + let placement; + if (salePlacement.saleFk == sale.saleFk && salePlacement.order) { + placement = { + saleFk: salePlacement.saleFk, + itemFk: salePlacement.itemFk, + placement: salePlacement.placement, + shelving: salePlacement.shelving, + created: salePlacement.created, + visible: salePlacement.visible, + order: salePlacement.order, + grouping: salePlacement.grouping, + priority: salePlacement.priority, + saleOrder: salePlacement.saleOrder, + isPreviousPrepared: salePlacement.isPreviousPrepared, + itemShelvingSaleFk: salePlacement.itemShelvingSaleFk, + ticketFk: salePlacement.ticketFk, + id: salePlacement.id + }; + sale.placements.push(placement); + } + } + + sale.barcodes = []; + for (const barcode of barcodes) { + if (barcode.movementId == sale.saleFk) { + if (barcode.code) { + sale.barcodes.push(barcode.code); + sale.barcodes.push(`0 ${barcode.code}`); + } + + if (barcode.id) { + sale.barcodes.push(barcode.id); + sale.barcodes.push(`0 ${barcode.id}`); + } + } + } + + ticket.sales.push(sale); + } + } + collection.tickets.push(ticket); } - async function getBarcodes(ticketId) { - const query = + return collection; + } + + async function getBarcodes(ticketId) { + const query = `SELECT s.id movementId, b.code, c.id @@ -152,21 +152,20 @@ module.exports = Self => { LEFT JOIN vn.travel tr ON tr.id = e.travelFk WHERE s.ticketFk = ? AND tr.landed >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)`; - return Self.rawSql(query, [ticketId]); - } + return Self.rawSql(query, [ticketId]); + } - async function setState(source, id, options) { - let state; - if (source == 'PRECHECKER') state = 'PREVIOUS_CONTROL'; - else if (source == 'CHECKER') state = 'ON_CHECKING'; + async function setState(source, id, options) { + let state; + if (source == 'PRECHECKER') state = 'PREVIOUS_CONTROL'; + else if (source == 'CHECKER') state = 'ON_CHECKING'; - if (state) { - await Self.rawSql( - 'CALL vn.ticketStateToday_setState(?,?)', - [id, state], - options - ); - } + if (state) { + await Self.rawSql( + 'CALL vn.ticketStateToday_setState(?,?)', + [id, state], + options + ); } - }; + } }; diff --git a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js index 6417fca93..8f2ea4408 100644 --- a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js +++ b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js @@ -43,11 +43,14 @@ describe('collection getSalesFromTicketOrCollection()', () => { it('should print a sticker', async() => { const tx = await models.Collection.beginTransaction({}); const options = {transaction: tx}; + const query = 'SELECT * FROM printQueue pq JOIN printQueueArgs pqa ON pqa.printQueueFk = pq.id'; try { - const printQueueBefore = await models.Collection.rawSql('SELECT * FROM printQueue', [], options); + const printQueueBefore = await models.Collection.rawSql( + query, [], options); await models.Collection.getSalesFromTicketOrCollection(ctx, - collectionOrTicketFk, print, source, options); - const printQueueAfter = await models.Collection.rawSql('SELECT * FROM printQueue', [], options); + collectionOrTicketFk, true, source, options); + const printQueueAfter = await models.Collection.rawSql( + query, [], options); expect(printQueueAfter.length).toEqual(printQueueBefore.length + 1); await tx.rollback(); @@ -56,4 +59,24 @@ describe('collection getSalesFromTicketOrCollection()', () => { throw e; } }); + + it('should getSalesFromTicketOrCollection', async() => { + const tx = await models.Collection.beginTransaction({}); + + try { + const options = {transaction: tx}; + await models.Ticket.updateAll({id: collectionOrTicketFk}, {shipped: '2001-01-02 00:00:00.000'}, options); + + const ticketTrackingBefore = await models.TicketTracking.find(null, options); + await models.Collection.getSalesFromTicketOrCollection(ctx, + collectionOrTicketFk, false, source, options); + const ticketTrackingAfter = await models.TicketTracking.find(null, options); + + expect(ticketTrackingAfter.length).toEqual(ticketTrackingBefore.length + 1); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); diff --git a/modules/item/back/methods/item-shelving/makeMulti.js b/modules/item/back/methods/item-shelving/makeMulti.js index 7d1ee11a0..e3a3b1cf5 100644 --- a/modules/item/back/methods/item-shelving/makeMulti.js +++ b/modules/item/back/methods/item-shelving/makeMulti.js @@ -47,7 +47,8 @@ module.exports = Self => { }, 0); discardItems.push(item); - const [result] = await Self.rawSql('SELECT vn.itemPacking(?, ?) itemPacking', [item, warehouseFk]); + const [result] = await Self.rawSql('SELECT vn.itemPacking(?, ?) itemPacking', + [item, warehouseFk], myOptions); let packing; if (result) packing = result.itemPacking; @@ -56,11 +57,7 @@ module.exports = Self => { quantity = quantity * packing; await Self.rawSql('CALL vn.itemShelving_add(?, ?, ?, NULL, NULL, ?, ?)', - [shelvingFk, - item, - quantity, - packing, - warehouseFk] + [shelvingFk, item, quantity, packing, warehouseFk], myOptions ); } } diff --git a/modules/item/back/methods/item-shelving/return.js b/modules/item/back/methods/item-shelving/return.js index aa44ef5b5..8e8b4eae2 100644 --- a/modules/item/back/methods/item-shelving/return.js +++ b/modules/item/back/methods/item-shelving/return.js @@ -39,8 +39,8 @@ module.exports = Self => { }; let itemShelvings = await models.ItemShelving.find(filterItemShelvings, myOptions); - const [alternatives] = await models.ItemShelving.rawSql( - 'CALL vn.itemShelving_getAlternatives(?)', [shelvingFk] + const [alternatives] = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)', + [shelvingFk], myOptions ); if (itemShelvings) { diff --git a/modules/ticket/back/methods/sale-tracking/updateTracking.js b/modules/ticket/back/methods/sale-tracking/updateTracking.js index 81eef28b4..22ff141d8 100644 --- a/modules/ticket/back/methods/sale-tracking/updateTracking.js +++ b/modules/ticket/back/methods/sale-tracking/updateTracking.js @@ -96,7 +96,7 @@ module.exports = Self => { neq: null } } - }); + }, myOptions); } if (isBuy) await models.SaleBuy.create({saleFk, buyFk}, myOptions); From 63fb3db8a1665045b96a964b7e94d4e7db8af3a7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 25 Jan 2024 12:14:14 +0100 Subject: [PATCH 076/150] fix: refs #6276 test item_card & general fixes --- back/methods/collection/assignCollection.js | 13 +++++++++---- .../collection/getSalesFromTicketOrCollection.js | 16 +++++++--------- loopback/locale/en.json | 6 ++++-- loopback/locale/es.json | 4 +++- modules/item/back/methods/item/card.js | 9 ++------- .../item/back/methods/item/specs/card.spec.js | 4 ++-- 6 files changed, 27 insertions(+), 25 deletions(-) diff --git a/back/methods/collection/assignCollection.js b/back/methods/collection/assignCollection.js index 3384b325a..c4671e747 100644 --- a/back/methods/collection/assignCollection.js +++ b/back/methods/collection/assignCollection.js @@ -13,16 +13,21 @@ module.exports = Self => { }, }); - Self.assignCollection = async ctx => { + Self.assignCollection = async(ctx, options) => { const userId = ctx.req.accessToken.userId; + const myOptions = {userId}; + const $t = ctx.req.__; - await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk)', [userId]); + if (typeof options == 'object') + Object.assign(myOptions, options); + + await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk)', [userId], myOptions); const [assignedCollection] = await Self.rawSql('SELECT @vCollectionFk'); const {'@vCollectionFk': collectionFk} = assignedCollection; - if (!collectionFk) throw new UserError('No hay tickets para sacar'); - await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk]); + if (!collectionFk) throw new UserError($t('There are not picking tickets')); + await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions); return collectionFk; }; diff --git a/back/methods/collection/getSalesFromTicketOrCollection.js b/back/methods/collection/getSalesFromTicketOrCollection.js index 8fbc0f55b..09ccbafdc 100644 --- a/back/methods/collection/getSalesFromTicketOrCollection.js +++ b/back/methods/collection/getSalesFromTicketOrCollection.js @@ -30,8 +30,8 @@ module.exports = Self => { Self.getSalesFromTicketOrCollection = async(ctx, collectionOrTicketFk, print, source, options) => { const userId = ctx.req.accessToken.userId; - const models = Self.app.models; const myOptions = {userId}; + const $t = ctx.req.__; if (typeof options == 'object') Object.assign(myOptions, options); @@ -53,22 +53,20 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); - if (tickets.length) await sendRocketTickets(tickets); + if (tickets.length) await sendRocketTickets(tickets, $t); return getCollection(id, tickets, sales, placements, myOptions); }; - async function sendRocketTickets(tickets) { + async function sendRocketTickets(tickets, $t) { for (let ticket of tickets) { let observations = ticket.observaciones.split(' '); for (let observation of observations) { const salesMan = ticket.salesPersonFk; - if (!observation.startsWith('#') && !observation.startsWith('@')) return; - await models.Chat.send(ctx, observation, - `El ticket ${ticket.ticketFk} del comercial ${salesMan} está en preparación.(mensaje creado automáticamente)` + $t('ticketCommercial', {ticket: ticket.ticketFk, salesMan}) ); } } @@ -83,7 +81,7 @@ module.exports = Self => { const {ticketFk} = ticket; ticket.sales = []; - const barcodes = await getBarcodes(ticketFk); + const barcodes = await getBarcodes(ticketFk, options); await Self.rawSql( 'CALL util.log_add(?, ?, ?, ?, ?, ?, ?, ?)', ['vn', 'ticket', 'Ticket', ticketFk, ticketFk, 'select', null, null], @@ -140,7 +138,7 @@ module.exports = Self => { return collection; } - async function getBarcodes(ticketId) { + async function getBarcodes(ticketId, options) { const query = `SELECT s.id movementId, b.code, @@ -152,7 +150,7 @@ module.exports = Self => { LEFT JOIN vn.travel tr ON tr.id = e.travelFk WHERE s.ticketFk = ? AND tr.landed >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)`; - return Self.rawSql(query, [ticketId]); + return Self.rawSql(query, [ticketId], options); } async function setState(source, id, options) { diff --git a/loopback/locale/en.json b/loopback/locale/en.json index dc3a4afae..5ff31a22f 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -213,6 +213,8 @@ "this state does not exist": "This state does not exist", "The line could not be marked": "The line could not be marked", "The sale can not be tracked": "The sale can not be tracked", - "Shelving not valid": "Shelving not valid" - + "Shelving not valid": "Shelving not valid", + "printerNotExists": "The printer does not exist", + "There are not picking tickets": "There are not picking tickets", + "ticketCommercial": "The ticket {{ ticket }} for the salesperson {{ salesMan }} is in preparation. (automatically generated message)" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 222df46d6..a1d1360a8 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -352,5 +352,7 @@ "The sale can not be tracked": "La línea no puede ser rastreada", "Shelving not valid": "Carro no válido", "Carro no válido": "Carro no válido", - "printerNotExists": "printerNotExists" + "printerNotExists": "No existe la impresora", + "There are not picking tickets": "No hay tickets para sacar", + "ticketCommercial": "El ticket {{ticket}} del comercial {{salesMan}} está en preparación.(mensaje creado automáticamente)" } \ No newline at end of file diff --git a/modules/item/back/methods/item/card.js b/modules/item/back/methods/item/card.js index 45c2ac36c..bc59c8bff 100644 --- a/modules/item/back/methods/item/card.js +++ b/modules/item/back/methods/item/card.js @@ -27,7 +27,7 @@ module.exports = Self => { Self.card = async(itemFk, warehouseFk) => { const models = Self.app.models; - const [result] = await Self.rawSql('CALL vn.item_getInfo(?, ?)', [itemFk, warehouseFk]); + const [[itemInfo]] = await Self.rawSql('CALL vn.item_getInfo(?, ?)', [itemFk, warehouseFk]); const barcodeItems = await Self.rawSql('SELECT vn.barcodeToItem(?) as realIdItem', [itemFk]); const [realIdItem] = barcodeItems.map(barcodeItem => barcodeItem.realIdItem); @@ -40,12 +40,7 @@ module.exports = Self => { } }); - let itemInfo; - if (result.length) { - itemInfo = {...result[0]}; - itemInfo.barcodes = barcodes; - } - + if (itemInfo) itemInfo.barcodes = barcodes; return itemInfo; }; }; diff --git a/modules/item/back/methods/item/specs/card.spec.js b/modules/item/back/methods/item/specs/card.spec.js index 725a4269d..65004cfa5 100644 --- a/modules/item/back/methods/item/specs/card.spec.js +++ b/modules/item/back/methods/item/specs/card.spec.js @@ -3,10 +3,10 @@ const {models} = require('vn-loopback/server/server'); describe('item card()', () => { const itemFk = 1; const warehouseFk = 1; - it('WIP: should get something', async() => { + it('should get an item with several barcodes', async() => { const card = await models.Item.card(itemFk, warehouseFk); expect(card).toBeDefined(); - expect(card.barcodes); + expect(card.barcodes.length).toBeTruthy(); }); }); From 293bbd3da33ee96733fc5cc87e40076183293747 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 29 Jan 2024 09:31:12 +0100 Subject: [PATCH 077/150] fix: refs #6276 merge database --- .../10837-whiteOrchid/00-firstScript.sql | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 db/versions/10837-whiteOrchid/00-firstScript.sql diff --git a/db/versions/10837-whiteOrchid/00-firstScript.sql b/db/versions/10837-whiteOrchid/00-firstScript.sql new file mode 100644 index 000000000..eef5faa80 --- /dev/null +++ b/db/versions/10837-whiteOrchid/00-firstScript.sql @@ -0,0 +1,18 @@ +-- Place your SQL code here +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'employee'), + ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'), + ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'), + ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'), + ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'), + ('SaleTracking','mark','WRITE','ALLOW','ROLE','employee'), + ('ItemBarcode','deleteByItemAndCode','WRITE','ALLOW','ROLE','employee'), + ('Collection','addItem','WRITE','ALLOW','ROLE','employee'), + ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('MobileAppVersionControl', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'), + ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('Collection', 'addItem', 'WRITE', 'ALLOW', 'ROLE', 'production'); + \ No newline at end of file From e17fc9141594161af61471846672654759b5c40a Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 30 Jan 2024 14:58:11 +0100 Subject: [PATCH 078/150] fix: refs #6276 fix acl, addSaleByCode & tests --- .vscode/settings.json | 3 +- back/models/collection.js | 1 - .../10832-purpleAralia/00-newWareHouse.sql | 24 +++---- loopback/locale/es.json | 3 - .../back/methods/item-shelving/makeMulti.js | 71 ------------------- .../item/back/methods/item-shelving/return.js | 7 +- .../item-shelving/specs/makeMulti.spec.js | 54 -------------- .../item-shelving/specs/return.spec.js | 11 +-- modules/item/back/models/item-shelving.js | 1 - .../back/methods/ticket/addSaleByCode.js | 27 +++---- .../ticket/specs/addSaleByCode.spec.js | 21 +----- modules/ticket/back/models/ticket.js | 1 + 12 files changed, 27 insertions(+), 197 deletions(-) delete mode 100644 modules/item/back/methods/item-shelving/makeMulti.js delete mode 100644 modules/item/back/methods/item-shelving/specs/makeMulti.spec.js rename back/methods/collection/addItem.js => modules/ticket/back/methods/ticket/addSaleByCode.js (57%) rename back/methods/collection/spec/addItem.spec.js => modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js (60%) diff --git a/.vscode/settings.json b/.vscode/settings.json index 76b039f61..03479d27a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -18,6 +18,5 @@ "salix", "fdescribe", "Loggable" - ], - "CodeGPT.apiKey": "CodeGPT Plus Beta" + ] } diff --git a/back/models/collection.js b/back/models/collection.js index 98a199fbd..93ab2731b 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -5,6 +5,5 @@ module.exports = Self => { require('../methods/collection/previousLabel')(Self); require('../methods/collection/getTickets')(Self); require('../methods/collection/assignCollection')(Self); - require('../methods/collection/addItem')(Self); require('../methods/collection/getSalesFromTicketOrCollection')(Self); }; diff --git a/db/versions/10832-purpleAralia/00-newWareHouse.sql b/db/versions/10832-purpleAralia/00-newWareHouse.sql index 1b1ec263f..4802a6c4a 100644 --- a/db/versions/10832-purpleAralia/00-newWareHouse.sql +++ b/db/versions/10832-purpleAralia/00-newWareHouse.sql @@ -1,18 +1,14 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES - ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'), - ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'), - ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'), - ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'), - ('SaleTracking','mark','WRITE','ALLOW','ROLE','employee'), - ('ItemBarcode','deleteByItemAndCode','WRITE','ALLOW','ROLE','employee'), - ('Collection','addItem','WRITE','ALLOW','ROLE','employee'), - ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'), - ('MobileAppVersionControl', '*', 'READ', 'ALLOW', 'ROLE', 'production'), ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'), - ('Collection', 'addItem', 'WRITE', 'ALLOW', 'ROLE', 'production'), - ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Collection', 'addItem', 'WRITE', 'ALLOW', 'ROLE', 'production'); + ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'production'), + ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','production'), + ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','production'), + ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','production'), + ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','production'), + ('SaleTracking','mark','WRITE','ALLOW','ROLE','production'), + ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'), + ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'production'), + ('Ticket', 'addSaleByCode', 'WRITE', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index a1d1360a8..18e191188 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -346,12 +346,9 @@ "You are already using a machine": "Ya estás usando una máquina.", "This worker does not exist": "Este trabajador no existe", "this state does not exist": "Este estado no existe", - "Este estado no existe": "Este estado no existe", "The line could not be marked": "No se ha podido marcar la línea", - "No se ha podido marcar la línea": "No se ha podido marcar la línea", "The sale can not be tracked": "La línea no puede ser rastreada", "Shelving not valid": "Carro no válido", - "Carro no válido": "Carro no válido", "printerNotExists": "No existe la impresora", "There are not picking tickets": "No hay tickets para sacar", "ticketCommercial": "El ticket {{ticket}} del comercial {{salesMan}} está en preparación.(mensaje creado automáticamente)" diff --git a/modules/item/back/methods/item-shelving/makeMulti.js b/modules/item/back/methods/item-shelving/makeMulti.js deleted file mode 100644 index e3a3b1cf5..000000000 --- a/modules/item/back/methods/item-shelving/makeMulti.js +++ /dev/null @@ -1,71 +0,0 @@ -module.exports = Self => { - Self.remoteMethod('makeMulti', { - description: 'Add a record or update it if it already exists.', - accessType: 'WRITE', - accepts: [{ - arg: 'shelvingFk', - type: 'string', - required: true, - }, - { - arg: 'items', - type: ['number'], - required: true, - description: 'array of item foreign keys' - }, - { - arg: 'warehouseFk', - type: 'number', - required: true - }], - - http: { - path: `/makeMulti`, - verb: 'POST' - } - }); - - Self.makeMulti = async(shelvingFk, items, warehouseFk, options) => { - const myOptions = {}; - let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - const discardItems = []; - - try { - for (let item of items) { - if (!discardItems.includes(item)) { - let quantity = items.reduce((acc, cur) => { - return acc + (cur === item ? 1 : 0); - }, 0); - discardItems.push(item); - - const [result] = await Self.rawSql('SELECT vn.itemPacking(?, ?) itemPacking', - [item, warehouseFk], myOptions); - let packing; - - if (result) packing = result.itemPacking; - if (!packing) packing = 1; - - quantity = quantity * packing; - - await Self.rawSql('CALL vn.itemShelving_add(?, ?, ?, NULL, NULL, ?, ?)', - [shelvingFk, item, quantity, packing, warehouseFk], myOptions - ); - } - } - - if (tx) await tx.commit(); - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/modules/item/back/methods/item-shelving/return.js b/modules/item/back/methods/item-shelving/return.js index 8e8b4eae2..81047461e 100644 --- a/modules/item/back/methods/item-shelving/return.js +++ b/modules/item/back/methods/item-shelving/return.js @@ -39,13 +39,14 @@ module.exports = Self => { }; let itemShelvings = await models.ItemShelving.find(filterItemShelvings, myOptions); - const [alternatives] = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)', - [shelvingFk], myOptions - ); if (itemShelvings) { + const [alternatives] = await models.ItemShelving.rawSql('CALL vn.itemShelving_getAlternatives(?)', + [shelvingFk], myOptions + ); return itemShelvings.map(itemShelving => { const item = itemShelving.item(); + const carros = alternatives.filter(alternative => alternative.itemFk == itemShelving.itemFk); return { diff --git a/modules/item/back/methods/item-shelving/specs/makeMulti.spec.js b/modules/item/back/methods/item-shelving/specs/makeMulti.spec.js deleted file mode 100644 index f64a815f2..000000000 --- a/modules/item/back/methods/item-shelving/specs/makeMulti.spec.js +++ /dev/null @@ -1,54 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('item makeMulti()', () => { - const warehouseFk = 1; - - beforeAll(async() => { - ctx = { - accessToken: {userId: 9}, - req: { - headers: {origin: 'http://localhost'}, - } - }; - }); - - it('should add two new records', async() => { - const shelvingFk = 'ZPP'; - const items = [1, 1, 1, 2]; - const tx = await models.ItemShelving.beginTransaction({}); - const options = {transaction: tx}; - - try { - await models.ItemShelving.makeMulti(shelvingFk, items, warehouseFk, options); - const itemShelvings = await models.ItemShelving.find({where: {shelvingFk}}, options); - - expect(itemShelvings.length).toEqual(2); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should update the visible items', async() => { - const shelvingFk = 'GVC'; - const items = [2, 2]; - const tx = await models.ItemShelving.beginTransaction({}); - const options = {transaction: tx}; - try { - const {visible: itemsBefore} = await models.ItemShelving.findOne({ - where: {shelvingFk, itemFk: items[0]} - }, options); - await models.ItemShelving.makeMulti(shelvingFk, items, warehouseFk, options); - const {visible: itemsAfter} = await models.ItemShelving.findOne({ - where: {shelvingFk, itemFk: items[0]} - }, options); - - expect(itemsAfter).toEqual(itemsBefore + 2); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -}); diff --git a/modules/item/back/methods/item-shelving/specs/return.spec.js b/modules/item/back/methods/item-shelving/specs/return.spec.js index c8acd6ab9..07ddc2168 100644 --- a/modules/item/back/methods/item-shelving/specs/return.spec.js +++ b/modules/item/back/methods/item-shelving/specs/return.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -describe('itemShelving return()', () => { +fdescribe('itemShelving return()', () => { beforeAll(async() => { ctx = { req: { @@ -9,15 +9,6 @@ describe('itemShelving return()', () => { }; }); - it('should return a list of items and alternative locations', async() => { - const shelvingFk = 'PCC'; - const itemShelvings = await models.ItemShelving.return(shelvingFk); - - expect(itemShelvings[0].itemFk).toEqual(999997); - expect(itemShelvings[0].quantity).toEqual(10); - expect(itemShelvings[0].carros.length).toEqual(1); - }); - it('should return a list of items without alternatives', async() => { const shelvingFk = 'HEJ'; const itemShelvings = await models.ItemShelving.return(shelvingFk); diff --git a/modules/item/back/models/item-shelving.js b/modules/item/back/models/item-shelving.js index 4eb5374e8..6e63a29b2 100644 --- a/modules/item/back/models/item-shelving.js +++ b/modules/item/back/models/item-shelving.js @@ -1,7 +1,6 @@ module.exports = Self => { require('../methods/item-shelving/deleteItemShelvings')(Self); require('../methods/item-shelving/getInventory')(Self); - require('../methods/item-shelving/makeMulti')(Self); require('../methods/item-shelving/return')(Self); require('../methods/item-shelving/updateFromSale')(Self); }; diff --git a/back/methods/collection/addItem.js b/modules/ticket/back/methods/ticket/addSaleByCode.js similarity index 57% rename from back/methods/collection/addItem.js rename to modules/ticket/back/methods/ticket/addSaleByCode.js index 1317662b4..5c63b465e 100644 --- a/back/methods/collection/addItem.js +++ b/modules/ticket/back/methods/ticket/addSaleByCode.js @@ -1,6 +1,5 @@ -const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethodCtx('addItem', { + Self.remoteMethodCtx('addSaleByCode', { description: 'Add a collection', accessType: 'WRITE', accepts: [ @@ -8,33 +7,26 @@ module.exports = Self => { arg: 'code', type: 'string', required: true - }, - { + }, { arg: 'quantity', type: 'number', required: true - }, - { + }, { arg: 'ticketFk', type: 'number', required: true }, - { - arg: 'warehouseFk', - type: 'number', - required: true - }, + ], http: { - path: `/addItem`, + path: `/addSaleByCode`, verb: 'POST' }, }); - Self.addItem = async(ctx, code, quantity, ticketFk, warehouseFk, options) => { + Self.addSaleByCode = async(ctx, code, quantity, ticketFk, options) => { const models = Self.app.models; const myOptions = {}; - const $t = ctx.req.__; let tx; if (typeof options == 'object') @@ -46,11 +38,8 @@ module.exports = Self => { } try { - const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [code, warehouseFk], myOptions); - - if (!item?.available) throw new UserError($t('We do not have availability for the selected item')); - - await models.Ticket.addSale(ctx, ticketFk, item.id, quantity, myOptions); + const [{itemFk}] = await Self.rawSql('SELECT barcodeToItem(?) itemFk', [code], myOptions); + await models.Ticket.addSale(ctx, ticketFk, itemFk, quantity, myOptions); if (tx) await tx.commit(); } catch (e) { diff --git a/back/methods/collection/spec/addItem.spec.js b/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js similarity index 60% rename from back/methods/collection/spec/addItem.spec.js rename to modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js index 199aae588..ce3a5b3ad 100644 --- a/back/methods/collection/spec/addItem.spec.js +++ b/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); -describe('collection addItem()', () => { +describe('Ticket addSaleByCode()', () => { const quantity = 3; const ticketFk = 24; const warehouseFk = 1; @@ -26,7 +26,7 @@ describe('collection addItem()', () => { const code = '1111111111'; const salesBefore = await models.Sale.find(null, options); - await models.Collection.addItem(activeCtx, code, quantity, ticketFk, warehouseFk, options); + await models.Ticket.addSaleByCode(activeCtx, code, quantity, ticketFk, warehouseFk, options); const salesAfter = await models.Sale.find(null, options); expect(salesAfter.length).toEqual(salesBefore.length + 1); @@ -36,21 +36,4 @@ describe('collection addItem()', () => { throw e; } }); - - it('should throw an error when the item is not available', async() => { - const code = '00000000000'; - const tx = await models.Sale.beginTransaction({}); - - try { - const options = {transaction: tx}; - - await models.Collection.addItem(activeCtx, code, quantity, ticketFk, warehouseFk, options); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - const error = e; - - expect(error.message).toEqual('We do not have availability for the selected item'); - } - }); }); diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js index 1930765fb..51a8372e3 100644 --- a/modules/ticket/back/models/ticket.js +++ b/modules/ticket/back/models/ticket.js @@ -1,4 +1,5 @@ module.exports = Self => { require('./ticket-methods')(Self); require('../methods/ticket/state')(Self); + require('../methods/ticket/addSaleByCode')(Self); }; From 2a6abffef938d77f975498aa475ec7a2f03f2d27 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 30 Jan 2024 16:07:33 +0100 Subject: [PATCH 079/150] fix: refs #6276 fix errors & refactor --- back/methods/collection/assignCollection.js | 3 +-- .../mobile-app-version-control/getVersion.js | 6 +++--- loopback/locale/en.json | 2 +- loopback/locale/es.json | 2 +- modules/item/back/methods/item/card.js | 1 - modules/ticket/back/methods/sale-tracking/mark.js | 4 ++-- .../back/methods/sale-tracking/specs/mark.spec.js | 2 +- .../back/methods/ticket/specs/setDeleted.spec.js | 13 ++++++++----- modules/ticket/back/models/expeditionPallet.json | 3 --- 9 files changed, 17 insertions(+), 19 deletions(-) diff --git a/back/methods/collection/assignCollection.js b/back/methods/collection/assignCollection.js index c4671e747..67a10df51 100644 --- a/back/methods/collection/assignCollection.js +++ b/back/methods/collection/assignCollection.js @@ -16,7 +16,6 @@ module.exports = Self => { Self.assignCollection = async(ctx, options) => { const userId = ctx.req.accessToken.userId; const myOptions = {userId}; - const $t = ctx.req.__; if (typeof options == 'object') Object.assign(myOptions, options); @@ -26,7 +25,7 @@ module.exports = Self => { const [assignedCollection] = await Self.rawSql('SELECT @vCollectionFk'); const {'@vCollectionFk': collectionFk} = assignedCollection; - if (!collectionFk) throw new UserError($t('There are not picking tickets')); + if (!collectionFk) throw new UserError('There are not picking tickets'); await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions); return collectionFk; diff --git a/back/methods/mobile-app-version-control/getVersion.js b/back/methods/mobile-app-version-control/getVersion.js index 510fd6c4a..38f4acc54 100644 --- a/back/methods/mobile-app-version-control/getVersion.js +++ b/back/methods/mobile-app-version-control/getVersion.js @@ -29,9 +29,9 @@ module.exports = Self => { let fields = ['id', 'appName']; if (workerFk) - fields = [...fields, ...['isVersionBetaCritical', 'versionBeta', 'urlBeta']]; + fields = fields.concat(['isVersionBetaCritical', 'versionBeta', 'urlBeta']); else - fields = [...fields, ...['isVersionCritical', 'version', 'urlProduction']]; + fields = fields.concat(['isVersionCritical', 'version', 'urlProduction']); const filter = { where: { @@ -40,6 +40,6 @@ module.exports = Self => { fields, }; - return await Self.findOne(filter); + return Self.findOne(filter); }; }; diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 5ff31a22f..fc15d0d0e 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -212,7 +212,7 @@ "This worker does not exist": "This worker does not exist", "this state does not exist": "This state does not exist", "The line could not be marked": "The line could not be marked", - "The sale can not be tracked": "The sale can not be tracked", + "The sale cannot be tracked": "The sale cannot be tracked", "Shelving not valid": "Shelving not valid", "printerNotExists": "The printer does not exist", "There are not picking tickets": "There are not picking tickets", diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 18e191188..f9e41d7f8 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -347,7 +347,7 @@ "This worker does not exist": "Este trabajador no existe", "this state does not exist": "Este estado no existe", "The line could not be marked": "No se ha podido marcar la línea", - "The sale can not be tracked": "La línea no puede ser rastreada", + "The sale cannot be tracked": "La línea no puede ser rastreada", "Shelving not valid": "Carro no válido", "printerNotExists": "No existe la impresora", "There are not picking tickets": "No hay tickets para sacar", diff --git a/modules/item/back/methods/item/card.js b/modules/item/back/methods/item/card.js index bc59c8bff..5d086ce88 100644 --- a/modules/item/back/methods/item/card.js +++ b/modules/item/back/methods/item/card.js @@ -36,7 +36,6 @@ module.exports = Self => { fields: ['code'], where: { itemFk: realIdItem - } }); diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/mark.js index dc288ba93..dd6cbc781 100644 --- a/modules/ticket/back/methods/sale-tracking/mark.js +++ b/modules/ticket/back/methods/sale-tracking/mark.js @@ -90,12 +90,12 @@ module.exports = Self => { const buy = await models.Buy.findById(buyFk, myOptions); if (buy.itemOriginalFk) await models.SaleBuy.create({saleFk, buyFk}, myOptions); } catch (e) { - throw new UserError($t('The sale can not be tracked')); + throw new UserError($t('The sale cannot be tracked')); } if (tx) await tx.commit(); } catch (e) { - if (e.message == $t('The sale can not be tracked')) { + if (e.message == $t('The sale cannot be tracked')) { if (tx) tx.commit(); throw e; } diff --git a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js index d981aeea5..723f5fb78 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js @@ -79,7 +79,7 @@ describe('saleTracking mark()', () => { } catch (e) { const error = e; - expect(error.message).toEqual('The sale can not be tracked'); + expect(error.message).toEqual('The sale cannot be tracked'); await tx.rollback(); } }); diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js index f3e35972f..520a9e403 100644 --- a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js @@ -50,14 +50,17 @@ describe('ticket setDeleted()', () => { return value; }; const ticketId = 23; - - await models.Ticket.setDeleted(ctx, ticketId, options); - - const [sectorCollection] = await models.Ticket.rawSql( + const [sectorCollectionBefore] = await models.Ticket.rawSql( `SELECT COUNT(*) numberRows FROM vn.sectorCollection`, [], options); - expect(sectorCollection.numberRows).toEqual(1); + await models.Ticket.setDeleted(ctx, ticketId, options); + + const [sectorCollectionAfter] = await models.Ticket.rawSql( + `SELECT COUNT(*) numberRows + FROM vn.sectorCollection`, [], options); + + expect(sectorCollectionAfter.numberRows).toEqual(sectorCollectionBefore.numberRows - 1); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/models/expeditionPallet.json b/modules/ticket/back/models/expeditionPallet.json index 7cb4e1e6d..cab3af6ec 100644 --- a/modules/ticket/back/models/expeditionPallet.json +++ b/modules/ticket/back/models/expeditionPallet.json @@ -12,9 +12,6 @@ "id": true, "description": "Identifier" }, - "truckFk": { - "type": "number" - }, "built": { "type": "date" }, From 8f5a5d9cba80966e5bd4f408a91c63fe7ffbacbe Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 31 Jan 2024 13:11:15 +0100 Subject: [PATCH 080/150] fix: refs #6703 tests & backs --- .../getSalesFromTicketOrCollection.js | 14 ++--- .../10837-whiteOrchid/00-firstScript.sql | 18 ------ loopback/locale/en.json | 2 - loopback/locale/es.json | 5 +- .../methods/expedition-pallet/getPallet.js | 60 ------------------- .../expedition-pallet/specs/getPallet.spec.js | 32 ---------- .../back/methods/sale-tracking/delete.js | 6 -- .../ticket/back/methods/sale-tracking/mark.js | 7 +-- .../sale-tracking/specs/delete.spec.js | 3 +- .../methods/sale-tracking/updateTracking.js | 3 +- .../ticket/back/models/expeditionPallet.js | 3 - modules/ticket/back/models/sale-buy.json | 3 +- modules/ticket/back/models/sale.js | 2 +- modules/worker/back/methods/operator/add.js | 10 ++-- 14 files changed, 19 insertions(+), 149 deletions(-) delete mode 100644 db/versions/10837-whiteOrchid/00-firstScript.sql delete mode 100644 modules/ticket/back/methods/expedition-pallet/getPallet.js delete mode 100644 modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js delete mode 100644 modules/ticket/back/models/expeditionPallet.js diff --git a/back/methods/collection/getSalesFromTicketOrCollection.js b/back/methods/collection/getSalesFromTicketOrCollection.js index 09ccbafdc..3c27a0be6 100644 --- a/back/methods/collection/getSalesFromTicketOrCollection.js +++ b/back/methods/collection/getSalesFromTicketOrCollection.js @@ -154,15 +154,13 @@ module.exports = Self => { } async function setState(source, id, options) { - let state; - if (source == 'PRECHECKER') state = 'PREVIOUS_CONTROL'; - else if (source == 'CHECKER') state = 'ON_CHECKING'; - - if (state) { + const states = { + 'PRECHECKER': 'PREVIOUS_CONTROL', + 'CHECKER': 'ON_CHECKING' + }; + if (states[source]) { await Self.rawSql( - 'CALL vn.ticketStateToday_setState(?,?)', - [id, state], - options + 'CALL vn.ticketStateToday_setState(?,?)', [id, states[source]], options ); } } diff --git a/db/versions/10837-whiteOrchid/00-firstScript.sql b/db/versions/10837-whiteOrchid/00-firstScript.sql deleted file mode 100644 index eef5faa80..000000000 --- a/db/versions/10837-whiteOrchid/00-firstScript.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Place your SQL code here -INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) - VALUES - ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'employee'), - ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','employee'), - ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','employee'), - ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','employee'), - ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','employee'), - ('SaleTracking','mark','WRITE','ALLOW','ROLE','employee'), - ('ItemBarcode','deleteByItemAndCode','WRITE','ALLOW','ROLE','employee'), - ('Collection','addItem','WRITE','ALLOW','ROLE','employee'), - ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'), - ('MobileAppVersionControl', '*', 'READ', 'ALLOW', 'ROLE', 'production'), - ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'), - ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'employee'), - ('Collection', 'addItem', 'WRITE', 'ALLOW', 'ROLE', 'production'); - \ No newline at end of file diff --git a/loopback/locale/en.json b/loopback/locale/en.json index fc15d0d0e..20bb3eb07 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -206,10 +206,8 @@ "Incorrect pin": "Incorrect pin.", "This machine is already in use.": "This machine is already in use.", "the plate does not exist": "The plate {{plate}} does not exist", - "This pallet does not exist": "This pallet does not exist", "We do not have availability for the selected item": "We do not have availability for the selected item", "You are already using a machine": "You are already using a machine", - "This worker does not exist": "This worker does not exist", "this state does not exist": "This state does not exist", "The line could not be marked": "The line could not be marked", "The sale cannot be tracked": "The sale cannot be tracked", diff --git a/loopback/locale/es.json b/loopback/locale/es.json index f9e41d7f8..65ff7e951 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -341,15 +341,14 @@ "There is no zone for these parameters 999999": "There is no zone for these parameters 999999", "This machine is already in use.": "Esta máquina ya está en uso.", "the plate does not exist": "La máquina {{plate}} no existe", - "This pallet does not exist": "Este palet no existe", "We do not have availability for the selected item": "No tenemos disponible el item seleccionado", "You are already using a machine": "Ya estás usando una máquina.", - "This worker does not exist": "Este trabajador no existe", "this state does not exist": "Este estado no existe", "The line could not be marked": "No se ha podido marcar la línea", "The sale cannot be tracked": "La línea no puede ser rastreada", "Shelving not valid": "Carro no válido", "printerNotExists": "No existe la impresora", "There are not picking tickets": "No hay tickets para sacar", - "ticketCommercial": "El ticket {{ticket}} del comercial {{salesMan}} está en preparación.(mensaje creado automáticamente)" + "ticketCommercial": "El ticket {{ticket}} del comercial {{salesMan}} está en preparación.(mensaje creado automáticamente)", + "Este trabajador no existe": "Este trabajador no existe" } \ No newline at end of file diff --git a/modules/ticket/back/methods/expedition-pallet/getPallet.js b/modules/ticket/back/methods/expedition-pallet/getPallet.js deleted file mode 100644 index 340dc02b0..000000000 --- a/modules/ticket/back/methods/expedition-pallet/getPallet.js +++ /dev/null @@ -1,60 +0,0 @@ - -const UserError = require('vn-loopback/util/user-error'); -module.exports = Self => { - Self.remoteMethodCtx('getPallet', { - description: 'Get pallet', - accessType: 'READ', - accepts: [ - { - arg: 'expeditionFk', - type: 'integer', - }, - ], - http: { - path: `/getPallet`, - verb: 'GET' - }, - returns: { - type: 'object', - root: true - }, - }); - - Self.getPallet = async(ctx, expeditionFk, options) => { - const myOptions = {}; - const $t = ctx.req.__; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - try { - const pallet = await Self.findOne({ - fields: ['truckFk'], - where: { - id: expeditionFk - }, - include: [ - { - relation: 'expeditionTruck', - scope: { - fields: ['eta', 'description'] - } - } - ], - }, myOptions); - - if (pallet) { - const truck = pallet.expeditionTruck(); - return { - truckFk: pallet.truckFk, - eta: truck.eta, - description: truck.description - }; - } - - throw new UserError($t('This pallet does not exist')); - } catch (e) { - return {message: e.message}; - } - }; -}; diff --git a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js b/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js deleted file mode 100644 index 497fe04bb..000000000 --- a/modules/ticket/back/methods/expedition-pallet/specs/getPallet.spec.js +++ /dev/null @@ -1,32 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('expeditonPallet getPallet()', () => { - beforeAll(async() => { - ctx = { - req: { - headers: {origin: 'http://localhost'}, - __: value => value - } - }; - }); - - it('should obtain the pallet data', async() => { - const palletId = 1; - const pallet = await models.ExpeditionPallet.getPallet(ctx, palletId); - - expect(pallet).toBeDefined(); - expect(pallet.truckFk).toEqual(1); - expect(pallet.description).toEqual('BEST TRUCK IN FLEET'); - }); - - it('should throw an error when the pallet does not exist', async() => { - const palletId = 600; - try { - await models.ExpeditionPallet.getPallet(ctx, palletId); - } catch (e) { - const error = e; - - expect(error.message).toEqual('This pallet does not exist'); - } - }); -}); diff --git a/modules/ticket/back/methods/sale-tracking/delete.js b/modules/ticket/back/methods/sale-tracking/delete.js index 5efd267dc..859f26354 100644 --- a/modules/ticket/back/methods/sale-tracking/delete.js +++ b/modules/ticket/back/methods/sale-tracking/delete.js @@ -14,10 +14,6 @@ module.exports = Self => { type: ['string'] }, ], - returns: { - type: 'boolean', - root: true - }, http: { path: `/delete`, verb: 'POST' @@ -63,8 +59,6 @@ module.exports = Self => { await saleTracking.destroy(myOptions); if (tx) await tx.commit(); - - return true; } catch (e) { if (tx) await tx.rollback(); throw e; diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/mark.js index dd6cbc781..71fdfa048 100644 --- a/modules/ticket/back/methods/sale-tracking/mark.js +++ b/modules/ticket/back/methods/sale-tracking/mark.js @@ -54,7 +54,6 @@ module.exports = Self => { Self.mark = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned, quantity, itemShelvingFk, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; - const $t = ctx.req.__; const myOptions = {}; let tx; @@ -90,18 +89,18 @@ module.exports = Self => { const buy = await models.Buy.findById(buyFk, myOptions); if (buy.itemOriginalFk) await models.SaleBuy.create({saleFk, buyFk}, myOptions); } catch (e) { - throw new UserError($t('The sale cannot be tracked')); + throw new UserError('The sale cannot be tracked'); } if (tx) await tx.commit(); } catch (e) { - if (e.message == $t('The sale cannot be tracked')) { + if (e.message == 'The sale cannot be tracked') { if (tx) tx.commit(); throw e; } if (tx) await tx.rollback(); - throw new UserError($t('The line could not be marked')); + throw new UserError('The line could not be marked'); } }; }; diff --git a/modules/ticket/back/methods/sale-tracking/specs/delete.spec.js b/modules/ticket/back/methods/sale-tracking/specs/delete.spec.js index e23c12a61..bb66db4f3 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/delete.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/delete.spec.js @@ -12,12 +12,11 @@ describe('sale-tracking delete()', () => { const saleFk = 1; const stateCode = ['PREPARED']; - const result = await models.SaleTracking.delete(saleFk, stateCode, options); + await models.SaleTracking.delete(saleFk, stateCode, options); const itemShelvingsAfter = await models.ItemShelvingSale.find(null, options); const saleTrackingsAfter = await models.SaleTracking.find(null, options); - expect(result).toEqual(true); expect(saleTrackingsAfter.length).toBeLessThan(saleTrackingsBefore.length); expect(itemShelvingsAfter.length).toBeLessThan(itemShelvingsBefore.length); diff --git a/modules/ticket/back/methods/sale-tracking/updateTracking.js b/modules/ticket/back/methods/sale-tracking/updateTracking.js index 22ff141d8..2ce8ddaba 100644 --- a/modules/ticket/back/methods/sale-tracking/updateTracking.js +++ b/modules/ticket/back/methods/sale-tracking/updateTracking.js @@ -43,7 +43,6 @@ module.exports = Self => { Self.updateTracking = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned = null, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; - const $t = ctx.req.__; const myOptions = {}; let tx; @@ -60,7 +59,7 @@ module.exports = Self => { where: {code}, }, myOptions); - if (!state) throw new UserError($t('this state does not exist')); + if (!state) throw new UserError('this state does not exist'); const uniqueAttributes = { saleFk, workerFk: userId, diff --git a/modules/ticket/back/models/expeditionPallet.js b/modules/ticket/back/models/expeditionPallet.js deleted file mode 100644 index f41ad7712..000000000 --- a/modules/ticket/back/models/expeditionPallet.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function(Self) { - require('../methods/expedition-pallet/getPallet')(Self); -}; diff --git a/modules/ticket/back/models/sale-buy.json b/modules/ticket/back/models/sale-buy.json index 60ff2bef4..a431f1224 100644 --- a/modules/ticket/back/models/sale-buy.json +++ b/modules/ticket/back/models/sale-buy.json @@ -9,8 +9,7 @@ "properties": { "saleFk": { "id": true, - "type": "number", - "forceId": false + "type": "number" }, "buyFk": { "type": "number" diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index 770fb3c5b..f20b00976 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -72,7 +72,7 @@ module.exports = Self => { if (item.family == 'EMB') return; const isInPreparing = await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*'); - if (!ctx.isNEwInstance && isInPreparing) return; + if (!ctx.isNewInstance && isInPreparing) return; await models.Sale.rawSql(`CALL catalog_calcFromItem(?,?,?,?)`, [ ticket.landed, diff --git a/modules/worker/back/methods/operator/add.js b/modules/worker/back/methods/operator/add.js index d330bc25b..150380513 100644 --- a/modules/worker/back/methods/operator/add.js +++ b/modules/worker/back/methods/operator/add.js @@ -1,4 +1,3 @@ -const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('add', { description: 'Add a new operator', @@ -12,7 +11,6 @@ module.exports = Self => { Self.add = async(ctx, options) => { const userId = ctx.req.accessToken.userId; const myOptions = {}; - const $t = ctx.req.__; let tx; if (typeof options == 'object') @@ -24,13 +22,13 @@ module.exports = Self => { } try { - await Self.create({ - workerFk: userId - }); + const isOperator = await Self.findById(user, myOptions); + if (!isOperator) await Self.create({workerFk: userId}, myOptions); + if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); - throw new UserError($t('This worker does not exist')); + throw e; } }; }; From ec7a88c6dd6e4ea644c2cf70b791225676dd02bc Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 1 Feb 2024 12:56:11 +0100 Subject: [PATCH 081/150] fix: refs #6703 tests, backs & fixtures --- db/dump/fixtures.before.sql | 175 +++++++++--------- loopback/server/connectors/vn-mysql.js | 8 +- .../methods/sale-tracking/updateTracking.js | 1 + modules/ticket/back/models/sale-buy.json | 3 + modules/ticket/back/models/specs/sale.spec.js | 21 ++- modules/worker/back/methods/operator/add.js | 17 +- 6 files changed, 117 insertions(+), 108 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 257e8c5cf..0d815d23a 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3094,9 +3094,7 @@ INSERT IGNORE INTO vn.sector SET id = 9991, description = 'NormalSector', warehouseFk = 999, - isPreviousPreparedByPacking = FALSE, code = 'NS', - isPreviousPrepared = FALSE, isPackagingArea = FALSE, sonFk = NULL, isMain = TRUE, @@ -3106,9 +3104,7 @@ INSERT IGNORE INTO vn.sector SET id = 9992, description = 'PreviousSector', warehouseFk = 999, - isPreviousPreparedByPacking = FALSE, code = 'PS', - isPreviousPrepared = TRUE, isPackagingArea = FALSE, sonFk = NULL, isMain = TRUE, @@ -3118,41 +3114,38 @@ INSERT IGNORE INTO vn.sector SET id = 9993, description = 'MezaninneSector', warehouseFk = 999, - isPreviousPreparedByPacking = TRUE, code = 'MS', - isPreviousPrepared = FALSE, isPackagingArea = FALSE, sonFk = 9991, isMain = TRUE, itemPackingTypeFk = NULL; -REPLACE vn.parking SET id = 9991011, sectorFk = 9991, code = 'A-01-1', pickingOrder = 1; -REPLACE vn.parking SET id = 9991012, sectorFk = 9991, code = 'A-02-2', pickingOrder = 2; -REPLACE vn.parking SET id = 9991013, sectorFk = 9991, code = 'A-03-3', pickingOrder = 3; -REPLACE vn.parking SET id = 9991014, sectorFk = 9991, code = 'A-04-4', pickingOrder = 4; -REPLACE vn.parking SET id = 9991015, sectorFk = 9991, code = 'A-05-5', pickingOrder = 5; -REPLACE vn.parking SET id = 9992011, sectorFk = 9992, code = 'P-01-1', pickingOrder = 6; -REPLACE vn.parking SET id = 9992012, sectorFk = 9992, code = 'P-02-2', pickingOrder = 7; -REPLACE vn.parking SET id = 9992013, sectorFk = 9992, code = 'P-03-3', pickingOrder = 8; +INSERT INTO vn.parking (id,sectorFk, code, pickingOrder) + VALUES (4,9991, 'A-01-1', 1), + (5,9991, 'A-02-2', 2), + (6,9991, 'A-03-3', 3), + (7,9991, 'A-04-4', 4), + (8,9991, 'A-05-5', 5), + (9,9992, 'P-01-1', 6), + (10,9992, 'P-02-2', 7), + (11,9992, 'P-03-3', 8), + (12,9993, 'M-01-1', 9), + (13,9993, 'M-02-2', 10), + (14,9993, 'M-03-3', 11); -REPLACE vn.parking SET id = 9993011, sectorFk = 9993, code = 'M-01-1', pickingOrder = 9; -REPLACE vn.parking SET id = 9993012, sectorFk = 9993, code = 'M-02-2', pickingOrder = 10; -REPLACE vn.parking SET id = 9993013, sectorFk = 9993, code = 'M-03-3', pickingOrder = 11; - -REPLACE vn.shelving SET code = 'NAA', parkingFk = 9991011, priority = 1; -REPLACE vn.shelving SET code = 'NBB', parkingFk = 9991012, priority = 1; -REPLACE vn.shelving SET code = 'NCC', parkingFk = 9991013, priority = 1; -REPLACE vn.shelving SET code = 'NDD', parkingFk = 9991014, priority = 1; -REPLACE vn.shelving SET code = 'NEE', parkingFk = 9991015, priority = 1; - -REPLACE vn.shelving SET code = 'PAA', parkingFk = 9992011, priority = 1; -REPLACE vn.shelving SET code = 'PBB', parkingFk = 9992012, priority = 1; -REPLACE vn.shelving SET code = 'PCC', parkingFk = 9992013, priority = 1; - -REPLACE vn.shelving SET code = 'MAA', parkingFk = 9993011, priority = 1; -REPLACE vn.shelving SET code = 'MBB', parkingFk = 9993012, priority = 1; -REPLACE vn.shelving SET code = 'MCC', parkingFk = 9993013, priority = 1; +INSERT INTO vn.shelving (code, parkingFk, priority) + VALUES ('NAA', 4, 1), + ('NBB', 5, 1), + ('NCC', 6, 1), + ('NDD', 7, 1), + ('NEE', 8, 1), + ('PAA', 9, 1), + ('PBB', 10, 1), + ('PCC', 11, 1), + ('MAA', 12, 1), + ('MBB', 13, 1), + ('MCC', 14, 1); INSERT IGNORE INTO vn.itemType SET id = 999, @@ -3172,10 +3165,9 @@ INSERT IGNORE INTO vn.travel landed = CURDATE(), warehouseInFk = 999, warehouseOutFk = 1, - isReceived = TRUE, - agencyFk = 1; + isReceived = TRUE; -REPLACE vn.entry +INSERT INTO vn.entry SET id = 999, supplierFk = 791, isConfirmed = TRUE, @@ -3183,7 +3175,7 @@ REPLACE vn.entry travelFk = 99, companyFk = 442; -REPLACE vn.ticket +INSERT INTO vn.ticket SET id = 999999, clientFk = 2, warehouseFk = 999, @@ -3194,7 +3186,7 @@ REPLACE vn.ticket agencyModeFk = 10, landed = CURDATE(); -REPLACE vn.collection +INSERT INTO vn.collection SET id = 10101010, workerFk = 9; @@ -3203,7 +3195,7 @@ INSERT IGNORE INTO vn.ticketCollection ticketFk = 999999, collectionFk = 10101010; -REPLACE vn.item +INSERT INTO vn.item SET id = 999991, name = 'Palito para pinchos', `size` = 25, @@ -3216,7 +3208,7 @@ REPLACE vn.item weightByPiece = 6, intrastatFk = 44219999; -REPLACE vn.buy +INSERT INTO vn.buy SET id = 9999991, entryFk = 999, itemFk = 999991, @@ -3233,7 +3225,7 @@ REPLACE vn.buy minPrice = 1, weight = 50; -REPLACE vn.sale +INSERT INTO vn.sale SET id = 99991, itemFk = 999991, ticketFk = 999999, @@ -3242,7 +3234,7 @@ REPLACE vn.sale price = 1, discount = 0; -REPLACE vn.item +INSERT INTO vn.item SET id = 999992, name = 'Madera verde', `size` = 10, @@ -3255,7 +3247,7 @@ REPLACE vn.item weightByPiece = 50, intrastatFk = 44219999; -REPLACE vn.buy +INSERT INTO vn.buy SET id = 9999992, entryFk = 999, itemFk = 999992, @@ -3272,7 +3264,7 @@ REPLACE vn.buy minPrice = 1, weight = 25; -REPLACE vn.sale +INSERT INTO vn.sale SET id = 99992, itemFk = 999992, ticketFk = 999999, @@ -3281,7 +3273,7 @@ REPLACE vn.sale price = 1, discount = 0; -REPLACE vn.item +INSERT INTO vn.item SET id = 999993, name = 'Madera Roja/Morada', `size` = 12, @@ -3294,7 +3286,7 @@ REPLACE vn.item weightByPiece = 35, intrastatFk = 44219999; -REPLACE vn.buy +INSERT INTO vn.buy SET id = 9999993, entryFk = 999, itemFk = 999993, @@ -3311,7 +3303,7 @@ REPLACE vn.buy minPrice = 1, weight = 25; -REPLACE vn.itemShelving +INSERT INTO vn.itemShelving SET id = 9931, itemFk = 999993, shelvingFk = 'NCC', @@ -3319,7 +3311,7 @@ REPLACE vn.itemShelving `grouping` = 5, packing = 10; -REPLACE vn.sale +INSERT INTO vn.sale SET id = 99993, itemFk = 999993, ticketFk = 999999, @@ -3328,7 +3320,7 @@ REPLACE vn.sale price = 1, discount = 0; -REPLACE vn.item +INSERT INTO vn.item SET id = 999994, name = 'Madera Naranja', `size` = 18, @@ -3341,7 +3333,7 @@ REPLACE vn.item weightByPiece = 160, intrastatFk = 44219999; -REPLACE vn.buy +INSERT INTO vn.buy SET id = 9999994, entryFk = 999, itemFk = 999994, @@ -3358,7 +3350,7 @@ REPLACE vn.buy minPrice = 1, weight = 25; -REPLACE vn.sale +INSERT INTO vn.sale SET id = 99994, itemFk = 999994, ticketFk = 999999, @@ -3367,7 +3359,7 @@ REPLACE vn.sale price = 1, discount = 0; -REPLACE vn.item +INSERT INTO vn.item SET id = 999995, name = 'Madera Amarilla', `size` = 11, @@ -3380,7 +3372,7 @@ REPLACE vn.item weightByPiece = 78, intrastatFk = 44219999; -REPLACE vn.buy +INSERT INTO vn.buy SET id = 9999995, entryFk = 999, itemFk = 999995, @@ -3397,7 +3389,7 @@ REPLACE vn.buy minPrice = 1, weight = 35; -REPLACE vn.sale +INSERT INTO vn.sale SET id = 99995, itemFk = 999995, ticketFk = 999999, @@ -3407,7 +3399,7 @@ REPLACE vn.sale discount = 0; -- Palito naranja -REPLACE vn.item +INSERT INTO vn.item SET id = 999998, name = 'Palito naranja', `size` = 11, @@ -3420,7 +3412,7 @@ REPLACE vn.item weightByPiece = 78, intrastatFk = 44219999; -REPLACE vn.buy +INSERT INTO vn.buy SET id = 9999998, entryFk = 999, itemFk = 999998, @@ -3437,7 +3429,7 @@ REPLACE vn.buy minPrice = 1, weight = 35; -REPLACE vn.sale +INSERT INTO vn.sale SET id = 99998, itemFk = 999998, ticketFk = 999999, @@ -3447,7 +3439,7 @@ REPLACE vn.sale discount = 0; -- Palito amarillo -REPLACE vn.item +INSERT INTO vn.item SET id = 999999, name = 'Palito amarillo', `size` = 11, @@ -3460,7 +3452,7 @@ REPLACE vn.item weightByPiece = 78, intrastatFk = 44219999; -REPLACE vn.buy +INSERT INTO vn.buy SET id = 9999999, entryFk = 999, itemFk = 999999, @@ -3477,7 +3469,7 @@ REPLACE vn.buy minPrice = 1, weight = 35; -REPLACE vn.sale +INSERT INTO vn.sale SET id = 99999, itemFk = 999999, ticketFk = 999999, @@ -3487,7 +3479,7 @@ REPLACE vn.sale discount = 0; -- Palito azul -REPLACE vn.item +INSERT INTO vn.item SET id = 1000000, name = 'Palito azul', `size` = 10, @@ -3500,7 +3492,7 @@ REPLACE vn.item weightByPiece = 78, intrastatFk = 44219999; -REPLACE vn.buy +INSERT INTO vn.buy SET id = 10000000, entryFk = 999, itemFk = 1000000, @@ -3517,7 +3509,7 @@ REPLACE vn.buy minPrice = 1, weight = 35; -REPLACE vn.sale +INSERT INTO vn.sale SET id = 100000, itemFk = 1000000, ticketFk = 999999, @@ -3527,7 +3519,7 @@ REPLACE vn.sale discount = 0; -- Palito rojo -REPLACE vn.item +INSERT INTO vn.item SET id = 1000001, name = 'Palito rojo', `size` = 10, @@ -3540,7 +3532,7 @@ REPLACE vn.item weightByPiece = 78, intrastatFk = 44219999; -REPLACE vn.buy +INSERT INTO vn.buy SET id = 10000001, entryFk = 999, itemFk = 1000001, @@ -3558,7 +3550,7 @@ REPLACE vn.buy weight = 35; -REPLACE vn.sale +INSERT INTO vn.sale SET id = 100001, itemFk = 1000001, ticketFk = 999999, @@ -3581,7 +3573,7 @@ INSERT IGNORE INTO vn.item weightByPiece = 20, intrastatFk = 44219999; -REPLACE vn.buy +INSERT vn.buy SET id = 9999996, entryFk = 999, itemFk = 999996, @@ -3598,7 +3590,7 @@ REPLACE vn.buy minPrice = 7, weight = 80; -REPLACE vn.sale +INSERT vn.sale SET id = 99996, itemFk = 999996, ticketFk = 999999, @@ -3621,7 +3613,7 @@ INSERT IGNORE INTO vn.item weightByPiece = 20, intrastatFk = 44219999; -REPLACE vn.buy +INSERT vn.buy SET id = 9999997, entryFk = 999, itemFk = 999997, @@ -3638,7 +3630,7 @@ REPLACE vn.buy minPrice = 7, weight = 80; -REPLACE vn.sale +INSERT vn.sale SET id = 99997, itemFk = 999997, ticketFk = 999999, @@ -3655,25 +3647,25 @@ DELETE ish.* FROM vn.itemShelving ish JOIN vn.warehouse w ON w.id = s.warehouseFk WHERE w.name = 'TestingWarehouse'; -REPLACE vn.itemShelving -(id, itemFk, shelvingFk, visible, created, `grouping`, packing, packagingFk, userFk, isChecked) +INSERT INTO vn.itemShelving +(itemFk, shelvingFk, visible, created, `grouping`, packing, packagingFk, userFk, isChecked) VALUES - (9911, 999991, 'NAA', 8, '2023-09-20', 1, 20, NULL, 103, NULL), - (9912, 999998, 'NAA', 80, '2023-09-20', 10, 30, NULL, 103, NULL), - (9913, 1000001, 'NAA', 6, '2023-09-20', 3, 50, NULL, 103, NULL), - (9914, 1000000, 'NBB', 50, '2023-09-18', 25, 500, NULL, 103, NULL), - (9915, 999993, 'NBB', 25, '2023-09-18', NULL, 10, NULL, 103, NULL), - (9916, 999999, 'NBB', 30, '2023-09-18', 10, 500, NULL, 103, NULL), - (9917, 999993, 'NCC', 25, '2023-09-20', 5, 10, NULL, 103, NULL), - (9918, 999997, 'NCC', 10, '2023-09-20', NULL, 100, NULL, 103, NULL), - (9919, 999999, 'NCC', 40, '2023-09-20', 10, 500, NULL, 103, NULL), - (9920, 999995, 'NDD', 10, '2023-09-19', NULL, 20, NULL, 103, NULL), - (9921, 999994, 'NDD', 48, '2023-09-19', 4, 20, NULL, 103, NULL), - (9922, 1000001, 'NEE', 6, '2023-09-21', 3, 50, NULL, 103, NULL), - (9923, 999992, 'NEE', 50, '2023-09-21', NULL, 1, NULL, 103, NULL), - (9924, 1000000, 'NEE', 25, '2023-09-21', 25, 500, NULL, 103, NULL), - (9925, 999996, 'PAA', 5, '2023-09-27', 1, 5, NULL, 103, NULL), - (9926, 999997, 'PCC', 10, '2023-09-27', 5, 100, NULL, 103, NULL); + (999991, 'NAA', 8, '2023-09-20', 1, 20, NULL, 103, NULL), + (999998, 'NAA', 80, '2023-09-20', 10, 30, NULL, 103, NULL), + (1000001, 'NAA', 6, '2023-09-20', 3, 50, NULL, 103, NULL), + (1000000, 'NBB', 50, '2023-09-18', 25, 500, NULL, 103, NULL), + (999993, 'NBB', 25, '2023-09-18', NULL, 10, NULL, 103, NULL), + (999999, 'NBB', 30, '2023-09-18', 10, 500, NULL, 103, NULL), + (999993, 'NCC', 25, '2023-09-20', 5, 10, NULL, 103, NULL), + (999997, 'NCC', 10, '2023-09-20', NULL, 100, NULL, 103, NULL), + (999999, 'NCC', 40, '2023-09-20', 10, 500, NULL, 103, NULL), + (999995, 'NDD', 10, '2023-09-19', NULL, 20, NULL, 103, NULL), + (999994, 'NDD', 48, '2023-09-19', 4, 20, NULL, 103, NULL), + (1000001, 'NEE', 6, '2023-09-21', 3, 50, NULL, 103, NULL), + (999992, 'NEE', 50, '2023-09-21', NULL, 1, NULL, 103, NULL), + (1000000, 'NEE', 25, '2023-09-21', 25, 500, NULL, 103, NULL), + (999996, 'PAA', 5, '2023-09-27', 1, 5, NULL, 103, NULL), + (999997, 'PCC', 10, '2023-09-27', 5, 100, NULL, 103, NULL); -- Previous for Bolas de madera INSERT IGNORE INTO vn.sectorCollection @@ -3682,9 +3674,9 @@ INSERT IGNORE INTO vn.sectorCollection sectorFk = 9992; INSERT IGNORE INTO vn.saleGroup - SET id = 999, + SET id = 4, userFk = 1, - parkingFk = 9992011, + parkingFk = 9, sectorFk = 9992; INSERT IGNORE INTO vn.sectorCollectionSaleGroup @@ -3692,13 +3684,14 @@ INSERT IGNORE INTO vn.sectorCollectionSaleGroup sectorCollectionFk = 99, saleGroupFk = 999; -REPLACE vn.saleGroupDetail +INSERT vn.saleGroupDetail SET id = 99991, saleFk = 99996, saleGroupFk = 999; -REPLACE vn.saleTracking - SET saleFk = 99996, +INSERT INTO vn.saleTracking + SET id = 7, + saleFk = 99996, isChecked = TRUE, workerFk = 103, stateFk = 28; diff --git a/loopback/server/connectors/vn-mysql.js b/loopback/server/connectors/vn-mysql.js index 7c086ff9b..737fd94d5 100644 --- a/loopback/server/connectors/vn-mysql.js +++ b/loopback/server/connectors/vn-mysql.js @@ -268,8 +268,14 @@ class VnMySQL extends MySQL { arguments, model, ctx, opts, cb); } + isLoggable(model) { + const Model = this.getModelDefinition(model).model; + const {settings} = Model.definition; + return settings.mixins?.Loggable; + } + invokeMethod(method, args, model, ctx, opts, cb) { - if (!opts?.httpCtx) + if (!this.isLoggable(model)) return super[method].apply(this, args); this.invokeMethodP(method, [...args], model, ctx, opts) diff --git a/modules/ticket/back/methods/sale-tracking/updateTracking.js b/modules/ticket/back/methods/sale-tracking/updateTracking.js index 2ce8ddaba..50e117084 100644 --- a/modules/ticket/back/methods/sale-tracking/updateTracking.js +++ b/modules/ticket/back/methods/sale-tracking/updateTracking.js @@ -97,6 +97,7 @@ module.exports = Self => { } }, myOptions); } + if (isBuy) await models.SaleBuy.create({saleFk, buyFk}, myOptions); diff --git a/modules/ticket/back/models/sale-buy.json b/modules/ticket/back/models/sale-buy.json index a431f1224..496a8d6fa 100644 --- a/modules/ticket/back/models/sale-buy.json +++ b/modules/ticket/back/models/sale-buy.json @@ -1,6 +1,9 @@ { "name": "SaleBuy", "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "saleBuy" diff --git a/modules/ticket/back/models/specs/sale.spec.js b/modules/ticket/back/models/specs/sale.spec.js index d078dc8e2..979b86108 100644 --- a/modules/ticket/back/models/specs/sale.spec.js +++ b/modules/ticket/back/models/specs/sale.spec.js @@ -3,7 +3,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -describe('sale model ', () => { +fdescribe('sale model ', () => { const ctx = { req: { accessToken: {userId: 9}, @@ -233,6 +233,25 @@ describe('sale model ', () => { } }); + it('should change the quantity if it has production role and is not a new instance', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + const tx = await models.Sale.beginTransaction({}); + const options = {transaction: tx}; + + try { + const saleId = 1; + const newQuantity = 10; + + const {quantity} = await models.Collection.setSaleQuantity(saleId, newQuantity, options); + + expect(quantity).toEqual(newQuantity); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + describe('newPrice', () => { it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { const ctx = { diff --git a/modules/worker/back/methods/operator/add.js b/modules/worker/back/methods/operator/add.js index 150380513..6fa780588 100644 --- a/modules/worker/back/methods/operator/add.js +++ b/modules/worker/back/methods/operator/add.js @@ -11,24 +11,11 @@ module.exports = Self => { Self.add = async(ctx, options) => { const userId = ctx.req.accessToken.userId; const myOptions = {}; - let tx; if (typeof options == 'object') Object.assign(myOptions, options); - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - - try { - const isOperator = await Self.findById(user, myOptions); - if (!isOperator) await Self.create({workerFk: userId}, myOptions); - - if (tx) await tx.commit(); - } catch (e) { - if (tx) await tx.rollback(); - throw e; - } + const isOperator = await Self.findById(user, myOptions); + if (!isOperator) await Self.create({workerFk: userId}, myOptions); }; }; From 21cf05ddd0a2057b6bb865143fa4adec28a8ec06 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 2 Feb 2024 09:23:29 +0100 Subject: [PATCH 082/150] fix: refs #6276 fix tests & errors --- .../item-shelving/specs/return.spec.js | 2 +- modules/item/back/methods/item/card.js | 11 +++++++--- modules/ticket/back/models/specs/sale.spec.js | 2 +- .../travel/specs/extraCommunityFilter.spec.js | 2 +- .../back/methods/travel/specs/filter.spec.js | 2 +- modules/worker/back/methods/operator/add.js | 2 +- .../back/methods/operator/spec/add.spec.js | 21 ++++++++++++------- 7 files changed, 26 insertions(+), 16 deletions(-) diff --git a/modules/item/back/methods/item-shelving/specs/return.spec.js b/modules/item/back/methods/item-shelving/specs/return.spec.js index 07ddc2168..a5edc0ade 100644 --- a/modules/item/back/methods/item-shelving/specs/return.spec.js +++ b/modules/item/back/methods/item-shelving/specs/return.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -fdescribe('itemShelving return()', () => { +describe('itemShelving return()', () => { beforeAll(async() => { ctx = { req: { diff --git a/modules/item/back/methods/item/card.js b/modules/item/back/methods/item/card.js index 5d086ce88..8ee4ccc6b 100644 --- a/modules/item/back/methods/item/card.js +++ b/modules/item/back/methods/item/card.js @@ -24,12 +24,17 @@ module.exports = Self => { }, }); - Self.card = async(itemFk, warehouseFk) => { + Self.card = async(itemFk, warehouseFk, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const models = Self.app.models; - const [[itemInfo]] = await Self.rawSql('CALL vn.item_getInfo(?, ?)', [itemFk, warehouseFk]); + const [[itemInfo]] = await Self.rawSql('CALL vn.item_getInfo(?, ?)', [itemFk, warehouseFk], myOptions); - const barcodeItems = await Self.rawSql('SELECT vn.barcodeToItem(?) as realIdItem', [itemFk]); + const barcodeItems = await Self.rawSql('SELECT vn.barcodeToItem(?) as realIdItem', [itemFk], myOptions); const [realIdItem] = barcodeItems.map(barcodeItem => barcodeItem.realIdItem); const barcodes = await models.ItemBarcode.find({ diff --git a/modules/ticket/back/models/specs/sale.spec.js b/modules/ticket/back/models/specs/sale.spec.js index 979b86108..26d64cfe2 100644 --- a/modules/ticket/back/models/specs/sale.spec.js +++ b/modules/ticket/back/models/specs/sale.spec.js @@ -3,7 +3,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -fdescribe('sale model ', () => { +describe('sale model ', () => { const ctx = { req: { accessToken: {userId: 9}, diff --git a/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js index 1ce55cc91..599851b55 100644 --- a/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js +++ b/modules/travel/back/methods/travel/specs/extraCommunityFilter.spec.js @@ -79,7 +79,7 @@ describe('Travel extraCommunityFilter()', () => { const result = await app.models.Travel.extraCommunityFilter(ctx, filter); - expect(result.length).toEqual(9); + expect(result.length).toEqual(8); }); it('should return the travel matching "cargoSupplierFk"', async() => { diff --git a/modules/travel/back/methods/travel/specs/filter.spec.js b/modules/travel/back/methods/travel/specs/filter.spec.js index 6cb366938..1a6ee895c 100644 --- a/modules/travel/back/methods/travel/specs/filter.spec.js +++ b/modules/travel/back/methods/travel/specs/filter.spec.js @@ -80,6 +80,6 @@ describe('Travel filter()', () => { const result = await app.models.Travel.filter(ctx); - expect(result.length).toEqual(6); + expect(result.length).toEqual(5); }); }); diff --git a/modules/worker/back/methods/operator/add.js b/modules/worker/back/methods/operator/add.js index 6fa780588..efd610562 100644 --- a/modules/worker/back/methods/operator/add.js +++ b/modules/worker/back/methods/operator/add.js @@ -15,7 +15,7 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const isOperator = await Self.findById(user, myOptions); + const isOperator = await Self.findById(userId, myOptions); if (!isOperator) await Self.create({workerFk: userId}, myOptions); }; }; diff --git a/modules/worker/back/methods/operator/spec/add.spec.js b/modules/worker/back/methods/operator/spec/add.spec.js index 4d26e8ca9..94daae8de 100644 --- a/modules/worker/back/methods/operator/spec/add.spec.js +++ b/modules/worker/back/methods/operator/spec/add.spec.js @@ -1,8 +1,8 @@ const {models} = require('vn-loopback/server/server'); describe('operator add()', () => { - const itBoss = 104; - const noWorker = 100000; + const noOperator = 104; + const operator = 9; beforeAll(async() => { ctx = { @@ -14,18 +14,23 @@ describe('operator add()', () => { }; }); - it('should throw an error if the worker does not exist', async() => { + it('should not add an existent operator', async() => { const tx = await models.Operator.beginTransaction({}); const options = {transaction: tx}; - ctx.req.accessToken.userId = noWorker; + ctx.req.accessToken.userId = operator; try { + const operatorBefore = await models.Operator.find(null, options); + const isOperator = await models.Operator.findOne(null, options); + + expect(isOperator).toBeDefined(); + await models.Operator.add(ctx, options); + const operatorAfter = await models.Operator.find(null, options); + + expect(operatorBefore.length).toEqual(operatorAfter.length); await tx.rollback(); } catch (e) { - const error = e; - - expect(error.message).toEqual('This worker does not exist'); await tx.rollback(); } }); @@ -33,7 +38,7 @@ describe('operator add()', () => { it('should add a new operator successfully', async() => { const tx = await models.Operator.beginTransaction({}); const options = {transaction: tx}; - ctx.req.accessToken.userId = itBoss; + ctx.req.accessToken.userId = noOperator; try { const operatorBefore = await models.Operator.find(null, options); From 9f194f4f63a9421cf0dbba7980b0923459c0b2d0 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 2 Feb 2024 10:28:13 +0100 Subject: [PATCH 083/150] fix: refs #6276 fix model --- modules/ticket/back/models/sale-buy.json | 3 --- 1 file changed, 3 deletions(-) diff --git a/modules/ticket/back/models/sale-buy.json b/modules/ticket/back/models/sale-buy.json index 496a8d6fa..a431f1224 100644 --- a/modules/ticket/back/models/sale-buy.json +++ b/modules/ticket/back/models/sale-buy.json @@ -1,9 +1,6 @@ { "name": "SaleBuy", "base": "VnModel", - "mixins": { - "Loggable": true - }, "options": { "mysql": { "table": "saleBuy" From fa32cf37cd35bb7a9aa625b8f7c070cf12aacf4a Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 2 Feb 2024 14:04:20 +0100 Subject: [PATCH 084/150] refs #6053 cpus --- jest.front.config.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/jest.front.config.js b/jest.front.config.js index 3289df8bb..955f06eca 100644 --- a/jest.front.config.js +++ b/jest.front.config.js @@ -1,7 +1,9 @@ // For a detailed explanation regarding each configuration property, visit: // https://jestjs.io/docs/en/configuration.html /* eslint max-len: ["error", { "code": 150 }]*/ +const cpus = require('os').cpus().length; +const maxCpus = Math.floor(cpus / 5) - 1; module.exports = { name: 'front end', displayName: { @@ -12,6 +14,7 @@ module.exports = { setupFilesAfterEnv: [ './jest-front.js' ], + maxWorkers: maxCpus, testMatch: [ '**/front/**/*.spec.js', '**/print/**/*.spec.js', From 8ad69a62b9a245f9d504dea7688777afcccf227d Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 8 Feb 2024 10:08:16 +0100 Subject: [PATCH 085/150] fix: refs #6276 loggable & userId --- loopback/common/mixins/loggable.js | 3 ++- loopback/server/connectors/vn-mysql.js | 6 +++--- modules/ticket/back/methods/sale-tracking/updateTracking.js | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/loopback/common/mixins/loggable.js b/loopback/common/mixins/loggable.js index 760fdf60a..24243ba68 100644 --- a/loopback/common/mixins/loggable.js +++ b/loopback/common/mixins/loggable.js @@ -1,6 +1,7 @@ const LoopBackContext = require('loopback-context'); async function handleObserve(ctx) { - ctx.options.httpCtx = LoopBackContext.getCurrentContext(); + const httpCtx = LoopBackContext.getCurrentContext(); + ctx.options.userId = httpCtx?.active?.accessToken?.userId; } module.exports = function(Self) { let Mixin = { diff --git a/loopback/server/connectors/vn-mysql.js b/loopback/server/connectors/vn-mysql.js index 737fd94d5..5edef4395 100644 --- a/loopback/server/connectors/vn-mysql.js +++ b/loopback/server/connectors/vn-mysql.js @@ -275,7 +275,7 @@ class VnMySQL extends MySQL { } invokeMethod(method, args, model, ctx, opts, cb) { - if (!this.isLoggable(model)) + if (!this.isLoggable(model) && !opts?.userId) return super[method].apply(this, args); this.invokeMethodP(method, [...args], model, ctx, opts) @@ -287,11 +287,11 @@ class VnMySQL extends MySQL { let tx; if (!opts.transaction) { tx = await Transaction.begin(this, {}); - opts = Object.assign({transaction: tx, httpCtx: opts.httpCtx}, opts); + opts = Object.assign({transaction: tx}, opts); } try { - const userId = opts.httpCtx && opts.httpCtx.active?.accessToken?.userId; + const {userId} = opts; if (userId) { const user = await Model.app.models.VnUser.findById(userId, {fields: ['name']}, opts); await this.executeP(`CALL account.myUser_loginWithName(?)`, [user.name], opts); diff --git a/modules/ticket/back/methods/sale-tracking/updateTracking.js b/modules/ticket/back/methods/sale-tracking/updateTracking.js index 50e117084..f58429790 100644 --- a/modules/ticket/back/methods/sale-tracking/updateTracking.js +++ b/modules/ticket/back/methods/sale-tracking/updateTracking.js @@ -43,7 +43,7 @@ module.exports = Self => { Self.updateTracking = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned = null, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; - const myOptions = {}; + const myOptions = {userId}; let tx; if (typeof options == 'object') From 33cca9bfe8816c1650f73ac8ea074605020beb03 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 8 Feb 2024 14:20:05 +0100 Subject: [PATCH 086/150] fix: refs #6276 assignColletion --- back/methods/collection/assignCollection.js | 6 +-- .../collection/spec/assignCollection.spec.js | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 4 deletions(-) create mode 100644 back/methods/collection/spec/assignCollection.spec.js diff --git a/back/methods/collection/assignCollection.js b/back/methods/collection/assignCollection.js index 67a10df51..575649de8 100644 --- a/back/methods/collection/assignCollection.js +++ b/back/methods/collection/assignCollection.js @@ -20,10 +20,8 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk)', [userId], myOptions); - - const [assignedCollection] = await Self.rawSql('SELECT @vCollectionFk'); - const {'@vCollectionFk': collectionFk} = assignedCollection; + const [info, okPacket, {collectionFk}] = await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk); SELECT @vCollectionFk collectionFk', + [userId], myOptions); if (!collectionFk) throw new UserError('There are not picking tickets'); await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions); diff --git a/back/methods/collection/spec/assignCollection.spec.js b/back/methods/collection/spec/assignCollection.spec.js new file mode 100644 index 000000000..e8f3882a3 --- /dev/null +++ b/back/methods/collection/spec/assignCollection.spec.js @@ -0,0 +1,38 @@ +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('ticket assignCollection()', () => { + let ctx; + let options; + let tx; + beforeEach(async() => { + ctx = { + req: { + accessToken: {userId: 1106}, + headers: {origin: 'http://localhost'}, + __: value => value + }, + args: {} + }; + + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: ctx.req + }); + + options = {transaction: tx}; + tx = await models.Sale.beginTransaction({}); + options.transaction = tx; + }); + + afterEach(async() => { + await tx.rollback(); + }); + + it('should throw an error when there is not picking tickets', async() => { + try { + await models.Collection.assignCollection(ctx, options); + } catch (e) { + expect(e.message).toEqual('There are not picking tickets'); + } + }); +}); From c2fffd1edaf4d45b170f142f56f8182d34e6651d Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 8 Feb 2024 14:52:23 +0100 Subject: [PATCH 087/150] fix: refs #6276 drop test --- .../getSalesFromTicketOrCollection.spec.js | 20 ------------------- 1 file changed, 20 deletions(-) diff --git a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js index 8f2ea4408..50ba69401 100644 --- a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js +++ b/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js @@ -59,24 +59,4 @@ describe('collection getSalesFromTicketOrCollection()', () => { throw e; } }); - - it('should getSalesFromTicketOrCollection', async() => { - const tx = await models.Collection.beginTransaction({}); - - try { - const options = {transaction: tx}; - await models.Ticket.updateAll({id: collectionOrTicketFk}, {shipped: '2001-01-02 00:00:00.000'}, options); - - const ticketTrackingBefore = await models.TicketTracking.find(null, options); - await models.Collection.getSalesFromTicketOrCollection(ctx, - collectionOrTicketFk, false, source, options); - const ticketTrackingAfter = await models.TicketTracking.find(null, options); - - expect(ticketTrackingAfter.length).toEqual(ticketTrackingBefore.length + 1); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); }); From 2fb68e81c96e750e7817cacc8286b253121d15bf Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 15 Feb 2024 15:17:39 +0100 Subject: [PATCH 088/150] fix: refs #6276 rollback sale --- modules/ticket/back/models/sale.js | 5 ++--- modules/ticket/back/models/specs/sale.spec.js | 19 ------------------- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index 035c4cb11..6204e9a02 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -70,8 +70,7 @@ module.exports = Self => { }, ctx.options); if (item.family == 'EMB') return; - const isInPreparing = await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*'); - if (!ctx.isNewInstance && isInPreparing) return; + if (await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*')) return; await models.Sale.rawSql(`CALL catalog_calcFromItem(?,?,?,?)`, [ ticket.landed, @@ -89,7 +88,7 @@ module.exports = Self => { if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; - if (newQuantity < item.minQuantity && newQuantity != available && !isInPreparing) + if (newQuantity < item.minQuantity && newQuantity != available) throw new UserError('The amount cannot be less than the minimum'); if (ctx.isNewInstance || isReduction) return; diff --git a/modules/ticket/back/models/specs/sale.spec.js b/modules/ticket/back/models/specs/sale.spec.js index 26d64cfe2..d078dc8e2 100644 --- a/modules/ticket/back/models/specs/sale.spec.js +++ b/modules/ticket/back/models/specs/sale.spec.js @@ -233,25 +233,6 @@ describe('sale model ', () => { } }); - it('should change the quantity if it has production role and is not a new instance', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); - const tx = await models.Sale.beginTransaction({}); - const options = {transaction: tx}; - - try { - const saleId = 1; - const newQuantity = 10; - - const {quantity} = await models.Collection.setSaleQuantity(saleId, newQuantity, options); - - expect(quantity).toEqual(newQuantity); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - describe('newPrice', () => { it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { const ctx = { From 89970e39d0dd57a1217b0cb0d26dcdbfe0706505 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 16 Feb 2024 10:47:41 +0100 Subject: [PATCH 089/150] fix: refs #6276 back tests --- .../ticket/back/methods/ticket/specs/addSaleByCode.spec.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js b/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js index ce3a5b3ad..b97139178 100644 --- a/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js +++ b/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js @@ -3,7 +3,7 @@ const LoopBackContext = require('loopback-context'); describe('Ticket addSaleByCode()', () => { const quantity = 3; - const ticketFk = 24; + const ticketFk = 13; const warehouseFk = 1; beforeAll(async() => { activeCtx = { @@ -19,7 +19,7 @@ describe('Ticket addSaleByCode()', () => { }); it('should add a new sale', async() => { - const tx = await models.Sale.beginTransaction({}); + const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; From 1767ce426aa4eb80e018640a908305b373264d18 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 16 Feb 2024 11:54:59 +0100 Subject: [PATCH 090/150] fix: refs #6276 collection_addItem --- loopback/locale/es.json | 704 +++++++++--------- .../back/methods/ticket/addSaleByCode.js | 14 +- 2 files changed, 356 insertions(+), 362 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index f82152f92..e31cfc58b 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -1,360 +1,348 @@ { - "Phone format is invalid": "El formato del teléfono no es correcto", - "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito", - "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia", - "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado", - "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado", - "Can't be blank": "No puede estar en blanco", - "Invalid TIN": "NIF/CIF inválido", - "TIN must be unique": "El NIF/CIF debe ser único", - "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web", - "Is invalid": "Es inválido", - "Quantity cannot be zero": "La cantidad no puede ser cero", - "Enter an integer different to zero": "Introduce un entero distinto de cero", - "Package cannot be blank": "El embalaje no puede estar en blanco", - "The company name must be unique": "La razón social debe ser única", - "Invalid email": "Correo electrónico inválido", - "The IBAN does not have the correct format": "El IBAN no tiene el formato correcto", - "That payment method requires an IBAN": "El método de pago seleccionado requiere un IBAN", - "That payment method requires a BIC": "El método de pago seleccionado requiere un BIC", - "State cannot be blank": "El estado no puede estar en blanco", - "Worker cannot be blank": "El trabajador no puede estar en blanco", - "Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado", - "can't be blank": "El campo no puede estar vacío", - "Observation type must be unique": "El tipo de observación no puede repetirse", - "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero", - "The grade must be similar to the last one": "El grade debe ser similar al último", - "Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente", - "Name cannot be blank": "El nombre no puede estar en blanco", - "Phone cannot be blank": "El teléfono no puede estar en blanco", - "Period cannot be blank": "El periodo no puede estar en blanco", - "Choose a company": "Selecciona una empresa", - "Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto", - "Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres", - "Cannot be blank": "El campo no puede estar en blanco", - "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero", - "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco", - "Description cannot be blank": "Se debe rellenar el campo de texto", - "The price of the item changed": "El precio del artículo cambió", - "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%", - "The value should be a number": "El valor debe ser un numero", - "This order is not editable": "Esta orden no se puede modificar", - "You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado", - "You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda", - "is not a valid date": "No es una fecha valida", - "Barcode must be unique": "El código de barras debe ser único", - "The warehouse can't be repeated": "El almacén no puede repetirse", - "The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item", - "The observation type can't be repeated": "El tipo de observación no puede repetirse", - "A claim with that sale already exists": "Ya existe una reclamación para esta línea", - "You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo", - "Warehouse cannot be blank": "El almacén no puede quedar en blanco", - "Agency cannot be blank": "La agencia no puede quedar en blanco", - "Not enough privileges to edit a client with verified data": "No tienes permisos para hacer cambios en un cliente con datos comprobados", - "This address doesn't exist": "Este consignatario no existe", - "You must delete the claim id %d first": "Antes debes borrar la reclamación %d", - "You don't have enough privileges": "No tienes suficientes permisos", - "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", - "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos básicos de una orden con artículos", - "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no está permitido el uso de la letra ñ", - "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", - "You can't create a ticket for an inactive client": "No puedes crear un ticket para un cliente inactivo", - "Tag value cannot be blank": "El valor del tag no puede quedar en blanco", - "ORDER_EMPTY": "Cesta vacía", - "You don't have enough privileges to do that": "No tienes permisos para cambiar esto", - "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT", - "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido", - "Street cannot be empty": "Dirección no puede estar en blanco", - "City cannot be empty": "Ciudad no puede estar en blanco", - "Code cannot be blank": "Código no puede estar en blanco", - "You cannot remove this department": "No puedes eliminar este departamento", - "The extension must be unique": "La extensión debe ser unica", - "The secret can't be blank": "La contraseña no puede estar en blanco", - "We weren't able to send this SMS": "No hemos podido enviar el SMS", - "This client can't be invoiced": "Este cliente no puede ser facturado", - "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", - "This ticket can't be invoiced": "Este ticket no puede ser facturado", - "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", - "This ticket can not be modified": "Este ticket no puede ser modificado", - "The introduced hour already exists": "Esta hora ya ha sido introducida", - "INFINITE_LOOP": "Existe una dependencia entre dos Jefes", - "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas", - "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros", - "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado", - "The current ticket can't be modified": "El ticket actual no puede ser modificado", - "The current claim can't be modified": "La reclamación actual no puede ser modificada", - "The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", - "The sales do not exists": "La(s) línea(s) seleccionada(s) no existe(n)", - "Please select at least one sale": "Por favor selecciona al menos una linea", - "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket", - "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", - "This item doesn't exists": "El artículo no existe", - "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", - "Extension format is invalid": "El formato de la extensión es inválido", - "Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket", - "This item is not available": "Este artículo no está disponible", - "This postcode already exists": "Este código postal ya existe", - "Concept cannot be blank": "El concepto no puede quedar en blanco", - "File doesn't exists": "El archivo no existe", - "You don't have privileges to change the zone": "No tienes permisos para cambiar la zona o para esos parámetros hay más de una opción de envío, hable con las agencias", - "This ticket is already on weekly tickets": "Este ticket ya está en tickets programados", - "Ticket id cannot be blank": "El id de ticket no puede quedar en blanco", - "Weekday cannot be blank": "El día de la semana no puede quedar en blanco", - "You can't delete a confirmed order": "No puedes borrar un pedido confirmado", - "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto", - "Invalid quantity": "Cantidad invalida", - "This postal code is not valid": "Este código postal no es válido", - "is invalid": "es inválido", - "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto", - "The department name can't be repeated": "El nombre del departamento no puede repetirse", - "This phone already exists": "Este teléfono ya existe", - "You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos", - "You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado", - "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada", - "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero", - "You should specify a date": "Debes especificar una fecha", - "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fin", - "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fin", - "You should mark at least one week day": "Debes marcar al menos un día de la semana", - "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", - "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", - "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios", - "Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}", - "Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}", - "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})", - "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})", - "State": "Estado", - "regular": "normal", - "reserved": "reservado", - "Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})", - "Deny buy request": "Se ha rechazado la petición de compra para el ticket id [{{ticketId}}]({{{url}}}). Motivo: {{observation}}", - "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*", - "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})", - "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})", - "Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}", - "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", - "Claim state has changed to": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *{{newState}}*", - "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", - "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", - "Distance must be lesser than 4000": "La distancia debe ser inferior a 4000", - "This ticket is deleted": "Este ticket está eliminado", - "Unable to clone this travel": "No ha sido posible clonar este travel", - "This thermograph id already exists": "La id del termógrafo ya existe", - "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante", - "ORDER_ALREADY_CONFIRMED": "ORDEN YA CONFIRMADA", - "Invalid password": "Invalid password", - "Password does not meet requirements": "La contraseña no cumple los requisitos", - "Role already assigned": "Rol ya asignado", - "Invalid role name": "Nombre de rol no válido", - "Role name must be written in camelCase": "El nombre del rol debe escribirse en camelCase", - "Email already exists": "El correo ya existe", - "User already exists": "El/La usuario/a ya existe", - "Absence change notification on the labour calendar": "Notificación de cambio de ausencia en el calendario laboral", - "Record of hours week": "Registro de horas semana {{week}} año {{year}} ", - "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.", - "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.", - "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})", - "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})", - "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación", - "Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", - "agencyModeFk": "Agencia", - "clientFk": "Cliente", - "zoneFk": "Zona", - "warehouseFk": "Almacén", - "shipped": "F. envío", - "landed": "F. entrega", - "addressFk": "Consignatario", - "companyFk": "Empresa", - "The social name cannot be empty": "La razón social no puede quedar en blanco", - "The nif cannot be empty": "El NIF no puede quedar en blanco", - "You need to fill sage information before you check verified data": "Debes rellenar la información de sage antes de marcar datos comprobados", - "ASSIGN_ZONE_FIRST": "Asigna una zona primero", - "Amount cannot be zero": "El importe no puede ser cero", - "Company has to be official": "Empresa inválida", - "You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria", - "Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas", - "The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta", - "New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*", - "New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*", - "Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío", - "This BIC already exist.": "Este BIC ya existe.", - "That item doesn't exists": "Ese artículo no existe", - "There's a new urgent ticket:": "Hay un nuevo ticket urgente:", - "Invalid account": "Cuenta inválida", - "Compensation account is empty": "La cuenta para compensar está vacia", - "This genus already exist": "Este genus ya existe", - "This specie already exist": "Esta especie ya existe", - "Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})", - "None": "Ninguno", - "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada", - "Cannot add more than one '1/2 day vacation'": "No puedes añadir más de un 'Vacaciones 1/2 dia'", - "This document already exists on this ticket": "Este documento ya existe en el ticket", - "Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables", - "You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes", - "nickname": "nickname", - "INACTIVE_PROVIDER": "Proveedor inactivo", - "This client is not invoiceable": "Este cliente no es facturable", - "serial non editable": "Esta serie no permite asignar la referencia", - "Max shipped required": "La fecha límite es requerida", - "Can't invoice to future": "No se puede facturar a futuro", - "Can't invoice to past": "No se puede facturar a pasado", - "This ticket is already invoiced": "Este ticket ya está facturado", - "A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero", - "A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa", - "Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes", - "Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes", - "Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio", - "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito", - "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas", - "Amounts do not match": "Las cantidades no coinciden", - "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", - "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos", - "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días", - "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", - "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día", - "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado", - "The account size must be exactly 10 characters": "El tamaño de la cuenta debe ser exactamente de 10 caracteres", - "Can't transfer claimed sales": "No puedes transferir lineas reclamadas", - "You don't have privileges to create refund": "No tienes permisos para crear un abono", - "The item is required": "El artículo es requerido", - "The agency is already assigned to another autonomous": "La agencia ya está asignada a otro autónomo", - "date in the future": "Fecha en el futuro", - "reference duplicated": "Referencia duplicada", - "This ticket is already a refund": "Este ticket ya es un abono", - "isWithoutNegatives": "Sin negativos", - "routeFk": "routeFk", - "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador", - "No hay un contrato en vigor": "No hay un contrato en vigor", - "No se permite fichar a futuro": "No se permite fichar a futuro", - "No está permitido trabajar": "No está permitido trabajar", - "Fichadas impares": "Fichadas impares", - "Descanso diario 12h.": "Descanso diario 12h.", - "Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.", - "Dirección incorrecta": "Dirección incorrecta", - "Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador", - "Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador", - "Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente", - "This route does not exists": "Esta ruta no existe", - "Claim pickup order sent": "Reclamación Orden de recogida enviada [{{claimId}}]({{{claimUrl}}}) al cliente *{{clientName}}*", - "You don't have grant privilege": "No tienes privilegios para dar privilegios", - "You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario", - "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) fusionado con [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})", - "Already has this status": "Ya tiene este estado", - "There aren't records for this week": "No existen registros para esta semana", - "Empty data source": "Origen de datos vacio", - "App locked": "Aplicación bloqueada por el usuario {{userId}}", - "Email verify": "Correo de verificación", - "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment", - "Receipt's bank was not found": "No se encontró el banco del recibo", - "This receipt was not compensated": "Este recibo no ha sido compensado", - "Client's email was not found": "No se encontró el email del cliente", - "Negative basis": "Base negativa", - "This worker code already exists": "Este codigo de trabajador ya existe", - "This personal mail already exists": "Este correo personal ya existe", - "This worker already exists": "Este trabajador ya existe", - "App name does not exist": "El nombre de aplicación no es válido", - "Try again": "Vuelve a intentarlo", - "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9", - "Failed to upload delivery note": "Error al subir albarán {{id}}", - "The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe", - "It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar", - "It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo", - "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas", - "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.", - "There is no assigned email for this client": "No hay correo asignado para este cliente", - "Exists an invoice with a future date": "Existe una factura con fecha posterior", - "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite", - "Warehouse inventory not set": "El almacén inventario no está establecido", - "This locker has already been assigned": "Esta taquilla ya ha sido asignada", - "Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº %d", - "Not exist this branch": "La rama no existe", - "This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado", - "Collection does not exist": "La colección no existe", - "Cannot obtain exclusive lock": "No se puede obtener un bloqueo exclusivo", - "Insert a date range": "Inserte un rango de fechas", - "Added observation": "{{user}} añadió esta observacion: {{text}}", - "Comment added to client": "Observación añadida al cliente {{clientFk}}", - "Invalid auth code": "Código de verificación incorrecto", - "Invalid or expired verification code": "Código de verificación incorrecto o expirado", - "Cannot create a new claimBeginning from a different ticket": "No se puede crear una línea de reclamación de un ticket diferente al origen", - "company": "Compañía", - "country": "País", - "clientId": "Id cliente", - "clientSocialName": "Cliente", - "amount": "Importe", - "taxableBase": "Base", - "ticketFk": "Id ticket", - "isActive": "Activo", - "hasToInvoice": "Facturar", - "isTaxDataChecked": "Datos comprobados", - "comercialId": "Id comercial", - "comercialName": "Comercial", - "Pass expired": "La contraseña ha caducado, cambiela desde Salix", - "Invalid NIF for VIES": "Invalid NIF for VIES", - "Ticket does not exist": "Este ticket no existe", - "Ticket is already signed": "Este ticket ya ha sido firmado", - "Authentication failed": "Autenticación fallida", - "You can't use the same password": "No puedes usar la misma contraseña", - "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono", - "Fecha fuera de rango": "Fecha fuera de rango", - "Error while generating PDF": "Error al generar PDF", - "Error when sending mail to client": "Error al enviar el correo al cliente", - "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico", - "The renew period has not been exceeded": "El periodo de renovación no ha sido superado", - "Valid priorities": "Prioridades válidas: %d", - "hasAnyNegativeBase": "Base negativa para los tickets: {{ticketsIds}}", - "hasAnyPositiveBase": "Base positivas para los tickets: {{ticketsIds}}", - "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado", - "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s", - "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias", - "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado", - "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado", - "You don't have enough privileges.": "No tienes suficientes permisos.", - "This ticket is locked": "Este ticket está bloqueado.", - "This ticket is not editable.": "Este ticket no es editable.", - "The ticket doesn't exist.": "No existe el ticket.", - "Social name should be uppercase": "La razón social debe ir en mayúscula", - "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", - "Ticket without Route": "Ticket sin ruta", - "Select a different client": "Seleccione un cliente distinto", - "Fill all the fields": "Rellene todos los campos", - "The response is not a PDF": "La respuesta no es un PDF", - "Booking completed": "Reserva completada", - "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", - "Incoterms data for consignee is missing": "Faltan los datos de los Incoterms para el consignatario", - "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada", - "User disabled": "Usuario desactivado", - "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", - "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", - "Cannot past travels with entries": "No se pueden pasar envíos con entradas", - "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", - "This claim has been updated": "La reclamación con Id: {{claimId}}, ha sido actualizada", - "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada", - "Incorrect pin": "Pin incorrecto", - "You already have the mailAlias": "Ya tienes este alias de correo", - "The alias cant be modified": "Este alias de correo no puede ser modificado", - "This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado", - "Name should be uppercase": "El nombre debe ir en mayúscula", - "Bank entity must be specified": "La entidad bancaria es obligatoria", - "An email is necessary": "Es necesario un email", - "You cannot update these fields": "No puedes actualizar estos campos", - "CountryFK cannot be empty": "El país no puede estar vacío", - "Cmr file does not exist": "El archivo del cmr no existe", - "You are not allowed to modify the alias": "No estás autorizado a modificar el alias", + "Phone format is invalid": "El formato del teléfono no es correcto", + "You are not allowed to change the credit": "No tienes privilegios para modificar el crédito", + "Unable to mark the equivalence surcharge": "No se puede marcar el recargo de equivalencia", + "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado", + "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado", + "Can't be blank": "No puede estar en blanco", + "Invalid TIN": "NIF/CIF inválido", + "TIN must be unique": "El NIF/CIF debe ser único", + "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web", + "Is invalid": "Es inválido", + "Quantity cannot be zero": "La cantidad no puede ser cero", + "Enter an integer different to zero": "Introduce un entero distinto de cero", + "Package cannot be blank": "El embalaje no puede estar en blanco", + "The company name must be unique": "La razón social debe ser única", + "Invalid email": "Correo electrónico inválido", + "The IBAN does not have the correct format": "El IBAN no tiene el formato correcto", + "That payment method requires an IBAN": "El método de pago seleccionado requiere un IBAN", + "That payment method requires a BIC": "El método de pago seleccionado requiere un BIC", + "State cannot be blank": "El estado no puede estar en blanco", + "Worker cannot be blank": "El trabajador no puede estar en blanco", + "Cannot change the payment method if no salesperson": "No se puede cambiar la forma de pago si no hay comercial asignado", + "can't be blank": "El campo no puede estar vacío", + "Observation type must be unique": "El tipo de observación no puede repetirse", + "The credit must be an integer greater than or equal to zero": "The credit must be an integer greater than or equal to zero", + "The grade must be similar to the last one": "El grade debe ser similar al último", + "Only manager can change the credit": "Solo el gerente puede cambiar el credito de este cliente", + "Name cannot be blank": "El nombre no puede estar en blanco", + "Phone cannot be blank": "El teléfono no puede estar en blanco", + "Period cannot be blank": "El periodo no puede estar en blanco", + "Choose a company": "Selecciona una empresa", + "Se debe rellenar el campo de texto": "Se debe rellenar el campo de texto", + "Description should have maximum of 45 characters": "La descripción debe tener maximo 45 caracteres", + "Cannot be blank": "El campo no puede estar en blanco", + "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero", + "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco", + "Description cannot be blank": "Se debe rellenar el campo de texto", + "The price of the item changed": "El precio del artículo cambió", + "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%", + "The value should be a number": "El valor debe ser un numero", + "This order is not editable": "Esta orden no se puede modificar", + "You can't create an order for a frozen client": "No puedes crear una orden para un cliente congelado", + "You can't create an order for a client that has a debt": "No puedes crear una orden para un cliente con deuda", + "is not a valid date": "No es una fecha valida", + "Barcode must be unique": "El código de barras debe ser único", + "The warehouse can't be repeated": "El almacén no puede repetirse", + "The tag or priority can't be repeated for an item": "El tag o prioridad no puede repetirse para un item", + "The observation type can't be repeated": "El tipo de observación no puede repetirse", + "A claim with that sale already exists": "Ya existe una reclamación para esta línea", + "You don't have enough privileges to change that field": "No tienes permisos para cambiar ese campo", + "Warehouse cannot be blank": "El almacén no puede quedar en blanco", + "Agency cannot be blank": "La agencia no puede quedar en blanco", + "Not enough privileges to edit a client with verified data": "No tienes permisos para hacer cambios en un cliente con datos comprobados", + "This address doesn't exist": "Este consignatario no existe", + "You must delete the claim id %d first": "Antes debes borrar la reclamación %d", + "You don't have enough privileges": "No tienes suficientes permisos", + "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", + "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos básicos de una orden con artículos", + "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no está permitido el uso de la letra ñ", + "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", + "You can't create a ticket for an inactive client": "No puedes crear un ticket para un cliente inactivo", + "Tag value cannot be blank": "El valor del tag no puede quedar en blanco", + "ORDER_EMPTY": "Cesta vacía", + "You don't have enough privileges to do that": "No tienes permisos para cambiar esto", + "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT", + "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido", + "Street cannot be empty": "Dirección no puede estar en blanco", + "City cannot be empty": "Ciudad no puede estar en blanco", + "Code cannot be blank": "Código no puede estar en blanco", + "You cannot remove this department": "No puedes eliminar este departamento", + "The extension must be unique": "La extensión debe ser unica", + "The secret can't be blank": "La contraseña no puede estar en blanco", + "We weren't able to send this SMS": "No hemos podido enviar el SMS", + "This client can't be invoiced": "Este cliente no puede ser facturado", + "You must provide the correction information to generate a corrective invoice": "Debes informar la información de corrección para generar una factura rectificativa", + "This ticket can't be invoiced": "Este ticket no puede ser facturado", + "You cannot add or modify services to an invoiced ticket": "No puedes añadir o modificar servicios a un ticket facturado", + "This ticket can not be modified": "Este ticket no puede ser modificado", + "The introduced hour already exists": "Esta hora ya ha sido introducida", + "INFINITE_LOOP": "Existe una dependencia entre dos Jefes", + "The sales of the receiver ticket can't be modified": "Las lineas del ticket al que envias no pueden ser modificadas", + "NO_AGENCY_AVAILABLE": "No hay una zona de reparto disponible con estos parámetros", + "ERROR_PAST_SHIPMENT": "No puedes seleccionar una fecha de envío en pasado", + "The current ticket can't be modified": "El ticket actual no puede ser modificado", + "The current claim can't be modified": "La reclamación actual no puede ser modificada", + "The sales of this ticket can't be modified": "Las lineas de este ticket no pueden ser modificadas", + "The sales do not exists": "La(s) línea(s) seleccionada(s) no existe(n)", + "Please select at least one sale": "Por favor selecciona al menos una linea", + "All sales must belong to the same ticket": "Todas las lineas deben pertenecer al mismo ticket", + "NO_ZONE_FOR_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", + "This item doesn't exists": "El artículo no existe", + "NOT_ZONE_WITH_THIS_PARAMETERS": "Para este día no hay ninguna zona configurada", + "Extension format is invalid": "El formato de la extensión es inválido", + "Invalid parameters to create a new ticket": "Parámetros inválidos para crear un nuevo ticket", + "This item is not available": "Este artículo no está disponible", + "This postcode already exists": "Este código postal ya existe", + "Concept cannot be blank": "El concepto no puede quedar en blanco", + "File doesn't exists": "El archivo no existe", + "You don't have privileges to change the zone": "No tienes permisos para cambiar la zona o para esos parámetros hay más de una opción de envío, hable con las agencias", + "This ticket is already on weekly tickets": "Este ticket ya está en tickets programados", + "Ticket id cannot be blank": "El id de ticket no puede quedar en blanco", + "Weekday cannot be blank": "El día de la semana no puede quedar en blanco", + "You can't delete a confirmed order": "No puedes borrar un pedido confirmado", + "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto", + "Invalid quantity": "Cantidad invalida", + "This postal code is not valid": "Este código postal no es válido", + "is invalid": "es inválido", + "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto", + "The department name can't be repeated": "El nombre del departamento no puede repetirse", + "This phone already exists": "Este teléfono ya existe", + "You cannot move a parent to its own sons": "No puedes mover un elemento padre a uno de sus hijos", + "You can't create a claim for a removed ticket": "No puedes crear una reclamación para un ticket eliminado", + "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada", + "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero", + "You should specify a date": "Debes especificar una fecha", + "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fin", + "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fin", + "You should mark at least one week day": "Debes marcar al menos un día de la semana", + "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", + "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", + "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios", + "Deleted sales from ticket": "He eliminado las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{deletions}}}", + "Added sale to ticket": "He añadido la siguiente linea al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{addition}}}", + "Changed sale discount": "He cambiado el descuento de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Created claim": "He creado la reclamación [{{claimId}}]({{{claimUrl}}}) de las siguientes lineas del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Changed sale price": "He cambiado el precio de [{{itemId}} {{concept}}]({{{itemUrl}}}) ({{quantity}}) de {{oldPrice}}€ ➔ *{{newPrice}}€* del ticket [{{ticketId}}]({{{ticketUrl}}})", + "Changed sale quantity": "He cambiado la cantidad de [{{itemId}} {{concept}}]({{{itemUrl}}}) de {{oldQuantity}} ➔ *{{newQuantity}}* del ticket [{{ticketId}}]({{{ticketUrl}}})", + "State": "Estado", + "regular": "normal", + "reserved": "reservado", + "Changed sale reserved state": "He cambiado el estado reservado de las siguientes lineas al ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "Bought units from buy request": "Se ha comprado {{quantity}} unidades de [{{itemId}} {{concept}}]({{{urlItem}}}) para el ticket id [{{ticketId}}]({{{url}}})", + "Deny buy request": "Se ha rechazado la petición de compra para el ticket id [{{ticketId}}]({{{url}}}). Motivo: {{observation}}", + "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} ({{clientId}})]({{{url}}}) a *{{credit}} €*", + "Changed client paymethod": "He cambiado la forma de pago del cliente [{{clientName}} ({{clientId}})]({{{url}}})", + "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} ({{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})", + "Change quantity": "{{concept}} cambia de {{oldQuantity}} a {{newQuantity}}", + "Claim will be picked": "Se recogerá el género de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", + "Claim state has changed to": "Se ha cambiado el estado de la reclamación [({{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}* a *{{newState}}*", + "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", + "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", + "Distance must be lesser than 1000": "La distancia debe ser inferior a 1000", + "This ticket is deleted": "Este ticket está eliminado", + "Unable to clone this travel": "No ha sido posible clonar este travel", + "This thermograph id already exists": "La id del termógrafo ya existe", + "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante", + "ORDER_ALREADY_CONFIRMED": "ORDEN YA CONFIRMADA", + "Invalid password": "Invalid password", + "Password does not meet requirements": "La contraseña no cumple los requisitos", + "Role already assigned": "Rol ya asignado", + "Invalid role name": "Nombre de rol no válido", + "Role name must be written in camelCase": "El nombre del rol debe escribirse en camelCase", + "Email already exists": "El correo ya existe", + "User already exists": "El/La usuario/a ya existe", + "Absence change notification on the labour calendar": "Notificación de cambio de ausencia en el calendario laboral", + "Record of hours week": "Registro de horas semana {{week}} año {{year}} ", + "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.", + "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.", + "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})", + "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})", + "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación", + "Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): {{{changes}}}", + "agencyModeFk": "Agencia", + "clientFk": "Cliente", + "zoneFk": "Zona", + "warehouseFk": "Almacén", + "shipped": "F. envío", + "landed": "F. entrega", + "addressFk": "Consignatario", + "companyFk": "Empresa", + "The social name cannot be empty": "La razón social no puede quedar en blanco", + "The nif cannot be empty": "El NIF no puede quedar en blanco", + "You need to fill sage information before you check verified data": "Debes rellenar la información de sage antes de marcar datos comprobados", + "ASSIGN_ZONE_FIRST": "Asigna una zona primero", + "Amount cannot be zero": "El importe no puede ser cero", + "Company has to be official": "Empresa inválida", + "You can not select this payment method without a registered bankery account": "No se puede utilizar este método de pago si no has registrado una cuenta bancaria", + "Action not allowed on the test environment": "Esta acción no está permitida en el entorno de pruebas", + "The selected ticket is not suitable for this route": "El ticket seleccionado no es apto para esta ruta", + "New ticket request has been created with price": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}* y un precio de *{{price}} €*", + "New ticket request has been created": "Se ha creado una nueva petición de compra '{{description}}' para el día *{{shipped}}*, con una cantidad de *{{quantity}}*", + "Swift / BIC cannot be empty": "Swift / BIC no puede estar vacío", + "This BIC already exist.": "Este BIC ya existe.", + "That item doesn't exists": "Ese artículo no existe", + "There's a new urgent ticket:": "Hay un nuevo ticket urgente:", + "Invalid account": "Cuenta inválida", + "Compensation account is empty": "La cuenta para compensar está vacia", + "This genus already exist": "Este genus ya existe", + "This specie already exist": "Esta especie ya existe", + "Client assignment has changed": "He cambiado el comercial ~*\"<{{previousWorkerName}}>\"*~ por *\"<{{currentWorkerName}}>\"* del cliente [{{clientName}} ({{clientId}})]({{{url}}})", + "None": "Ninguno", + "The contract was not active during the selected date": "El contrato no estaba activo durante la fecha seleccionada", + "Cannot add more than one '1/2 day vacation'": "No puedes añadir más de un 'Vacaciones 1/2 dia'", + "This document already exists on this ticket": "Este documento ya existe en el ticket", + "Some of the selected tickets are not billable": "Algunos de los tickets seleccionados no son facturables", + "You can't invoice tickets from multiple clients": "No puedes facturar tickets de multiples clientes", + "nickname": "nickname", + "INACTIVE_PROVIDER": "Proveedor inactivo", + "This client is not invoiceable": "Este cliente no es facturable", + "serial non editable": "Esta serie no permite asignar la referencia", + "Max shipped required": "La fecha límite es requerida", + "Can't invoice to future": "No se puede facturar a futuro", + "Can't invoice to past": "No se puede facturar a pasado", + "This ticket is already invoiced": "Este ticket ya está facturado", + "A ticket with an amount of zero can't be invoiced": "No se puede facturar un ticket con importe cero", + "A ticket with a negative base can't be invoiced": "No se puede facturar un ticket con una base negativa", + "Global invoicing failed": "[Facturación global] No se han podido facturar algunos clientes", + "Wasn't able to invoice the following clients": "No se han podido facturar los siguientes clientes", + "Can't verify data unless the client has a business type": "No se puede verificar datos de un cliente que no tiene tipo de negocio", + "You don't have enough privileges to set this credit amount": "No tienes suficientes privilegios para establecer esta cantidad de crédito", + "You can't change the credit set to zero from a financialBoss": "No puedes cambiar el cŕedito establecido a cero por un jefe de finanzas", + "Amounts do not match": "Las cantidades no coinciden", + "The PDF document does not exist": "El documento PDF no existe. Prueba a regenerarlo desde la opción 'Regenerar PDF factura'", + "The type of business must be filled in basic data": "El tipo de negocio debe estar rellenado en datos básicos", + "You can't create a claim from a ticket delivered more than seven days ago": "No puedes crear una reclamación de un ticket entregado hace más de siete días", + "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", + "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día", + "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado", + "The account size must be exactly 10 characters": "El tamaño de la cuenta debe ser exactamente de 10 caracteres", + "Can't transfer claimed sales": "No puedes transferir lineas reclamadas", + "You don't have privileges to create refund": "No tienes permisos para crear un abono", + "The item is required": "El artículo es requerido", + "The agency is already assigned to another autonomous": "La agencia ya está asignada a otro autónomo", + "date in the future": "Fecha en el futuro", + "reference duplicated": "Referencia duplicada", + "This ticket is already a refund": "Este ticket ya es un abono", + "isWithoutNegatives": "Sin negativos", + "routeFk": "routeFk", + "Can't change the password of another worker": "No se puede cambiar la contraseña de otro trabajador", + "No hay un contrato en vigor": "No hay un contrato en vigor", + "No se permite fichar a futuro": "No se permite fichar a futuro", + "No está permitido trabajar": "No está permitido trabajar", + "Fichadas impares": "Fichadas impares", + "Descanso diario 12h.": "Descanso diario 12h.", + "Descanso semanal 36h. / 72h.": "Descanso semanal 36h. / 72h.", + "Dirección incorrecta": "Dirección incorrecta", + "Modifiable user details only by an administrator": "Detalles de usuario modificables solo por un administrador", + "Modifiable password only via recovery or by an administrator": "Contraseña modificable solo a través de la recuperación o por un administrador", + "Not enough privileges to edit a client": "No tienes suficientes privilegios para editar un cliente", + "This route does not exists": "Esta ruta no existe", + "Claim pickup order sent": "Reclamación Orden de recogida enviada [{{claimId}}]({{{claimUrl}}}) al cliente *{{clientName}}*", + "You don't have grant privilege": "No tienes privilegios para dar privilegios", + "You don't own the role and you can't assign it to another user": "No eres el propietario del rol y no puedes asignarlo a otro usuario", + "Ticket merged": "Ticket [{{originId}}]({{{originFullPath}}}) ({{{originDated}}}) fusionado con [{{destinationId}}]({{{destinationFullPath}}}) ({{{destinationDated}}})", + "Already has this status": "Ya tiene este estado", + "There aren't records for this week": "No existen registros para esta semana", + "Empty data source": "Origen de datos vacio", + "App locked": "Aplicación bloqueada por el usuario {{userId}}", + "Email verify": "Correo de verificación", + "Landing cannot be lesser than shipment": "Landing cannot be lesser than shipment", + "Receipt's bank was not found": "No se encontró el banco del recibo", + "This receipt was not compensated": "Este recibo no ha sido compensado", + "Client's email was not found": "No se encontró el email del cliente", + "Negative basis": "Base negativa", + "This worker code already exists": "Este codigo de trabajador ya existe", + "This personal mail already exists": "Este correo personal ya existe", + "This worker already exists": "Este trabajador ya existe", + "App name does not exist": "El nombre de aplicación no es válido", + "Try again": "Vuelve a intentarlo", + "Aplicación bloqueada por el usuario 9": "Aplicación bloqueada por el usuario 9", + "Failed to upload delivery note": "Error al subir albarán {{id}}", + "The DOCUWARE PDF document does not exists": "El documento PDF Docuware no existe", + "It is not possible to modify tracked sales": "No es posible modificar líneas de pedido que se hayan empezado a preparar", + "It is not possible to modify sales that their articles are from Floramondo": "No es posible modificar líneas de pedido cuyos artículos sean de Floramondo", + "It is not possible to modify cloned sales": "No es posible modificar líneas de pedido clonadas", + "A supplier with the same name already exists. Change the country.": "Un proveedor con el mismo nombre ya existe. Cambie el país.", + "There is no assigned email for this client": "No hay correo asignado para este cliente", + "Exists an invoice with a future date": "Existe una factura con fecha posterior", + "Invoice date can't be less than max date": "La fecha de factura no puede ser inferior a la fecha límite", + "Warehouse inventory not set": "El almacén inventario no está establecido", + "This locker has already been assigned": "Esta taquilla ya ha sido asignada", + "Tickets with associated refunds": "No se pueden borrar tickets con abonos asociados. Este ticket está asociado al abono Nº %d", + "Not exist this branch": "La rama no existe", + "This ticket cannot be signed because it has not been boxed": "Este ticket no puede firmarse porque no ha sido encajado", + "Collection does not exist": "La colección no existe", + "Cannot obtain exclusive lock": "No se puede obtener un bloqueo exclusivo", + "Insert a date range": "Inserte un rango de fechas", + "Added observation": "{{user}} añadió esta observacion: {{text}}", + "Comment added to client": "Observación añadida al cliente {{clientFk}}", + "Invalid auth code": "Código de verificación incorrecto", + "Invalid or expired verification code": "Código de verificación incorrecto o expirado", + "Cannot create a new claimBeginning from a different ticket": "No se puede crear una línea de reclamación de un ticket diferente al origen", + "company": "Compañía", + "country": "País", + "clientId": "Id cliente", + "clientSocialName": "Cliente", + "amount": "Importe", + "taxableBase": "Base", + "ticketFk": "Id ticket", + "isActive": "Activo", + "hasToInvoice": "Facturar", + "isTaxDataChecked": "Datos comprobados", + "comercialId": "Id comercial", + "comercialName": "Comercial", + "Pass expired": "La contraseña ha caducado, cambiela desde Salix", + "Invalid NIF for VIES": "Invalid NIF for VIES", + "Ticket does not exist": "Este ticket no existe", + "Ticket is already signed": "Este ticket ya ha sido firmado", + "Authentication failed": "Autenticación fallida", + "You can't use the same password": "No puedes usar la misma contraseña", + "You can only add negative amounts in refund tickets": "Solo se puede añadir cantidades negativas en tickets abono", + "Fecha fuera de rango": "Fecha fuera de rango", + "Error while generating PDF": "Error al generar PDF", + "Error when sending mail to client": "Error al enviar el correo al cliente", + "Mail not sent": "Se ha producido un fallo al enviar la factura al cliente [{{clientId}}]({{{clientUrl}}}), por favor revisa la dirección de correo electrónico", + "The renew period has not been exceeded": "El periodo de renovación no ha sido superado", + "Valid priorities": "Prioridades válidas: %d", + "hasAnyNegativeBase": "Base negativa para los tickets: {{ticketsIds}}", + "hasAnyPositiveBase": "Base positivas para los tickets: {{ticketsIds}}", + "You cannot assign an alias that you are not assigned to": "No puede asignar un alias que no tenga asignado", + "This ticket cannot be left empty.": "Este ticket no se puede dejar vacío. %s", + "The company has not informed the supplier account for bank transfers": "La empresa no tiene informado la cuenta de proveedor para transferencias bancarias", + "You cannot assign/remove an alias that you are not assigned to": "No puede asignar/eliminar un alias que no tenga asignado", + "This invoice has a linked vehicle.": "Esta factura tiene un vehiculo vinculado", + "You don't have enough privileges.": "No tienes suficientes permisos.", + "This ticket is locked": "Este ticket está bloqueado.", + "This ticket is not editable.": "Este ticket no es editable.", + "The ticket doesn't exist.": "No existe el ticket.", + "Social name should be uppercase": "La razón social debe ir en mayúscula", + "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", + "Ticket without Route": "Ticket sin ruta", + "Select a different client": "Seleccione un cliente distinto", + "Fill all the fields": "Rellene todos los campos", + "The response is not a PDF": "La respuesta no es un PDF", + "Booking completed": "Reserva completada", + "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", + "Incoterms data for consignee is missing": "Faltan los datos de los Incoterms para el consignatario", + "The notification subscription of this worker cant be modified": "La subscripción a la notificación de este trabajador no puede ser modificada", + "User disabled": "Usuario desactivado", + "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mínima", + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mínima", + "Cannot past travels with entries": "No se pueden pasar envíos con entradas", + "It was not able to remove the next expeditions:": "No se pudo eliminar las siguientes expediciones: {{expeditions}}", + "This claim has been updated": "La reclamación con Id: {{claimId}}, ha sido actualizada", + "This user does not have an assigned tablet": "Este usuario no tiene tablet asignada", + "Incorrect pin": "Pin incorrecto", + "You already have the mailAlias": "Ya tienes este alias de correo", + "The alias cant be modified": "Este alias de correo no puede ser modificado", "No tickets to invoice": "No hay tickets para facturar", - "This machine is already in use.": "Esta máquina ya está en uso.", - "the plate does not exist": "La máquina {{plate}} no existe", - "We do not have availability for the selected item": "No tenemos disponible el item seleccionado", - "You are already using a machine": "Ya estás usando una máquina.", - "this state does not exist": "Este estado no existe", - "The line could not be marked": "No se ha podido marcar la línea", - "The sale cannot be tracked": "La línea no puede ser rastreada", - "Shelving not valid": "Carro no válido", - "printerNotExists": "No existe la impresora", - "There are not picking tickets": "No hay tickets para sacar", - "ticketCommercial": "El ticket {{ticket}} del comercial {{salesMan}} está en preparación.(mensaje creado automáticamente)", - -} + "This ticket already has a cmr saved": "Este ticket ya tiene un cmr guardado", + "Name should be uppercase": "El nombre debe ir en mayúscula", + "Bank entity must be specified": "La entidad bancaria es obligatoria", + "An email is necessary": "Es necesario un email", + "You cannot update these fields": "No puedes actualizar estos campos", + "CountryFK cannot be empty": "El país no puede estar vacío", + "Cmr file does not exist": "El archivo del cmr no existe", + "We do not have availability for the selected item": "No tenemos disponible el artículo seleccionado" +} \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/addSaleByCode.js b/modules/ticket/back/methods/ticket/addSaleByCode.js index 5c63b465e..cb3bcccd3 100644 --- a/modules/ticket/back/methods/ticket/addSaleByCode.js +++ b/modules/ticket/back/methods/ticket/addSaleByCode.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('addSaleByCode', { description: 'Add a collection', @@ -15,6 +16,10 @@ module.exports = Self => { arg: 'ticketFk', type: 'number', required: true + }, { + arg: 'warehouseFk', + type: 'number', + required: true }, ], @@ -24,8 +29,7 @@ module.exports = Self => { }, }); - Self.addSaleByCode = async(ctx, code, quantity, ticketFk, options) => { - const models = Self.app.models; + Self.addSaleByCode = async(ctx, code, quantity, ticketFk, warehouseFk, options) => { const myOptions = {}; let tx; @@ -38,8 +42,10 @@ module.exports = Self => { } try { - const [{itemFk}] = await Self.rawSql('SELECT barcodeToItem(?) itemFk', [code], myOptions); - await models.Ticket.addSale(ctx, ticketFk, itemFk, quantity, myOptions); + const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [code, warehouseFk], myOptions); + if (!item?.available) throw new UserError('We do not have availability for the selected item'); + + await Self.rawSql('CALL vn.collection_addItem(?, ?, ?)', [item.id, quantity, ticketFk], myOptions); if (tx) await tx.commit(); } catch (e) { From 934278b0181c14f109a95afbb8aec71b4147c0c9 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 19 Feb 2024 08:45:43 +0100 Subject: [PATCH 091/150] refs #6053 maxCPUs 4 --- jest.front.config.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jest.front.config.js b/jest.front.config.js index 955f06eca..4cbfa2353 100644 --- a/jest.front.config.js +++ b/jest.front.config.js @@ -2,8 +2,10 @@ // https://jestjs.io/docs/en/configuration.html /* eslint max-len: ["error", { "code": 150 }]*/ const cpus = require('os').cpus().length; +console.log('cpus: ', cpus); +const maxCpus = Math.floor(cpus / 4); +console.log('maxCpus: ', maxCpus); -const maxCpus = Math.floor(cpus / 5) - 1; module.exports = { name: 'front end', displayName: { From d5a341330750b369173bcf72f23c8bcd70f8f43f Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 19 Feb 2024 14:46:42 +0100 Subject: [PATCH 092/150] fix: refs #6776 method names & chanmges --- .../{assignCollection.js => assign.js} | 6 +- ...sFromTicketOrCollection.js => getSales.js} | 13 ++--- ...ssignCollection.spec.js => assign.spec.js} | 4 +- ...tOrCollection.spec.js => getSales.spec.js} | 6 +- back/methods/machine-worker/updateInTime.js | 6 +- back/models/collection.js | 4 +- .../10832-purpleAralia/00-newWareHouse.sql | 7 +-- .../{return.js => getAlternative.js} | 6 +- ...{return.spec.js => getAlternative.spec.js} | 6 +- .../back/methods/item/{card.js => get.js} | 28 +++++---- .../item/specs/{card.spec.js => get.spec.js} | 6 +- modules/item/back/models/item-shelving.js | 2 +- modules/item/back/models/item.js | 2 +- .../back/methods/ticket/addSaleByCode.js | 11 ++-- modules/worker/back/methods/operator/add.js | 21 ------- .../back/methods/operator/spec/add.spec.js | 58 ------------------- modules/worker/back/models/operator.js | 2 - 17 files changed, 49 insertions(+), 139 deletions(-) rename back/methods/collection/{assignCollection.js => assign.js} (86%) rename back/methods/collection/{getSalesFromTicketOrCollection.js => getSales.js} (94%) rename back/methods/collection/spec/{assignCollection.spec.js => assign.spec.js} (88%) rename back/methods/collection/spec/{getSalesFromTicketOrCollection.spec.js => getSales.spec.js} (90%) rename modules/item/back/methods/item-shelving/{return.js => getAlternative.js} (92%) rename modules/item/back/methods/item-shelving/specs/{return.spec.js => getAlternative.spec.js} (70%) rename modules/item/back/methods/item/{card.js => get.js} (55%) rename modules/item/back/methods/item/specs/{card.spec.js => get.spec.js} (67%) delete mode 100644 modules/worker/back/methods/operator/add.js delete mode 100644 modules/worker/back/methods/operator/spec/add.spec.js diff --git a/back/methods/collection/assignCollection.js b/back/methods/collection/assign.js similarity index 86% rename from back/methods/collection/assignCollection.js rename to back/methods/collection/assign.js index 575649de8..8a2300e3e 100644 --- a/back/methods/collection/assignCollection.js +++ b/back/methods/collection/assign.js @@ -1,10 +1,10 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethodCtx('assignCollection', { + Self.remoteMethodCtx('assign', { description: 'Assign a collection', accessType: 'WRITE', http: { - path: `/assignCollection`, + path: `/assign`, verb: 'POST' }, returns: { @@ -13,7 +13,7 @@ module.exports = Self => { }, }); - Self.assignCollection = async(ctx, options) => { + Self.assign = async(ctx, options) => { const userId = ctx.req.accessToken.userId; const myOptions = {userId}; diff --git a/back/methods/collection/getSalesFromTicketOrCollection.js b/back/methods/collection/getSales.js similarity index 94% rename from back/methods/collection/getSalesFromTicketOrCollection.js rename to back/methods/collection/getSales.js index 3c27a0be6..e9a87bfa3 100644 --- a/back/methods/collection/getSalesFromTicketOrCollection.js +++ b/back/methods/collection/getSales.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('getSalesFromTicketOrCollection', { + Self.remoteMethodCtx('getSales', { description: 'Get sales from ticket or collection', accessType: 'READ', accepts: [ @@ -23,12 +23,12 @@ module.exports = Self => { root: true }, http: { - path: `/getSalesFromTicketOrCollection`, + path: `/getSales`, verb: 'GET' }, }); - Self.getSalesFromTicketOrCollection = async(ctx, collectionOrTicketFk, print, source, options) => { + Self.getSales = async(ctx, collectionOrTicketFk, print, source, options) => { const userId = ctx.req.accessToken.userId; const myOptions = {userId}; const $t = ctx.req.__; @@ -62,11 +62,11 @@ module.exports = Self => { let observations = ticket.observaciones.split(' '); for (let observation of observations) { - const salesMan = ticket.salesPersonFk; + const salesPerson = ticket.salesPersonFk; if (!observation.startsWith('#') && !observation.startsWith('@')) return; await models.Chat.send(ctx, observation, - $t('ticketCommercial', {ticket: ticket.ticketFk, salesMan}) + $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) ); } } @@ -92,9 +92,8 @@ module.exports = Self => { if (sale.ticketFk == ticketFk) { sale.placements = []; for (const salePlacement of placements) { - let placement; if (salePlacement.saleFk == sale.saleFk && salePlacement.order) { - placement = { + const placement = { saleFk: salePlacement.saleFk, itemFk: salePlacement.itemFk, placement: salePlacement.placement, diff --git a/back/methods/collection/spec/assignCollection.spec.js b/back/methods/collection/spec/assign.spec.js similarity index 88% rename from back/methods/collection/spec/assignCollection.spec.js rename to back/methods/collection/spec/assign.spec.js index e8f3882a3..745343819 100644 --- a/back/methods/collection/spec/assignCollection.spec.js +++ b/back/methods/collection/spec/assign.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -describe('ticket assignCollection()', () => { +describe('ticket assign()', () => { let ctx; let options; let tx; @@ -30,7 +30,7 @@ describe('ticket assignCollection()', () => { it('should throw an error when there is not picking tickets', async() => { try { - await models.Collection.assignCollection(ctx, options); + await models.Collection.assign(ctx, options); } catch (e) { expect(e.message).toEqual('There are not picking tickets'); } diff --git a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js b/back/methods/collection/spec/getSales.spec.js similarity index 90% rename from back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js rename to back/methods/collection/spec/getSales.spec.js index 50ba69401..e6205cc79 100644 --- a/back/methods/collection/spec/getSalesFromTicketOrCollection.spec.js +++ b/back/methods/collection/spec/getSales.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -describe('collection getSalesFromTicketOrCollection()', () => { +describe('collection getSales()', () => { const collectionOrTicketFk = 999999; const print = true; const source = 'CHECKER'; @@ -18,7 +18,7 @@ describe('collection getSalesFromTicketOrCollection()', () => { const tx = await models.Collection.beginTransaction({}); const options = {transaction: tx}; try { - const collection = await models.Collection.getSalesFromTicketOrCollection(ctx, + const collection = await models.Collection.getSales(ctx, collectionOrTicketFk, print, source, options); const [firstTicket] = collection.tickets; @@ -47,7 +47,7 @@ describe('collection getSalesFromTicketOrCollection()', () => { try { const printQueueBefore = await models.Collection.rawSql( query, [], options); - await models.Collection.getSalesFromTicketOrCollection(ctx, + await models.Collection.getSales(ctx, collectionOrTicketFk, true, source, options); const printQueueAfter = await models.Collection.rawSql( query, [], options); diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index 706f1a80e..cfeda4425 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -50,13 +50,13 @@ module.exports = Self => { if (machineWorker) { const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); const hoursDifference = (Date.vnNow() - machineWorker.inTime.getTime()) / (60 * 60 * 1000); - const isHimSelf = userId == machineWorker.workerFk; + const isHimself = userId == machineWorker.workerFk; const isSameMachine = machine.id == machineWorker.machineFk; - if (hoursDifference < maxHours && !isHimSelf) + if (hoursDifference < maxHours && !isHimself) throw new UserError($t('This machine is already in use.')); - if (hoursDifference < maxHours && isHimSelf && !isSameMachine) + if (hoursDifference < maxHours && isHimself && !isSameMachine) throw new UserError($t('You are already using a machine')); await machineWorker.updateAttributes({ diff --git a/back/models/collection.js b/back/models/collection.js index 7cc88c950..f2c2f1566 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -3,6 +3,6 @@ module.exports = Self => { require('../methods/collection/setSaleQuantity')(Self); require('../methods/collection/previousLabel')(Self); require('../methods/collection/getTickets')(Self); - require('../methods/collection/assignCollection')(Self); - require('../methods/collection/getSalesFromTicketOrCollection')(Self); + require('../methods/collection/assign')(Self); + require('../methods/collection/getSales')(Self); }; diff --git a/db/versions/10832-purpleAralia/00-newWareHouse.sql b/db/versions/10832-purpleAralia/00-newWareHouse.sql index 4802a6c4a..d2a86bf3e 100644 --- a/db/versions/10832-purpleAralia/00-newWareHouse.sql +++ b/db/versions/10832-purpleAralia/00-newWareHouse.sql @@ -1,6 +1,6 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES - ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'), + ('Collection', 'assign', 'WRITE', 'ALLOW', 'ROLE', 'production'), ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'production'), ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','production'), ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','production'), @@ -8,7 +8,4 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','production'), ('SaleTracking','mark','WRITE','ALLOW','ROLE','production'), ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'), - ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'), - ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'production'), - ('Ticket', 'addSaleByCode', 'WRITE', 'ALLOW', 'ROLE', 'production'); - \ No newline at end of file + ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file diff --git a/modules/item/back/methods/item-shelving/return.js b/modules/item/back/methods/item-shelving/getAlternative.js similarity index 92% rename from modules/item/back/methods/item-shelving/return.js rename to modules/item/back/methods/item-shelving/getAlternative.js index 81047461e..8c0f63a2f 100644 --- a/modules/item/back/methods/item-shelving/return.js +++ b/modules/item/back/methods/item-shelving/getAlternative.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethod('return', { + Self.remoteMethod('getAlternative', { description: 'Returns a list of items and possible alternative locations', accessType: 'READ', accepts: [{ @@ -12,12 +12,12 @@ module.exports = Self => { root: true }, http: { - path: `/return`, + path: `/getAlternative`, verb: 'GET' } }); - Self.return = async(shelvingFk, options) => { + Self.getAlternative = async(shelvingFk, options) => { const models = Self.app.models; const myOptions = {}; diff --git a/modules/item/back/methods/item-shelving/specs/return.spec.js b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js similarity index 70% rename from modules/item/back/methods/item-shelving/specs/return.spec.js rename to modules/item/back/methods/item-shelving/specs/getAlternative.spec.js index a5edc0ade..8c8d8a33d 100644 --- a/modules/item/back/methods/item-shelving/specs/return.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js @@ -1,6 +1,6 @@ const {models} = require('vn-loopback/server/server'); -describe('itemShelving return()', () => { +describe('itemShelving getAlternative()', () => { beforeAll(async() => { ctx = { req: { @@ -11,14 +11,14 @@ describe('itemShelving return()', () => { it('should return a list of items without alternatives', async() => { const shelvingFk = 'HEJ'; - const itemShelvings = await models.ItemShelving.return(shelvingFk); + const itemShelvings = await models.ItemShelving.getAlternative(shelvingFk); expect(itemShelvings[0].carros.length).toEqual(0); }); it('should return an empty list', async() => { const shelvingFk = 'ZZP'; - const itemShelvings = await models.ItemShelving.return(shelvingFk); + const itemShelvings = await models.ItemShelving.getAlternative(shelvingFk); expect(itemShelvings.length).toEqual(0); }); diff --git a/modules/item/back/methods/item/card.js b/modules/item/back/methods/item/get.js similarity index 55% rename from modules/item/back/methods/item/card.js rename to modules/item/back/methods/item/get.js index 8ee4ccc6b..38b37a90c 100644 --- a/modules/item/back/methods/item/card.js +++ b/modules/item/back/methods/item/get.js @@ -1,14 +1,14 @@ module.exports = Self => { - Self.remoteMethod('card', { + Self.remoteMethod('get', { description: 'Get the data from an item', accessType: 'READ', http: { - path: `/card`, + path: `/get`, verb: 'GET' }, accepts: [ { - arg: 'itemFk', + arg: 'barcode', type: 'number', required: true, }, @@ -24,7 +24,7 @@ module.exports = Self => { }, }); - Self.card = async(itemFk, warehouseFk, options) => { + Self.get = async(barcode, warehouseFk, options) => { const myOptions = {}; if (typeof options == 'object') @@ -32,19 +32,17 @@ module.exports = Self => { const models = Self.app.models; - const [[itemInfo]] = await Self.rawSql('CALL vn.item_getInfo(?, ?)', [itemFk, warehouseFk], myOptions); + const [[itemInfo]] = await Self.rawSql('CALL vn.item_getInfo(?, ?)', [barcode, warehouseFk], myOptions); - const barcodeItems = await Self.rawSql('SELECT vn.barcodeToItem(?) as realIdItem', [itemFk], myOptions); - const [realIdItem] = barcodeItems.map(barcodeItem => barcodeItem.realIdItem); + if (itemInfo) { + itemInfo.barcodes = await models.ItemBarcode.find({ + fields: ['code'], + where: { + itemFk: itemInfo.id + } + }); + } - const barcodes = await models.ItemBarcode.find({ - fields: ['code'], - where: { - itemFk: realIdItem - } - }); - - if (itemInfo) itemInfo.barcodes = barcodes; return itemInfo; }; }; diff --git a/modules/item/back/methods/item/specs/card.spec.js b/modules/item/back/methods/item/specs/get.spec.js similarity index 67% rename from modules/item/back/methods/item/specs/card.spec.js rename to modules/item/back/methods/item/specs/get.spec.js index 65004cfa5..55262004a 100644 --- a/modules/item/back/methods/item/specs/card.spec.js +++ b/modules/item/back/methods/item/specs/get.spec.js @@ -1,10 +1,10 @@ const {models} = require('vn-loopback/server/server'); -describe('item card()', () => { - const itemFk = 1; +describe('item get()', () => { + const barcode = 1; const warehouseFk = 1; it('should get an item with several barcodes', async() => { - const card = await models.Item.card(itemFk, warehouseFk); + const card = await models.Item.get(barcode, warehouseFk); expect(card).toBeDefined(); expect(card.barcodes.length).toBeTruthy(); diff --git a/modules/item/back/models/item-shelving.js b/modules/item/back/models/item-shelving.js index 6e63a29b2..e180a2d7c 100644 --- a/modules/item/back/models/item-shelving.js +++ b/modules/item/back/models/item-shelving.js @@ -1,6 +1,6 @@ module.exports = Self => { require('../methods/item-shelving/deleteItemShelvings')(Self); require('../methods/item-shelving/getInventory')(Self); - require('../methods/item-shelving/return')(Self); + require('../methods/item-shelving/getAlternative')(Self); require('../methods/item-shelving/updateFromSale')(Self); }; diff --git a/modules/item/back/models/item.js b/modules/item/back/models/item.js index 17c7a59f1..e715ab431 100644 --- a/modules/item/back/models/item.js +++ b/modules/item/back/models/item.js @@ -17,7 +17,7 @@ module.exports = Self => { require('../methods/item/buyerWasteEmail')(Self); require('../methods/item/labelPdf')(Self); require('../methods/item/setVisibleDiscard')(Self); - require('../methods/item/card')(Self); + require('../methods/item/get')(Self); Self.validatesPresenceOf('originFk', {message: 'Cannot be blank'}); diff --git a/modules/ticket/back/methods/ticket/addSaleByCode.js b/modules/ticket/back/methods/ticket/addSaleByCode.js index cb3bcccd3..c22cbc20e 100644 --- a/modules/ticket/back/methods/ticket/addSaleByCode.js +++ b/modules/ticket/back/methods/ticket/addSaleByCode.js @@ -1,11 +1,10 @@ -const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('addSaleByCode', { description: 'Add a collection', accessType: 'WRITE', accepts: [ { - arg: 'code', + arg: 'barcode', type: 'string', required: true }, { @@ -29,7 +28,7 @@ module.exports = Self => { }, }); - Self.addSaleByCode = async(ctx, code, quantity, ticketFk, warehouseFk, options) => { + Self.addSaleByCode = async(ctx, barcode, quantity, ticketFk, warehouseFk, options) => { const myOptions = {}; let tx; @@ -42,10 +41,8 @@ module.exports = Self => { } try { - const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [code, warehouseFk], myOptions); - if (!item?.available) throw new UserError('We do not have availability for the selected item'); - - await Self.rawSql('CALL vn.collection_addItem(?, ?, ?)', [item.id, quantity, ticketFk], myOptions); + const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [barcode, warehouseFk], myOptions); + await Self.addSale(ctx, ticketFk, item.id, quantity, myOptions); if (tx) await tx.commit(); } catch (e) { diff --git a/modules/worker/back/methods/operator/add.js b/modules/worker/back/methods/operator/add.js deleted file mode 100644 index efd610562..000000000 --- a/modules/worker/back/methods/operator/add.js +++ /dev/null @@ -1,21 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('add', { - description: 'Add a new operator', - accessType: 'WRITE', - http: { - path: `/add`, - verb: 'POST' - } - }); - - Self.add = async(ctx, options) => { - const userId = ctx.req.accessToken.userId; - const myOptions = {}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - const isOperator = await Self.findById(userId, myOptions); - if (!isOperator) await Self.create({workerFk: userId}, myOptions); - }; -}; diff --git a/modules/worker/back/methods/operator/spec/add.spec.js b/modules/worker/back/methods/operator/spec/add.spec.js deleted file mode 100644 index 94daae8de..000000000 --- a/modules/worker/back/methods/operator/spec/add.spec.js +++ /dev/null @@ -1,58 +0,0 @@ -const {models} = require('vn-loopback/server/server'); - -describe('operator add()', () => { - const noOperator = 104; - const operator = 9; - - beforeAll(async() => { - ctx = { - req: { - accessToken: {}, - headers: {origin: 'http://localhost'}, - __: value => value - } - }; - }); - - it('should not add an existent operator', async() => { - const tx = await models.Operator.beginTransaction({}); - const options = {transaction: tx}; - ctx.req.accessToken.userId = operator; - - try { - const operatorBefore = await models.Operator.find(null, options); - const isOperator = await models.Operator.findOne(null, options); - - expect(isOperator).toBeDefined(); - - await models.Operator.add(ctx, options); - const operatorAfter = await models.Operator.find(null, options); - - expect(operatorBefore.length).toEqual(operatorAfter.length); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - } - }); - - it('should add a new operator successfully', async() => { - const tx = await models.Operator.beginTransaction({}); - const options = {transaction: tx}; - ctx.req.accessToken.userId = noOperator; - - try { - const operatorBefore = await models.Operator.find(null, options); - await models.Operator.add(ctx, options); - const operatorAfter = await models.Operator.find(null, options); - - const isOperator = await models.Operator.findOne(null, options); - - expect(operatorBefore.length).toEqual(operatorAfter.length - 1); - expect(isOperator).toBeDefined(); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -}); diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index 442ac343f..cf6c198b6 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -1,6 +1,4 @@ module.exports = Self => { - require('../methods/operator/add')(Self); - Self.observe('after save', async function(ctx) { const instance = ctx.data || ctx.instance; const models = Self.app.models; From 072280cc9caf2b888475d8544fdbceda0568dac7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 20 Feb 2024 08:48:47 +0100 Subject: [PATCH 093/150] fix: refs #6776 method names --- .../methods/sale-tracking/{mark.js => setPicked.js} | 8 ++++---- .../specs/{mark.spec.js => setPicked.spec.js} | 10 +++++----- modules/ticket/back/models/sale-tracking.js | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) rename modules/ticket/back/methods/sale-tracking/{mark.js => setPicked.js} (90%) rename modules/ticket/back/methods/sale-tracking/specs/{mark.spec.js => setPicked.spec.js} (93%) diff --git a/modules/ticket/back/methods/sale-tracking/mark.js b/modules/ticket/back/methods/sale-tracking/setPicked.js similarity index 90% rename from modules/ticket/back/methods/sale-tracking/mark.js rename to modules/ticket/back/methods/sale-tracking/setPicked.js index 71fdfa048..990768197 100644 --- a/modules/ticket/back/methods/sale-tracking/mark.js +++ b/modules/ticket/back/methods/sale-tracking/setPicked.js @@ -1,8 +1,8 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethodCtx('mark', { - description: 'Insert an itemShelvingSale and Modify a saleTracking record', + Self.remoteMethodCtx('setPicked', { + description: 'Add the sales line of the item and set the tracking.', accessType: 'WRITE', accepts: [ { @@ -46,12 +46,12 @@ module.exports = Self => { } ], http: { - path: `/mark`, + path: `/setPicked`, verb: 'POST' } }); - Self.mark = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned, quantity, itemShelvingFk, options) => { + Self.setPicked = async(ctx, saleFk, originalQuantity, code, isChecked, buyFk, isScanned, quantity, itemShelvingFk, options) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; const myOptions = {}; diff --git a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js b/modules/ticket/back/methods/sale-tracking/specs/setPicked.spec.js similarity index 93% rename from modules/ticket/back/methods/sale-tracking/specs/mark.spec.js rename to modules/ticket/back/methods/sale-tracking/specs/setPicked.spec.js index 723f5fb78..0cf2ccbeb 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/mark.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/setPicked.spec.js @@ -1,5 +1,5 @@ const {models} = require('vn-loopback/server/server'); -describe('saleTracking mark()', () => { +describe('saleTracking setPicked()', () => { const saleFk = 1; const originalQuantity = 10; const code = 'PREPARED'; @@ -24,7 +24,7 @@ describe('saleTracking mark()', () => { const options = {transaction: tx}; const code = 'FAKESTATE'; try { - await models.SaleTracking.mark( + await models.SaleTracking.setPicked( ctx, saleFk, originalQuantity, @@ -50,7 +50,7 @@ describe('saleTracking mark()', () => { const tx = await models.SaleTracking.beginTransaction({}); const options = {transaction: tx}; try { - await models.SaleTracking.mark( + await models.SaleTracking.setPicked( ctx, saleFk, originalQuantity, @@ -63,7 +63,7 @@ describe('saleTracking mark()', () => { options ); - await models.SaleTracking.mark( + await models.SaleTracking.setPicked( ctx, saleFk, originalQuantity, @@ -89,7 +89,7 @@ describe('saleTracking mark()', () => { const options = {transaction: tx}; try { const itemShelvingSaleBefore = await models.ItemShelvingSale.find({}, options); - await models.SaleTracking.mark( + await models.SaleTracking.setPicked( ctx, saleFk, originalQuantity, diff --git a/modules/ticket/back/models/sale-tracking.js b/modules/ticket/back/models/sale-tracking.js index f284ec185..b5f8aeed5 100644 --- a/modules/ticket/back/models/sale-tracking.js +++ b/modules/ticket/back/models/sale-tracking.js @@ -4,5 +4,5 @@ module.exports = Self => { require('../methods/sale-tracking/new')(Self); require('../methods/sale-tracking/delete')(Self); require('../methods/sale-tracking/updateTracking')(Self); - require('../methods/sale-tracking/mark')(Self); + require('../methods/sale-tracking/setPicked')(Self); }; From 55b490160bed737cf58dc809dcfd3ff7e3a92107 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 20 Feb 2024 09:27:37 +0100 Subject: [PATCH 094/150] fix: refs #6776 back --- modules/ticket/back/methods/ticket/addSaleByCode.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/addSaleByCode.js b/modules/ticket/back/methods/ticket/addSaleByCode.js index c22cbc20e..a73628c86 100644 --- a/modules/ticket/back/methods/ticket/addSaleByCode.js +++ b/modules/ticket/back/methods/ticket/addSaleByCode.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('addSaleByCode', { description: 'Add a collection', @@ -42,7 +43,9 @@ module.exports = Self => { try { const [[item]] = await Self.rawSql('CALL vn.item_getInfo(?,?)', [barcode, warehouseFk], myOptions); - await Self.addSale(ctx, ticketFk, item.id, quantity, myOptions); + if (!item?.available) throw new UserError('We do not have availability for the selected item'); + + await Self.rawSql('CALL vn.collection_addItem(?, ?, ?)', [item.id, quantity, ticketFk], myOptions); if (tx) await tx.commit(); } catch (e) { From 9ce162da7144b8b064b4d1f0ab91f4b02e349082 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 20 Feb 2024 10:59:13 +0100 Subject: [PATCH 095/150] fix: refs #6776 back --- db/versions/10832-purpleAralia/00-newWareHouse.sql | 4 ++-- modules/ticket/back/methods/sale-tracking/delete.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/db/versions/10832-purpleAralia/00-newWareHouse.sql b/db/versions/10832-purpleAralia/00-newWareHouse.sql index d2a86bf3e..448c69322 100644 --- a/db/versions/10832-purpleAralia/00-newWareHouse.sql +++ b/db/versions/10832-purpleAralia/00-newWareHouse.sql @@ -4,8 +4,8 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('ExpeditionPallet', 'getPallet', 'READ', 'ALLOW', 'ROLE', 'production'), ('MachineWorker','updateInTime','WRITE','ALLOW','ROLE','production'), ('MobileAppVersionControl','getVersion','READ','ALLOW','ROLE','production'), - ('SaleTracking','deleteTracking','WRITE','ALLOW','ROLE','production'), + ('SaleTracking','delete','WRITE','ALLOW','ROLE','production'), ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','production'), - ('SaleTracking','mark','WRITE','ALLOW','ROLE','production'), + ('SaleTracking','setPicked','WRITE','ALLOW','ROLE','production'), ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'), ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file diff --git a/modules/ticket/back/methods/sale-tracking/delete.js b/modules/ticket/back/methods/sale-tracking/delete.js index 859f26354..fda21a014 100644 --- a/modules/ticket/back/methods/sale-tracking/delete.js +++ b/modules/ticket/back/methods/sale-tracking/delete.js @@ -2,7 +2,7 @@ module.exports = Self => { Self.remoteMethod('delete', { description: 'Delete sale trackings and item shelving sales', - accessType: 'READ', + accessType: 'WRITE', accepts: [ { arg: 'saleFk', From 131ae6b522ddd4288d7a3af49aa0b96eb750def0 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 23 Feb 2024 07:44:25 +0100 Subject: [PATCH 096/150] refs #6193 feat:modify inventory --- db/routines/vn/procedures/itemShelving_inventory.sql | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/itemShelving_inventory.sql b/db/routines/vn/procedures/itemShelving_inventory.sql index ce2934426..73e438fbb 100644 --- a/db/routines/vn/procedures/itemShelving_inventory.sql +++ b/db/routines/vn/procedures/itemShelving_inventory.sql @@ -30,10 +30,11 @@ BEGIN ish.visible, p.sectorFk, it.workerFk buyer, - CONCAT('http:',ic.url, '/catalog/1600x900/',i.image) urlImage, + ic.url, + i.image, ish.isChecked, CASE - WHEN s.notPrepared > sm.parked THEN 0 + WHEN IFNULL (s.notPrepared, 0) > sm.parked THEN 0 WHEN sm.visible > sm.parked THEN 1 ELSE 2 END priority @@ -43,7 +44,7 @@ BEGIN JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk JOIN shelving sh ON sh.code = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk - JOIN ( + LEFT JOIN ( SELECT s.itemFk, sum(s.quantity) notPrepared FROM sale s JOIN ticket t ON t.id = s.ticketFk From 7fdfd4fcb418d49a6e1b6b9ea570cc139c2756ef Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 23 Feb 2024 13:02:56 +0100 Subject: [PATCH 097/150] fix: refs #6276 desestructuring --- back/methods/collection/assign.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/collection/assign.js b/back/methods/collection/assign.js index 8a2300e3e..b0c1d9995 100644 --- a/back/methods/collection/assign.js +++ b/back/methods/collection/assign.js @@ -20,7 +20,7 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const [info, okPacket, {collectionFk}] = await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk); SELECT @vCollectionFk collectionFk', + const [,, {collectionFk}] = await Self.rawSql('CALL vn.collection_assign(?, @vCollectionFk); SELECT @vCollectionFk collectionFk', [userId], myOptions); if (!collectionFk) throw new UserError('There are not picking tickets'); From 8263b203a79f336441036af27fbf2e608d2cd0a4 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 26 Feb 2024 18:38:50 +0100 Subject: [PATCH 098/150] remove(claimRma): refs #6349 remove --- db/dump/.dump/data.sql | 2 -- db/dump/fixtures.before.sql | 8 ----- .../10913-bronzeGalax/00-firstScript.sql | 4 +++ modules/claim/back/model-config.json | 5 +--- modules/claim/back/models/claim-rma.js | 9 ------ modules/claim/back/models/claim-rma.json | 30 ------------------- modules/claim/back/models/claim.json | 9 ------ myt.config.yml | 1 - 8 files changed, 5 insertions(+), 63 deletions(-) create mode 100644 db/versions/10913-bronzeGalax/00-firstScript.sql delete mode 100644 modules/claim/back/models/claim-rma.js delete mode 100644 modules/claim/back/models/claim-rma.json diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index d7e99a4ee..979f7d738 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -1356,8 +1356,6 @@ INSERT INTO `ACL` VALUES (385,'Route','driverRoutePdf','READ','ALLOW','ROLE','em INSERT INTO `ACL` VALUES (386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'); INSERT INTO `ACL` VALUES (388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'); -INSERT INTO `ACL` VALUES (389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'); -INSERT INTO `ACL` VALUES (390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'); INSERT INTO `ACL` VALUES (391,'Notification','*','WRITE','ALLOW','ROLE','system'); INSERT INTO `ACL` VALUES (392,'Boxing','*','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (393,'Url','*','READ','ALLOW','ROLE','employee'); diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 7ba85d8d5..14380c897 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1880,14 +1880,6 @@ INSERT INTO `vn`.`claimRatio`(`clientFk`, `yearSale`, `claimAmount`, `claimingRa (1103, 2000, 0.00, 0.00, 0.02, 1.00), (1104, 2500, 150.00, 0.02, 0.10, 1.00); -INSERT INTO vn.claimRma (`id`, `code`, `created`, `workerFk`) - VALUES - (1, '02676A049183', DEFAULT, 1106), - (2, '02676A049183', DEFAULT, 1106), - (3, '02676A049183', DEFAULT, 1107), - (4, '02676A049183', DEFAULT, 1107), - (5, '01837B023653', DEFAULT, 1106); - INSERT INTO `vn`.`claimLog` (`originFk`, userFk, `action`, changedModel, oldInstance, newInstance, changedModelId, `description`) VALUES (1, 18, 'update', 'Claim', '{"hasToPickUp":false}', '{"hasToPickUp":true}', 1, NULL), diff --git a/db/versions/10913-bronzeGalax/00-firstScript.sql b/db/versions/10913-bronzeGalax/00-firstScript.sql new file mode 100644 index 000000000..aef0c8738 --- /dev/null +++ b/db/versions/10913-bronzeGalax/00-firstScript.sql @@ -0,0 +1,4 @@ +-- Place your SQL code here +RENAME TABLE IF EXISTS vn.claimRma TO vn.claimRma__; +ALTER TABLE IF EXISTS vn.claimRma__ COMMENT='kkeada el 2024-02-26 por Pablo'; +ALTER TABLE vn.claim CHANGE IF EXISTS rma rma__ varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL; diff --git a/modules/claim/back/model-config.json b/modules/claim/back/model-config.json index 83d88039c..d90ed4c1e 100644 --- a/modules/claim/back/model-config.json +++ b/modules/claim/back/model-config.json @@ -43,8 +43,5 @@ }, "ClaimObservation": { "dataSource": "vn" - }, - "ClaimRma": { - "dataSource": "vn" - } + } } diff --git a/modules/claim/back/models/claim-rma.js b/modules/claim/back/models/claim-rma.js deleted file mode 100644 index 6a93613bd..000000000 --- a/modules/claim/back/models/claim-rma.js +++ /dev/null @@ -1,9 +0,0 @@ -const LoopBackContext = require('loopback-context'); - -module.exports = Self => { - Self.observe('before save', async function(ctx) { - const changes = ctx.data || ctx.instance; - const loopBackContext = LoopBackContext.getCurrentContext(); - changes.workerFk = loopBackContext.active.accessToken.userId; - }); -}; diff --git a/modules/claim/back/models/claim-rma.json b/modules/claim/back/models/claim-rma.json deleted file mode 100644 index 27c3c9729..000000000 --- a/modules/claim/back/models/claim-rma.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "ClaimRma", - "base": "VnModel", - "options": { - "mysql": { - "table": "claimRma" - } - }, - "properties": { - "id": { - "id": true, - "type": "number", - "description": "Identifier" - }, - "code": { - "type": "string", - "required": true - }, - "created": { - "type": "date" - } - }, - "relations": { - "worker": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "workerFk" - } - } -} diff --git a/modules/claim/back/models/claim.json b/modules/claim/back/models/claim.json index b85b9e073..1fbbb00b1 100644 --- a/modules/claim/back/models/claim.json +++ b/modules/claim/back/models/claim.json @@ -45,9 +45,6 @@ }, "packages": { "type": "number" - }, - "rma": { - "type": "string" } }, "relations": { @@ -56,12 +53,6 @@ "model": "ClaimState", "foreignKey": "claimStateFk" }, - "rmas": { - "type": "hasMany", - "model": "ClaimRma", - "foreignKey": "code", - "primaryKey": "rma" - }, "client": { "type": "belongsTo", "model": "Client", diff --git a/myt.config.yml b/myt.config.yml index 0b1d62d25..d7d1ad181 100755 --- a/myt.config.yml +++ b/myt.config.yml @@ -179,7 +179,6 @@ localFixtures: - claimLog - claimObservation - claimRatio - - claimRma - claimState - client - clientConfig From afaa5fee7d64fc28bb43cdc2830ac3d48364d5d5 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 26 Feb 2024 19:00:45 +0100 Subject: [PATCH 099/150] fix(spec): refs #6349 fix fixtures --- db/dump/fixtures.before.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 14380c897..effb83819 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1826,12 +1826,12 @@ INSERT INTO `vn`.`claimState`(`id`, `code`, `description`, `roleFk`, `priority`, ( 6, 'mana', 'Mana', 72, 4, 0), ( 7, 'lack', 'Faltas', 72, 2, 0); -INSERT INTO `vn`.`claim`(`id`, `ticketCreated`, `claimStateFk`, `clientFk`, `workerFk`, `responsibility`, `isChargedToMana`, `created`, `packages`, `rma`, `ticketFk`) +INSERT INTO `vn`.`claim`(`id`, `ticketCreated`, `claimStateFk`, `clientFk`, `workerFk`, `responsibility`, `isChargedToMana`, `created`, `packages`, `ticketFk`) VALUES - (1, util.VN_CURDATE(), 1, 1101, 18, 3, 0, util.VN_CURDATE(), 0, '02676A049183', 11), - (2, util.VN_CURDATE(), 2, 1101, 18, 3, 0, util.VN_CURDATE(), 1, NULL, 16), - (3, util.VN_CURDATE(), 3, 1101, 18, 1, 1, util.VN_CURDATE(), 5, NULL, 7), - (4, util.VN_CURDATE(), 3, 1104, 18, 5, 0, util.VN_CURDATE(), 10, NULL, 8); + (1, util.VN_CURDATE(), 1, 1101, 18, 3, 0, util.VN_CURDATE(), 0, 11), + (2, util.VN_CURDATE(), 2, 1101, 18, 3, 0, util.VN_CURDATE(), 1, 16), + (3, util.VN_CURDATE(), 3, 1101, 18, 1, 1, util.VN_CURDATE(), 5, 7), + (4, util.VN_CURDATE(), 3, 1104, 18, 5, 0, util.VN_CURDATE(), 10, 8); INSERT INTO `vn`.`claimObservation` (`claimFk`, `workerFk`, `text`, `created`) VALUES From 1fe665357ffdd3aef8a5f8a41ebdd861ddcea644 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 27 Feb 2024 10:05:46 +0100 Subject: [PATCH 100/150] refs #6053 fix cpus --- jest.front.config.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/jest.front.config.js b/jest.front.config.js index b631a234a..4b292801e 100644 --- a/jest.front.config.js +++ b/jest.front.config.js @@ -2,9 +2,7 @@ // https://jestjs.io/docs/en/configuration.html /* eslint max-len: ["error", { "code": 150 }]*/ const cpus = require('os').cpus().length; -console.log('cpus: ', cpus); -const maxCpus = Math.floor(cpus / 4); -console.log('maxCpus: ', maxCpus); +const maxCpus = Math.floor(cpus * 0.45); module.exports = { name: 'front end', From b86110c898353e7c1dd0d2e16add048b7af4e850 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 27 Feb 2024 10:29:49 +0100 Subject: [PATCH 101/150] fix: refs #6276 changes --- back/methods/collection/getSales.js | 2 +- modules/item/back/methods/item-shelving/getAlternative.js | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index e9a87bfa3..c9f277890 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -46,7 +46,7 @@ module.exports = Self => { const [sales] = await Self.rawSql('CALL vn.sale_getFromTicketOrCollection(?)', [id], myOptions); - const isPicker = source == 'CHECKER'; + const isPicker = source != 'CHECKER'; const [placements] = await Self.rawSql('CALL vn.collectionPlacement_get(?, ?)', [id, isPicker], myOptions ); diff --git a/modules/item/back/methods/item-shelving/getAlternative.js b/modules/item/back/methods/item-shelving/getAlternative.js index 8c0f63a2f..dd497d580 100644 --- a/modules/item/back/methods/item-shelving/getAlternative.js +++ b/modules/item/back/methods/item-shelving/getAlternative.js @@ -52,7 +52,9 @@ module.exports = Self => { return { id: itemShelving.id, itemFk: itemShelving.itemFk, - longName: item ? item.longName || `${item.name} ${item.size}` : '', + name: item.name, + size: item.size, + longName: item.longName, quantity: itemShelving.visible, carros }; From 2fe0d5f5ddb640366eb66663213aedc128e20a23 Mon Sep 17 00:00:00 2001 From: robert Date: Tue, 27 Feb 2024 13:02:15 +0100 Subject: [PATCH 102/150] fix: refs #6371 restore tables dock y Tramos --- db/versions/10914-aquaBirch/00-firstScript.sql | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 db/versions/10914-aquaBirch/00-firstScript.sql diff --git a/db/versions/10914-aquaBirch/00-firstScript.sql b/db/versions/10914-aquaBirch/00-firstScript.sql new file mode 100644 index 000000000..a182d5407 --- /dev/null +++ b/db/versions/10914-aquaBirch/00-firstScript.sql @@ -0,0 +1,6 @@ +-- Place your SQL code here +ALTER TABLE IF EXISTS vn2008.dock__ RENAME vn2008.dock; +ALTER TABLE IF EXISTS vn2008.dock COMMENT=''; + +ALTER TABLE IF EXISTS vn2008.Tramos__ RENAME vn2008.Tramos; +ALTER TABLE IF EXISTS vn2008.Tramos COMMENT=''; \ No newline at end of file From fefc193ec0f4e3207574aa2f5a00c03772a48472 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 27 Feb 2024 13:59:21 +0100 Subject: [PATCH 103/150] refactor: refs #6496 Deleted clean vn2008 --- db/routines/cache/procedures/clean.sql | 2 +- db/routines/vn/procedures/clean.sql | 233 ++++++++++-------- db/routines/vn2008/procedures/clean.sql | 79 ------ .../vn2008/procedures/clean_launcher.sql | 6 - .../10915-limeMastic/00-firstScript.sql | 2 + 5 files changed, 131 insertions(+), 191 deletions(-) delete mode 100644 db/routines/vn2008/procedures/clean.sql delete mode 100644 db/routines/vn2008/procedures/clean_launcher.sql create mode 100644 db/versions/10915-limeMastic/00-firstScript.sql diff --git a/db/routines/cache/procedures/clean.sql b/db/routines/cache/procedures/clean.sql index 95841a713..ee64d052e 100644 --- a/db/routines/cache/procedures/clean.sql +++ b/db/routines/cache/procedures/clean.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `cache`.`clean`() BEGIN DECLARE vDateShort DATETIME; - SET vDateShort = TIMESTAMPADD(MONTH, -1, util.VN_CURDATE()); + SET vDateShort = util.VN_CURDATE() - INTERVAL 1 MONTH; DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; END$$ diff --git a/db/routines/vn/procedures/clean.sql b/db/routines/vn/procedures/clean.sql index 06f36afce..c1cafc0fe 100644 --- a/db/routines/vn/procedures/clean.sql +++ b/db/routines/vn/procedures/clean.sql @@ -1,48 +1,42 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`clean`() BEGIN - DECLARE vDateShort DATETIME; - DECLARE vOneYearAgo DATE; - DECLARE vFourYearsAgo DATE; - DECLARE vFiveYearsAgo DATE; - DECLARE v18Month DATE; - DECLARE v26Month DATE; - DECLARE v3Month DATE; +/** + * Purges outdated data to optimize performance. + * Exercise caution when executing. + */ + DECLARE v2Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 MONTH; + DECLARE v3Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 3 MONTH; + DECLARE v18Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 18 MONTH; + DECLARE v26Months DATE DEFAULT util.VN_CURDATE() - INTERVAL 26 MONTH; + DECLARE v1Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 1 YEAR; + DECLARE v2Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 2 YEAR; + DECLARE v4Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 4 YEAR; + DECLARE v5Years DATE DEFAULT util.VN_CURDATE() - INTERVAL 5 YEAR; DECLARE vTrashId VARCHAR(15); - DECLARE v2Years DATE; - DECLARE v5Years DATE; - - SET vDateShort = util.VN_CURDATE() - INTERVAL 2 MONTH; - SET vOneYearAgo = util.VN_CURDATE() - INTERVAL 1 YEAR; - SET vFourYearsAgo = util.VN_CURDATE() - INTERVAL 4 YEAR; - SET vFiveYearsAgo = util.VN_CURDATE() - INTERVAL 5 YEAR; - SET v18Month = util.VN_CURDATE() - INTERVAL 18 MONTH; - SET v26Month = util.VN_CURDATE() - INTERVAL 26 MONTH; - SET v3Month = util.VN_CURDATE() - INTERVAL 3 MONTH; - SET v2Years = util.VN_CURDATE() - INTERVAL 2 YEAR; - SET v5Years = util.VN_CURDATE() - INTERVAL 5 YEAR; + DECLARE vCompanyBlk INT; DELETE FROM workerActivity WHERE created < v2Years; - DELETE FROM ticketParking WHERE created < vDateShort; - DELETE FROM routesMonitor WHERE dated < vDateShort; - DELETE FROM workerTimeControlLog WHERE created < vDateShort; - DELETE FROM `message` WHERE sendDate < vDateShort; - DELETE FROM messageInbox WHERE sendDate < vDateShort; - DELETE FROM messageInbox WHERE sendDate < vDateShort; - DELETE FROM workerTimeControl WHERE timed < vFourYearsAgo; + DELETE FROM ticketParking WHERE created < v2Months; + DELETE FROM routesMonitor WHERE dated < v2Months; + DELETE FROM workerTimeControlLog WHERE created < v2Months; + DELETE FROM `message` WHERE sendDate < v2Months; + DELETE FROM messageInbox WHERE sendDate < v2Months; + DELETE FROM messageInbox WHERE sendDate < v2Months; + DELETE FROM workerTimeControl WHERE timed < v4Years; DELETE FROM itemShelving WHERE created < util.VN_CURDATE() AND visible = 0; - DELETE FROM ticketDown WHERE created < TIMESTAMPADD(DAY,-1,util.VN_CURDATE()); - DELETE FROM entryLog WHERE creationDate < vDateShort; - DELETE IGNORE FROM expedition WHERE created < v26Month; - DELETE FROM sms WHERE created < v18Month; - DELETE FROM saleTracking WHERE created < vOneYearAgo; - DELETE FROM ticketTracking WHERE created < v18Month; + DELETE FROM ticketDown WHERE created < util.yesterday(); + DELETE FROM entryLog WHERE creationDate < v2Months; + DELETE IGNORE FROM expedition WHERE created < v26Months; + DELETE FROM sms WHERE created < v18Months; + DELETE FROM saleTracking WHERE created < v1Years; + DELETE FROM ticketTracking WHERE created < v18Months; DELETE tobs FROM ticketObservation tobs JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < v5Years; - DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo; - DELETE FROM sharingCart where ended < vDateShort; - DELETE FROM sharingClient where ended < vDateShort; + DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < v1Years; + DELETE FROM sharingCart where ended < v2Months; + DELETE FROM sharingClient where ended < v2Months; DELETE tw.* FROM ticketWeekly tw LEFT JOIN sale s ON s.ticketFk = tw.ticketFk LEFT JOIN ticketRequest tr ON tr.ticketFk = tw.ticketFk @@ -50,73 +44,73 @@ BEGIN WHERE s.id IS NULL AND tr.id IS NULL AND ts.id IS NULL; - DELETE FROM claim WHERE ticketCreated < vFourYearsAgo; - DELETE FROM message WHERE sendDate < vDateShort; - -- Robert ubicacion anterior de trevelLog comentario para debug - DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Month; + DELETE FROM claim WHERE ticketCreated < v4Years; + -- Robert ubicacion anterior de travelLog comentario para debug + DELETE FROM zoneEvent WHERE `type` = 'day' AND dated < v3Months; DELETE bm FROM buyMark bm JOIN buy b ON b.id = bm.id JOIN entry e ON e.id = b.entryFk JOIN travel t ON t.id = e.travelFk - WHERE t.landed <= vDateShort; - DELETE b FROM vn.buy b - JOIN vn.entryConfig e ON e.defaultEntry = b.entryFk - WHERE b.created < vDateShort; - DELETE FROM vn.itemShelvingLog WHERE created < vDateShort; - DELETE FROM vn.stockBuyed WHERE creationDate < vDateShort; - DELETE FROM vn.itemCleanLog WHERE created < util.VN_NOW() - INTERVAL 1 YEAR; - DELETE FROM printQueue WHERE statusCode = 'printed' AND created < vDateShort; - DELETE FROM ticketLog WHERE creationDate <= vFiveYearsAgo; + WHERE t.landed <= v2Months; + DELETE b FROM buy b + JOIN entryConfig e ON e.defaultEntry = b.entryFk + WHERE b.created < v2Months; + DELETE FROM itemShelvingLog WHERE created < v2Months; + DELETE FROM stockBuyed WHERE creationDate < v2Months; + DELETE FROM itemCleanLog WHERE created < util.VN_NOW() - INTERVAL 1 YEAR; + DELETE FROM printQueue WHERE statusCode = 'printed' AND created < v2Months; + DELETE FROM ticketLog WHERE creationDate <= v5Years; -- Equipos duplicados DELETE w.* FROM workerTeam w - JOIN (SELECT id, team, workerFk, COUNT(*) - 1 as duplicated + JOIN ( + SELECT id, team, workerFk, COUNT(*) - 1 duplicated FROM workerTeam GROUP BY team,workerFk HAVING duplicated - ) d ON d.team = w.team AND d.workerFk = w.workerFk AND d.id != w.id; + ) d ON d.team = w.team + AND d.workerFk = w.workerFk + AND d.id <> w.id; DELETE sc FROM saleComponent sc JOIN sale s ON s.id= sc.saleFk JOIN ticket t ON t.id= s.ticketFk - WHERE t.shipped < v18Month; + WHERE t.shipped < v18Months; DELETE c - FROM vn.claim c - JOIN vn.claimState cs ON cs.id = c.claimStateFk - WHERE cs.description = "Anulado" AND - c.created < vDateShort; - DELETE - FROM vn.expeditionTruck - WHERE eta < v3Month; + FROM claim c + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cs.description = "Anulado" + AND c.created < v2Months; - DELETE FROM XDiario WHERE FECHA < v3Month OR FECHA IS NULL; - -- borrar travels sin entradas - DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete; - CREATE TEMPORARY TABLE tmp.thermographToDelete + DELETE FROM expeditionTruck WHERE eta < v3Months; + DELETE FROM XDiario WHERE FECHA < v3Months OR FECHA IS NULL; + + -- Borrar travels sin entradas + CREATE OR REPLACE TEMPORARY TABLE tThermographToDelete SELECT th.id,th.dmsFk - FROM vn.travel t - LEFT JOIN vn.entry e ON e.travelFk = t.id - JOIN vn.travelThermograph th ON th.travelFk = t.id + FROM travel t + LEFT JOIN entry e ON e.travelFk = t.id + JOIN travelThermograph th ON th.travelFk = t.id WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL; SELECT dt.id INTO vTrashId - FROM vn.dmsType dt + FROM dmsType dt WHERE dt.code = 'trash'; - UPDATE tmp.thermographToDelete th - JOIN vn.dms d ON d.id = th.dmsFk + UPDATE tThermographToDelete th + JOIN dms d ON d.id = th.dmsFk SET d.dmsTypeFk = vTrashId; DELETE th - FROM tmp.thermographToDelete tmp - JOIN vn.travelThermograph th ON th.id = tmp.id; + FROM tThermographToDelete tmp + JOIN travelThermograph th ON th.id = tmp.id; DELETE t - FROM vn.travel t - LEFT JOIN vn.entry e ON e.travelFk = t.id + FROM travel t + LEFT JOIN entry e ON e.travelFk = t.id WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL; UPDATE dms d @@ -125,69 +119,98 @@ BEGIN WHERE created < TIMESTAMPADD(MONTH, -dt.monthToDelete, util.VN_CURDATE()); -- borrar entradas sin compras - DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; - CREATE TEMPORARY TABLE tmp.entryToDelete + CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete SELECT e.* - FROM vn.entry e - LEFT JOIN vn.buy b ON b.entryFk = e.id - JOIN vn.entryConfig ec ON e.id != ec.defaultEntry + FROM entry e + LEFT JOIN buy b ON b.entryFk = e.id + JOIN entryConfig ec ON e.id <> ec.defaultEntry WHERE e.dated < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND b.entryFK IS NULL; DELETE e - FROM vn.entry e - JOIN tmp.entryToDelete tmp ON tmp.id = e.id; + FROM entry e + JOIN tEntryToDelete tmp ON tmp.id = e.id; -- borrar de route registros menores a 4 años - DROP TEMPORARY TABLE IF EXISTS tmp.routeToDelete; - CREATE TEMPORARY TABLE tmp.routeToDelete + CREATE OR REPLACE TEMPORARY TABLE tRouteToDelete SELECT * - FROM vn.route r + FROM route r WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); - UPDATE tmp.routeToDelete tmp - JOIN vn.dms d ON d.id = tmp.gestdocFk + UPDATE tRouteToDelete tmp + JOIN dms d ON d.id = tmp.gestdocFk SET d.dmsTypeFk = vTrashId; DELETE r - FROM tmp.routeToDelete tmp - JOIN vn.route r ON r.id = tmp.id; + FROM tRouteToDelete tmp + JOIN route r ON r.id = tmp.id; -- borrar registros de dua y awb menores a 2 años - DROP TEMPORARY TABLE IF EXISTS tmp.duaToDelete; - CREATE TEMPORARY TABLE tmp.duaToDelete + CREATE OR REPLACE TEMPORARY TABLE tDuaToDelete SELECT * - FROM vn.dua + FROM dua WHERE operated < TIMESTAMPADD(YEAR,-2,CURDATE()); - UPDATE tmp.duaToDelete tm - JOIN vn.dms d ON d.id = tm.gestdocFk + UPDATE tDuaToDelete tm + JOIN dms d ON d.id = tm.gestdocFk SET d.dmsTypeFk = vTrashId; DELETE d - FROM tmp.duaToDelete tmp - JOIN vn.dua d ON d.id = tmp.id; + FROM tDuaToDelete tmp + JOIN dua d ON d.id = tmp.id; DELETE a - FROM vn.awb a - LEFT JOIN vn.travel t ON t.awbFk = a.id + FROM awb a + LEFT JOIN travel t ON t.awbFk = a.id WHERE a.created < v2Years AND t.id IS NULL; -- Borra los registros de collection y ticketcollection - DELETE FROM vn.collection WHERE created < vDateShort; + DELETE FROM collection WHERE created < v2Months; + DELETE FROM travelLog WHERE creationDate < v3Months; - DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete; - DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; - DROP TEMPORARY TABLE IF EXISTS tmp.duaToDelete; - - DELETE FROM travelLog WHERE creationDate < v3Month; - - CALL shelving_clean; + CALL shelving_clean(); DELETE FROM chat WHERE dated < v5Years; + DELETE tt FROM ticketTracking tt + JOIN ticket t ON tt.ticketFk = t.id + WHERE t.shipped <= v2Months; - DELETE tt FROM ticketTracking tt JOIN vn.ticket t ON tt.ticketFk = t.id - WHERE t.shipped <= vDateShort; + -- Clean vn2008 + DELETE FROM mail WHERE creationDate < v2Months; + DELETE FROM split WHERE dated < v18Months; + DELETE FROM remittance WHERE dated < v18Months; + + CREATE OR REPLACE TEMPORARY TABLE tTicketDelete + SELECT DISTINCT tl.originFk ticketFk + FROM ticketLog tl + JOIN ( + SELECT MAX(tl.id)ids + FROM ticket t + JOIN ticketLog tl ON tl.originFk = t.id + WHERE t.shipped BETWEEN '2000-01-01' AND '2000-12-31' + AND t.isDeleted + GROUP BY t.id + ) sub ON sub.ids = tl.id + WHERE tl.creationDate <= util.VN_CURDATE() - INTERVAL 60 DAY; + DELETE t + FROM ticket t + JOIN tTicketDelete tmp ON tmp.ticketFk = t.id; + -- Tickets Nulos PAK 11/10/2016 + SELECT id INTO vCompanyBlk FROM company WHERE code = 'BLK'; + UPDATE ticket + SET companyFk = vCompanyBlk + WHERE clientFk = (SELECT id FROM client WHERE name = 'AUTOCONSUMO') + AND companyFk <> vCompanyBlk; + + DROP TEMPORARY TABLE tTicketDelete, + tThermographToDelete, + tEntryToDelete, + tDuaToDelete, + tRouteToDelete; + + -- Other schemas + DELETE FROM hedera.`order` WHERE date_send < v18Months; + DELETE FROM pbx.cdr WHERE call_date < v18Months; END$$ DELIMITER ; diff --git a/db/routines/vn2008/procedures/clean.sql b/db/routines/vn2008/procedures/clean.sql deleted file mode 100644 index 946157fa0..000000000 --- a/db/routines/vn2008/procedures/clean.sql +++ /dev/null @@ -1,79 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`clean`(IN `v_full` TINYINT(1)) -proc: BEGIN - DECLARE vDate DATETIME; - DECLARE vDate18 DATETIME; - DECLARE vDate26 DATETIME; - DECLARE vDate8 DATE; - DECLARE vDate6 DATE; - DECLARE vDate3 DATE; - DECLARE vDate2000 DATE; - DECLARE vRangeDeleteTicket INT; - DECLARE vStrtable VARCHAR(15) DEFAULT NULL; - - SET vDate = util.VN_CURDATE() - INTERVAL 2 MONTH; - SET vDate18 = util.VN_CURDATE() - INTERVAL 18 MONTH; - SET vDate26 = util.VN_CURDATE() - INTERVAL 26 MONTH; - SET vDate3 = util.VN_CURDATE() - INTERVAL 3 MONTH; - SET vDate8 = util.VN_CURDATE() - INTERVAL 8 DAY; - SET vDate6 = util.VN_CURDATE() - INTERVAL 6 DAY; - SET vDate2000 = util.VN_CURDATE() + INTERVAL (2000 - YEAR(util.VN_CURDATE())) YEAR; - SET vRangeDeleteTicket = 60; - - DELETE FROM cdr WHERE calldate < vDate18; - DELETE FROM mail WHERE DATE_ODBC < vDate; - DELETE FROM Movimientos_mark WHERE odbc_date < vDate; - DELETE FROM Splits WHERE Fecha < vDate18; - - DELETE tobs - FROM movement_label tobs - JOIN Movimientos m ON tobs.Id_Movimiento = m.Id_Movimiento - JOIN Tickets t ON m.Id_Ticket = t.Id_Ticket WHERE t.Fecha < vDate; - - DELETE FROM Remesas WHERE `Fecha Remesa` < vDate18; - - DELETE tt.* - FROM Tickets_turno tt - LEFT JOIN Movimientos m USING(Id_Ticket) - WHERE m.Id_Article IS NULL; - - DELETE FROM cl_main WHERE Fecha < vDate18; - DELETE FROM hedera.`order` WHERE date_send < vDate18; - DELETE FROM vn.message WHERE sendDate < vDate; - - DELETE FROM cache.departure_limit WHERE Fecha < util.VN_CURDATE() - INTERVAL 1 MONTH; - - DELETE cm - FROM Compres_mark cm - JOIN Compres c ON c.Id_Compra = cm.Id_Compra - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel t ON t.id = e.travel_id - WHERE t.landing <= vDate; - - IF v_full THEN - CREATE OR REPLACE TEMPORARY TABLE tTicketDelete - SELECT DISTINCT tl.originFk ticketFk - FROM vn.ticketLog tl - JOIN (SELECT MAX(tl.id)ids - FROM vn.ticket t - JOIN vn.ticketLog tl ON tl.originFk = t.id - WHERE t.shipped BETWEEN '2000-01-01' AND '2000-12-31' - AND t.isDeleted - GROUP BY t.id - )sub ON sub.ids = tl.id - WHERE tl.creationDate <= util.VN_CURDATE() - INTERVAL 60 DAY; - - DELETE t - FROM vn.ticket t - JOIN tTicketDelete tmp ON tmp.ticketFk = t.id; - - DROP TEMPORARY TABLE tTicketDelete; - END IF; - - -- Tickets Nulos PAK 11/10/2016 - UPDATE Tickets - SET empresa_id = 965 - WHERE Id_Cliente = 31 - AND empresa_id != 965; -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/procedures/clean_launcher.sql b/db/routines/vn2008/procedures/clean_launcher.sql deleted file mode 100644 index 63c23e8cf..000000000 --- a/db/routines/vn2008/procedures/clean_launcher.sql +++ /dev/null @@ -1,6 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`clean_launcher`() -BEGIN - CALL clean(TRUE); -END$$ -DELIMITER ; diff --git a/db/versions/10915-limeMastic/00-firstScript.sql b/db/versions/10915-limeMastic/00-firstScript.sql new file mode 100644 index 000000000..be83a4984 --- /dev/null +++ b/db/versions/10915-limeMastic/00-firstScript.sql @@ -0,0 +1,2 @@ +DELETE IGNORE FROM bs.nightTask + WHERE `procedure` = 'clean_launcher'; From 80ecd698f8011c506b467f255ab285c8a42ba466 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 28 Feb 2024 08:23:58 +0100 Subject: [PATCH 104/150] refactor: refs #6499 Migrated procs to vn --- .../procedures/balanceNestTree_addChild.sql} | 33 +++--- .../procedures/balanceNestTree_delete.sql} | 35 +++--- .../vn/procedures/balanceNestTree_move.sql | 111 ++++++++++++++++++ db/routines/vn/procedures/pay.sql | 68 +++++++++++ db/routines/vn2008/procedures/nest_move.sql | 108 ----------------- db/routines/vn2008/procedures/pay.sql | 67 ----------- 6 files changed, 210 insertions(+), 212 deletions(-) rename db/routines/{vn2008/procedures/nest_child_add.sql => vn/procedures/balanceNestTree_addChild.sql} (54%) rename db/routines/{vn2008/procedures/nest_delete.sql => vn/procedures/balanceNestTree_delete.sql} (52%) create mode 100644 db/routines/vn/procedures/balanceNestTree_move.sql create mode 100644 db/routines/vn/procedures/pay.sql delete mode 100644 db/routines/vn2008/procedures/nest_move.sql delete mode 100644 db/routines/vn2008/procedures/pay.sql diff --git a/db/routines/vn2008/procedures/nest_child_add.sql b/db/routines/vn/procedures/balanceNestTree_addChild.sql similarity index 54% rename from db/routines/vn2008/procedures/nest_child_add.sql rename to db/routines/vn/procedures/balanceNestTree_addChild.sql index 5b45a9d07..d16168a59 100644 --- a/db/routines/vn2008/procedures/nest_child_add.sql +++ b/db/routines/vn/procedures/balanceNestTree_addChild.sql @@ -1,48 +1,45 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`nest_child_add`( - vTable VARCHAR(45) - ,vChild VARCHAR(45) - ,vFatherId INT +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_addChild`( + vSelfFather INT, + vName VARCHAR(45) ) BEGIN - DECLARE vMyLeft INT; + DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree'); + DECLARE vLeft INT; - SET vTable = util.quoteIdentifier(vTable); - - DROP TEMPORARY TABLE IF EXISTS aux; - CREATE TEMPORARY TABLE aux - SELECT 0 as lft; + CREATE OR REPLACE TEMPORARY TABLE tAux + SELECT 0 lft; EXECUTE IMMEDIATE CONCAT( - 'UPDATE aux + 'UPDATE tAux SET lft = (SELECT lft FROM ', vTable, ' WHERE id = ?)') USING vFatherId; - SELECT lft INTO vMyLeft FROM aux; - DROP TEMPORARY TABLE aux; + SELECT lft INTO vLeft FROM tAux; EXECUTE IMMEDIATE CONCAT( 'UPDATE ', vTable, ' SET rgt = rgt + 2 WHERE rgt > ? ORDER BY rgt DESC') - USING vMyLeft; + USING vLeft; EXECUTE IMMEDIATE CONCAT( 'UPDATE ', vTable, ' SET lft = lft + 2 WHERE lft > ? ORDER BY lft DESC') - USING vMyLeft; + USING vLeft; EXECUTE IMMEDIATE CONCAT( 'INSERT INTO ', vTable, ' (name, lft, rgt) VALUES(?, ? + 1, ? + 2)') USING vChild, - vMyLeft, - vMyLeft; - + vLeft, + vLeft; + + DROP TEMPORARY TABLE tAux; END$$ DELIMITER ; diff --git a/db/routines/vn2008/procedures/nest_delete.sql b/db/routines/vn/procedures/balanceNestTree_delete.sql similarity index 52% rename from db/routines/vn2008/procedures/nest_delete.sql rename to db/routines/vn/procedures/balanceNestTree_delete.sql index 84f75294b..d2f37851f 100644 --- a/db/routines/vn2008/procedures/nest_delete.sql +++ b/db/routines/vn/procedures/balanceNestTree_delete.sql @@ -1,51 +1,48 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`nest_delete`( - vTable VARCHAR(45) - ,vNodeId INT +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_delete`( + vSelf INT ) BEGIN - DECLARE vMyRight INT; - DECLARE vMyLeft INT; - DECLARE vMyWidth INT; + DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree'); + DECLARE vRight INT; + DECLARE vLeft INT; + DECLARE vWidth INT; - DROP TEMPORARY TABLE IF EXISTS aux; - CREATE TEMPORARY TABLE aux + CREATE OR REPLACE TEMPORARY TABLE tAux SELECT 0 rgt, 0 lft, 0 wdt; - - SET vTable = util.quoteIdentifier(vTable); EXECUTE IMMEDIATE CONCAT( - 'UPDATE aux a + 'UPDATE tAux a JOIN ', vTable, ' t SET a.rgt = t.rgt, a.lft = t.lft, a.wdt = t.rgt - t.lft + 1 WHERE t.id = ?') - USING vNodeId; + USING vSelf; SELECT rgt, lft, wdt - INTO vMyRight, vMyLeft, vMyWidth - FROM aux; - - DROP TEMPORARY TABLE aux; + INTO vRight, vLeft, vWidth + FROM tAux; EXECUTE IMMEDIATE CONCAT( 'DELETE FROM ', vTable, ' WHERE lft BETWEEN ? AND ?') - USING vMyLeft, vMyRight; + USING vLeft, vRight; EXECUTE IMMEDIATE CONCAT( 'UPDATE ', vTable, ' SET rgt = rgt - ? WHERE rgt > ? ORDER BY rgt') - USING vMyWidth,vMyRight; + USING vWidth,vRight; EXECUTE IMMEDIATE CONCAT( 'UPDATE ', vTable, ' SET lft = lft - ? WHERE lft > ? ORDER BY lft') - USING vMyWidth, vMyRight; + USING vWidth, vRight; + + DROP TEMPORARY TABLE tAux; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/balanceNestTree_move.sql b/db/routines/vn/procedures/balanceNestTree_move.sql new file mode 100644 index 000000000..ea7c734db --- /dev/null +++ b/db/routines/vn/procedures/balanceNestTree_move.sql @@ -0,0 +1,111 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_move`( + vSelfNode INT, + vSelfFather INT +) +BEGIN + DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree'); + DECLARE vRight INT; + DECLARE vLeft INT; + DECLARE vWidth INT; + DECLARE vFatherRight INT; + DECLARE vFatherLeft INT; + DECLARE vGap INT; + + CREATE OR REPLACE TEMPORARY TABLE tAux + SELECT 0 rgt, 0 lft, 0 wdt, 0 frg, 0 flf; + + -- Averiguamos el ancho de la rama + EXECUTE IMMEDIATE CONCAT( + 'UPDATE tAux a + JOIN ', vTable, ' t + SET a.wdt = t.rgt - t.lft + 1 + WHERE t.id = ?') + USING vSelfNode; + + -- Averiguamos la posicion del nuevo padre + EXECUTE IMMEDIATE CONCAT( + 'UPDATE tAux a + JOIN ', vTable, ' t + SET a.frg = t.rgt, + a.flf = t.lft + WHERE t.id = ?') + USING vSelfFather; + + SELECT wdt, frg, flf + INTO vWidth, vFatherRight, vFatherLeft + FROM tAux; + + -- 1º Incrementamos los valores de todos los nodos a la derecha + -- del punto de inserción (vFatherRight) , para hacer sitio + EXECUTE IMMEDIATE CONCAT( + 'UPDATE ', vTable, + 'SET rgt = rgt + ? + WHERE rgt >= ? + ORDER BY rgt DESC') + USING vWidth, + vFatherRight; + + EXECUTE IMMEDIATE CONCAT( + 'UPDATE ', vTable, + 'SET lft = lft + ? + WHERE lft >= ? + ORDER BY lft DESC') + USING vWidth, + vFatherRight; + + -- Es preciso recalcular los valores del nodo en el + -- caso de que estuviera a la derecha del nuevo padre + EXECUTE IMMEDIATE CONCAT( + 'UPDATE tAux a + JOIN ', vTable, ' t + SET a.rgt = t.rgt, + a.lft = t.lft + WHERE t.id = ?') + USING vSelfNode; + + SELECT lft, rgt, frg - lft + INTO vLeft, vRight, vGap + FROM tAux; + + -- 2º Incrementamos el valor de todos los nodos a + -- trasladar hasta alcanzar su nueva posicion + EXECUTE IMMEDIATE CONCAT( + 'UPDATE ', vTable, + 'SET lft = lft + ? + WHERE lft BETWEEN ? AND ? + ORDER BY lft DESC') + USING vGap, + vLeft, + vRight; + + EXECUTE IMMEDIATE CONCAT( + 'UPDATE ', vTable, + 'SET rgt = rgt + ? + WHERE rgt BETWEEN ? AND ? + ORDER BY rgt DESC') + USING vGap, + vLeft, + vRight; + + -- 3º Restaremos a todos los nodos resultantes, a la derecha + -- de la posicion arrancada el ancho de la rama escindida + EXECUTE IMMEDIATE CONCAT( + 'UPDATE ', vTable, + 'SET lft = lft - ? + WHERE lft > ? + ORDER BY lft') + USING vWidth, + vLeft; + + EXECUTE IMMEDIATE CONCAT( + 'UPDATE ', vTable, + 'SET rgt = rgt - ? + WHERE rgt > ? + ORDER BY rgt') + USING vWidth, + vRight; + + DROP TEMPORARY TABLE tAux; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/pay.sql b/db/routines/vn/procedures/pay.sql new file mode 100644 index 000000000..42b7a6a55 --- /dev/null +++ b/db/routines/vn/procedures/pay.sql @@ -0,0 +1,68 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`pay`( + vDated DATE, + vSupplierFk INT, + vAmount DOUBLE, + vCurrencyFk INT, + vDivisa DOUBLE, + vBankFk INT, + vPayMethodFk INT, + vExpenseFk DOUBLE, + vConcept VARCHAR(40), + vCompanyFk INT) +BEGIN + INSERT INTO till( + concept, + serie, + `number`, + `out`, + dated, + isAccountable, + bankFk, + workerFk, + companyFk, + isConciliate + ) + SELECT CONCAT('n/pago a ', `name`), + 'R', + vSupplierFk, + vAmount, + vDated, + 1, + vBankFk, + account.myUser_getId(), + vCompanyFk, + 1 + FROM supplier + WHERE id = vSupplierFk; + + INSERT INTO payment( + received, + dueDated, + supplierFk, + amount, + currencyFk, + divisa, + bankFk, + payMethodFk, + bankingFees, + concept, + companyFk + ) + VALUES( + vDated, + vDated, + vSupplierFk, + vAmount, + vCurrencyFk, + IF(NOT vDivisa, NULL, vDivisa), + vBankFk, + vPayMethodFk, + vExpenseFk, + vConcept, + vCompanyFk + ); + + SELECT LAST_INSERT_ID() pago_id; +END$$ +DELIMITER ; diff --git a/db/routines/vn2008/procedures/nest_move.sql b/db/routines/vn2008/procedures/nest_move.sql deleted file mode 100644 index 950d46e68..000000000 --- a/db/routines/vn2008/procedures/nest_move.sql +++ /dev/null @@ -1,108 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`nest_move`( - vTable VARCHAR(45) - ,idNODE INT - ,idFATHER INT -) -BEGIN - DECLARE myRight INT; - DECLARE myLeft INT; - DECLARE myWidth INT; - DECLARE fatherRight INT; - DECLARE fatherLeft INT; - DECLARE gap INT; - - SET vTable = util.quoteIdentifier(vTable); - - DROP TEMPORARY TABLE IF EXISTS aux; - CREATE TEMPORARY TABLE aux - SELECT 0 as rgt, 0 as lft, 0 as wdt, 0 as frg, 0 as flf; - - -- Averiguamos el ancho de la rama - EXECUTE IMMEDIATE CONCAT( - 'UPDATE aux a - JOIN ', vTable, ' t - SET a.wdt = t.rgt - t.lft + 1 - WHERE t.id = ?') - USING idNODE; - - -- Averiguamos la posicion del nuevo padre - EXECUTE IMMEDIATE CONCAT( - 'UPDATE aux a - JOIN ', vTable, ' t - SET a.frg = t.rgt, - a.flf = t.lft - WHERE t.id = ?') - USING idFATHER; - - SELECT wdt, frg, flf INTO myWidth, fatherRight, fatherLeft - FROM aux; - - -- 1º Incrementamos los valores de todos los nodos a la derecha del punto de inserción (fatherRight) , para hacer sitio - EXECUTE IMMEDIATE CONCAT( - 'UPDATE ', vTable, - 'SET rgt = rgt + ? - WHERE rgt >= ? - ORDER BY rgt DESC') - USING myWidth, - fatherRight; - - EXECUTE IMMEDIATE CONCAT( - 'UPDATE ', vTable, - 'SET lft = lft + ? - WHERE lft >= ? - ORDER BY lft DESC') - USING myWidth, - fatherRight; - - -- Es preciso recalcular los valores del nodo en el caso de que estuviera a la derecha del nuevo padre - EXECUTE IMMEDIATE CONCAT( - 'UPDATE aux a - JOIN ', vTable, ' t - SET a.rgt = t.rgt, - a.lft = t.lft - WHERE t.id = ?') - USING idNODE; - - SELECT lft, rgt, frg - lft INTO myLeft, myRight, gap - FROM aux; - - -- 2º Incrementamos el valor de todos los nodos a trasladar hasta alcanzar su nueva posicion - EXECUTE IMMEDIATE CONCAT( - 'UPDATE ', vTable, - 'SET lft = lft + ? - WHERE lft BETWEEN ? AND ? - ORDER BY lft DESC') - USING gap, - myLeft, - myRight; - - EXECUTE IMMEDIATE CONCAT( - 'UPDATE ', vTable, - 'SET rgt = rgt + ? - WHERE rgt BETWEEN ? AND ? - ORDER BY rgt DESC') - USING gap, - myLeft, - myRight; - - -- 3º Restaremos a todos los nodos resultantes, a la derecha de la posicion arrancada el ancho de la rama escindida - EXECUTE IMMEDIATE CONCAT( - 'UPDATE ', vTable, - 'SET lft = lft - ? - WHERE lft > ? - ORDER BY lft') - USING myWidth, - myLeft; - - EXECUTE IMMEDIATE CONCAT( - 'UPDATE ', vTable, - 'SET rgt = rgt - ? - WHERE rgt > ? - ORDER BY rgt') - USING myWidth, - myRight; - - DROP TEMPORARY TABLE aux; -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/procedures/pay.sql b/db/routines/vn2008/procedures/pay.sql deleted file mode 100644 index ec73ee696..000000000 --- a/db/routines/vn2008/procedures/pay.sql +++ /dev/null @@ -1,67 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`pay`(IN datFEC DATE - , IN idPROV INT - , IN dblIMPORTE DOUBLE - , IN idMONEDA INT - , IN dblDIVISA DOUBLE - , IN idCAJA INT - , IN idPAYMET INT - , IN dblGASTOS DOUBLE - , IN strCONCEPTO VARCHAR(40) - , IN idEMP INT) -BEGIN - - -- Registro en la tabla Cajas - INSERT INTO Cajas ( Concepto - , Serie - , Numero - , Salida - , Cajafecha - , Partida - , Id_Banco - , Id_Trabajador - ,empresa_id - ,conciliado) - - SELECT CONCAT('n/pago a ', Proveedor) - , 'R' - , idPROV - , dblIMPORTE - , datFEC - , 1 - , idCAJA - , account.myUser_getId() - , idEMP - , 1 - FROM Proveedores - WHERE Id_Proveedor = idPROV; - - -- Registro en la tabla pago - INSERT INTO pago(fecha - , dueDated - , id_proveedor - , importe - , id_moneda - , divisa - , id_banco - , pay_met_id - , g_bancarios - , concepte - , empresa_id) - - VALUES(datFEC - , datFEC - , idPROV - , dblIMPORTE - , idMONEDA - , IF(dblDIVISA = 0, NULL, dblDIVISA) - , idCAJA - , idPAYMET - , dblGASTOS - , strCONCEPTO - , idEMP); - - SELECT LAST_INSERT_ID() as pago_id; - -END$$ -DELIMITER ; From 6c67462943343b21c5cc5292c24762665523325e Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 28 Feb 2024 08:26:17 +0100 Subject: [PATCH 105/150] refactor: refs #6499 Minor changes --- db/routines/vn/procedures/balanceNestTree_addChild.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/balanceNestTree_addChild.sql b/db/routines/vn/procedures/balanceNestTree_addChild.sql index d16168a59..a4d6dc4b0 100644 --- a/db/routines/vn/procedures/balanceNestTree_addChild.sql +++ b/db/routines/vn/procedures/balanceNestTree_addChild.sql @@ -15,7 +15,7 @@ BEGIN SET lft = (SELECT lft FROM ', vTable, ' WHERE id = ?)') - USING vFatherId; + USING vSelfFather; SELECT lft INTO vLeft FROM tAux; From b9c5930f68a31f93125229227a44ecdb70b5e379 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 28 Feb 2024 08:29:12 +0100 Subject: [PATCH 106/150] refactor: refs #6499 Minor changes --- db/routines/vn/procedures/balanceNestTree_addChild.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/balanceNestTree_addChild.sql b/db/routines/vn/procedures/balanceNestTree_addChild.sql index a4d6dc4b0..7433cbb42 100644 --- a/db/routines/vn/procedures/balanceNestTree_addChild.sql +++ b/db/routines/vn/procedures/balanceNestTree_addChild.sql @@ -36,7 +36,7 @@ BEGIN EXECUTE IMMEDIATE CONCAT( 'INSERT INTO ', vTable, ' (name, lft, rgt) VALUES(?, ? + 1, ? + 2)') - USING vChild, + USING vName, vLeft, vLeft; From cba0e55846045da31098d94f15d9e2c207a8c403 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 28 Feb 2024 08:39:49 +0100 Subject: [PATCH 107/150] refactor: refs #6499 Added comments --- .../vn/procedures/balanceNestTree_addChild.sql | 11 +++++++++-- .../vn/procedures/balanceNestTree_delete.sql | 5 +++++ db/routines/vn/procedures/balanceNestTree_move.sql | 12 +++++++++--- db/routines/vn/procedures/pay.sql | 14 ++++++++++++++ 4 files changed, 37 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/balanceNestTree_addChild.sql b/db/routines/vn/procedures/balanceNestTree_addChild.sql index 7433cbb42..0f4f31b06 100644 --- a/db/routines/vn/procedures/balanceNestTree_addChild.sql +++ b/db/routines/vn/procedures/balanceNestTree_addChild.sql @@ -1,9 +1,16 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_addChild`( - vSelfFather INT, + vSelf INT, vName VARCHAR(45) ) BEGIN +/** + * Agrega u nuevo nodo hijo a un nodo existente dentro de la estructura + * de árbol de vn.balanceNestTree. + * + * @param vSelf Identificador del nodo + * @param vName Nombre del nuevo nodo hijo + */ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree'); DECLARE vLeft INT; @@ -15,7 +22,7 @@ BEGIN SET lft = (SELECT lft FROM ', vTable, ' WHERE id = ?)') - USING vSelfFather; + USING vSelf; SELECT lft INTO vLeft FROM tAux; diff --git a/db/routines/vn/procedures/balanceNestTree_delete.sql b/db/routines/vn/procedures/balanceNestTree_delete.sql index d2f37851f..1d6a9efff 100644 --- a/db/routines/vn/procedures/balanceNestTree_delete.sql +++ b/db/routines/vn/procedures/balanceNestTree_delete.sql @@ -3,6 +3,11 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_del vSelf INT ) BEGIN +/** + * Elimina un nodo dentro de la estructura de árbol de vn.balanceNestTree. + * + * @param vSelf Identificador del nodo + */ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree'); DECLARE vRight INT; DECLARE vLeft INT; diff --git a/db/routines/vn/procedures/balanceNestTree_move.sql b/db/routines/vn/procedures/balanceNestTree_move.sql index ea7c734db..e4f0b9de4 100644 --- a/db/routines/vn/procedures/balanceNestTree_move.sql +++ b/db/routines/vn/procedures/balanceNestTree_move.sql @@ -1,9 +1,15 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_move`( - vSelfNode INT, + vSelf INT, vSelfFather INT ) BEGIN +/** + * Mueve un nodo dentro de la estructura de árbol de vn.balanceNestTree. + * + * @param vSelf Identificador del nodo + * @param vSelfFather Identificador del nuevo padre del nodo + */ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree'); DECLARE vRight INT; DECLARE vLeft INT; @@ -21,7 +27,7 @@ BEGIN JOIN ', vTable, ' t SET a.wdt = t.rgt - t.lft + 1 WHERE t.id = ?') - USING vSelfNode; + USING vSelf; -- Averiguamos la posicion del nuevo padre EXECUTE IMMEDIATE CONCAT( @@ -62,7 +68,7 @@ BEGIN SET a.rgt = t.rgt, a.lft = t.lft WHERE t.id = ?') - USING vSelfNode; + USING vSelf; SELECT lft, rgt, frg - lft INTO vLeft, vRight, vGap diff --git a/db/routines/vn/procedures/pay.sql b/db/routines/vn/procedures/pay.sql index 42b7a6a55..5dc21e45f 100644 --- a/db/routines/vn/procedures/pay.sql +++ b/db/routines/vn/procedures/pay.sql @@ -11,6 +11,20 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`pay`( vConcept VARCHAR(40), vCompanyFk INT) BEGIN +/** + * Registra un pago realizado a un proveedor. + * + * @param vDated Fecha del pago + * @param vSupplierFk Id del proveedor + * @param vAmount Cantidad a pagar + * @param vCurrencyFk Id de la moneda + * @param vDivisa Tipo de cambio utilizado + * @param vBankFk Id del banco + * @param vPayMethodFk Id del método de pago + * @param vExpenseFk Id de gasto + * @param vConcept Concepto del pago + * @param vCompanyFk Id de la empresa + */ INSERT INTO till( concept, serie, From f95a4f3530a14b875e113ef155920ccbbff407a9 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 28 Feb 2024 09:06:48 +0100 Subject: [PATCH 108/150] refactor: refs #6276 drop setState function --- back/methods/collection/getSales.js | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index c9f277890..cf0496600 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -42,7 +42,12 @@ module.exports = Self => { const [tickets] = await Self.rawSql('CALL vn.collection_getTickets(?)', [id], myOptions); - await setState(source, id, myOptions); + if (source) { + await Self.rawSql( + 'CALL vn.ticketStateToday_setState(?,?)', [id, source], options + ); + } + const [sales] = await Self.rawSql('CALL vn.sale_getFromTicketOrCollection(?)', [id], myOptions); @@ -151,16 +156,4 @@ module.exports = Self => { AND tr.landed >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)`; return Self.rawSql(query, [ticketId], options); } - - async function setState(source, id, options) { - const states = { - 'PRECHECKER': 'PREVIOUS_CONTROL', - 'CHECKER': 'ON_CHECKING' - }; - if (states[source]) { - await Self.rawSql( - 'CALL vn.ticketStateToday_setState(?,?)', [id, states[source]], options - ); - } - } }; From b8e6cc9f9ce3e6221aba1385046db019daf0bb47 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 28 Feb 2024 09:08:47 +0100 Subject: [PATCH 109/150] refactor: refs #6499 Added comments --- db/routines/vn/procedures/balanceNestTree_addChild.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/balanceNestTree_addChild.sql b/db/routines/vn/procedures/balanceNestTree_addChild.sql index 0f4f31b06..5cd1ab470 100644 --- a/db/routines/vn/procedures/balanceNestTree_addChild.sql +++ b/db/routines/vn/procedures/balanceNestTree_addChild.sql @@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_add ) BEGIN /** - * Agrega u nuevo nodo hijo a un nodo existente dentro de la estructura + * Agrega un nuevo nodo hijo a un nodo existente dentro de la estructura * de árbol de vn.balanceNestTree. * * @param vSelf Identificador del nodo From 9f2d1a8c0f523db3b7ec33ad90dd1d883136e8dd Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 28 Feb 2024 09:13:01 +0100 Subject: [PATCH 110/150] refactor: refs #6499 Minor change --- db/routines/vn/procedures/pay.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/pay.sql b/db/routines/vn/procedures/pay.sql index 5dc21e45f..c868bfb53 100644 --- a/db/routines/vn/procedures/pay.sql +++ b/db/routines/vn/procedures/pay.sql @@ -24,6 +24,7 @@ BEGIN * @param vExpenseFk Id de gasto * @param vConcept Concepto del pago * @param vCompanyFk Id de la empresa + * @return paymentFk Id de pago insertado */ INSERT INTO till( concept, @@ -77,6 +78,6 @@ BEGIN vCompanyFk ); - SELECT LAST_INSERT_ID() pago_id; + SELECT LAST_INSERT_ID() paymentFk; END$$ DELIMITER ; From 82445683a77d9fc0599980691ea8a03857e29a1a Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 28 Feb 2024 09:19:57 +0100 Subject: [PATCH 111/150] fix: refs #6501 entry_getTransferFix --- .../vn/procedures/entry_getTransfer.sql | 47 +++++++++---------- 1 file changed, 21 insertions(+), 26 deletions(-) diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 151bebd4d..b82f273ae 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -13,15 +13,15 @@ BEGIN DECLARE vWarehouseIn INT; DECLARE vWarehouseOut INT; DECLARE vCalcVisible INT; - DECLARE vInventoryDate DATE DEFAULT vn.getInventoryDate(); + DECLARE vInventoryDate DATE DEFAULT getInventoryDate(); SELECT shipped, landed, warehouseInFk, warehouseOutFk INTO vDateShipped, vDateLanded, vWarehouseIn, vWarehouseOut - FROM vn.travel t - JOIN vn.entry e ON e.travelFk = t.id + FROM travel t + JOIN entry e ON e.travelFk = t.id WHERE e.id = vSelf; - CALL vn.rate_getPrices(vDateShipped, vWarehouseIn); + CALL rate_getPrices(vDateShipped, vWarehouseIn); -- Traslado en almacen origen CREATE OR REPLACE TEMPORARY TABLE tBuy @@ -84,7 +84,7 @@ BEGIN WHERE a.available ON DUPLICATE KEY UPDATE availableLanding = a.available; ELSE - CALL vn.item_getStock(vWarehouseOut, vDateShipped, NULL); + CALL item_getStock(vWarehouseOut, vDateShipped, NULL); CREATE OR REPLACE TEMPORARY TABLE tItem (UNIQUE INDEX i USING HASH (itemFk)) @@ -97,7 +97,7 @@ BEGIN FROM tmp.itemList; END IF; - CALL vn.buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded); + CALL buyUltimateFromInterval(vWarehouseIn,vInventoryDate, vDateLanded); CREATE OR REPLACE TEMPORARY TABLE tTransfer ENGINE = MEMORY @@ -145,26 +145,26 @@ BEGIN b.id buyFkOrigin, pa.returnCost, b.weight - FROM vn.item i + FROM item i JOIN tItem ti ON ti.itemFk = i.id - LEFT JOIN vn.producer p ON p.id = i.producerFk - LEFT JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN producer p ON p.id = i.producerFk + LEFT JOIN itemType it ON it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN origin o ON o.id = i.originFk LEFT JOIN tBuy lb ON lb.itemFk = i.id - LEFT JOIN vn.buy b ON b.id = lb.buyFk - LEFT JOIN vn.packaging pa ON pa.id = b.packagingFk - LEFT JOIN vn.entry e2 ON e2.id = b.entryFk - LEFT JOIN vn.supplier s ON s.id = e2.supplierFk - LEFT JOIN vn.entry e ON e.id = vSelf - LEFT JOIN vn.travel tr ON tr.id = e.travelFk - LEFT JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - LEFT JOIN vn.buy b2 ON b2.itemFk = i.id + LEFT JOIN buy b ON b.id = lb.buyFk + LEFT JOIN packaging pa ON pa.id = b.packagingFk + LEFT JOIN entry e2 ON e2.id = b.entryFk + LEFT JOIN supplier s ON s.id = e2.supplierFk + LEFT JOIN entry e ON e.id = vSelf + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN agencyMode am ON am.id = tr.agencyModeFk + LEFT JOIN buy b2 ON b2.itemFk = i.id AND b2.entryFk = vSelf - LEFT JOIN vn.packaging pa2 ON pa2.id = b.packagingFk + LEFT JOIN packaging pa2 ON pa2.id = b.packagingFk LEFT JOIN tmp.rate r ON TRUE LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id - LEFT JOIN vn.buy b3 ON b3.id = bufi.buyFk + LEFT JOIN buy b3 ON b3.id = bufi.buyFk WHERE ic.display AND NOT e.isRaid AND (ti.visible OR ti.available) @@ -172,11 +172,6 @@ BEGIN CREATE INDEX tIndex USING HASH ON tTransfer (itemFk); - SET @carriage := 0; - SET @comission := 0; - SET @packaging := 0; - SET @rate3 := 0; - SET @cost := 0; SELECT *, quantity - MOD(quantity , `grouping`) subQuantity, MOD(quantity, `grouping`) soll, From 6b7dc67c3e1f42f3e94da3946331d68d57fa0034 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Thu, 29 Feb 2024 06:25:41 +0000 Subject: [PATCH 112/150] hotfix fix: replace pdf with csv --- modules/invoiceOut/back/methods/invoiceOut/invoiceCsv.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/invoiceCsv.js b/modules/invoiceOut/back/methods/invoiceOut/invoiceCsv.js index d33df74a2..c734b588c 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/invoiceCsv.js +++ b/modules/invoiceOut/back/methods/invoiceOut/invoiceCsv.js @@ -80,6 +80,6 @@ module.exports = Self => { const content = toCSV(sales); - return [content, 'text/csv', `inline; filename="doc-${reference}.pdf"`]; + return [content, 'text/csv', `inline; filename="doc-${reference}.csv"`]; }; }; From 599e8761c15d06a67f1c5cc224c1d197814449d9 Mon Sep 17 00:00:00 2001 From: JAVIER SEGARRA MARTINEZ Date: Thu, 29 Feb 2024 06:26:21 +0000 Subject: [PATCH 113/150] hotfix fix: replace pdf with csv --- modules/ticket/back/methods/ticket/deliveryNoteCsv.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/deliveryNoteCsv.js b/modules/ticket/back/methods/ticket/deliveryNoteCsv.js index 55ec4089d..40526ac16 100644 --- a/modules/ticket/back/methods/ticket/deliveryNoteCsv.js +++ b/modules/ticket/back/methods/ticket/deliveryNoteCsv.js @@ -79,6 +79,6 @@ module.exports = Self => { ORDER BY s.ticketFk, s.created`, [id]); const content = toCSV(sales); - return [content, 'text/csv', `inline; filename="doc-${id}.pdf"`]; + return [content, 'text/csv', `inline; filename="doc-${id}.csv"`]; }; }; From 7a43ccaa3685d11afcedcb68569eaa75b5b6ca3c Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 29 Feb 2024 07:32:19 +0100 Subject: [PATCH 114/150] refactor: refs #6496 Requested changes --- db/routines/cache/procedures/clean.sql | 6 +--- db/routines/vn/procedures/clean.sql | 45 +++++++++++++------------- 2 files changed, 24 insertions(+), 27 deletions(-) diff --git a/db/routines/cache/procedures/clean.sql b/db/routines/cache/procedures/clean.sql index ee64d052e..5e6628689 100644 --- a/db/routines/cache/procedures/clean.sql +++ b/db/routines/cache/procedures/clean.sql @@ -1,10 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `cache`.`clean`() BEGIN - DECLARE vDateShort DATETIME; - - SET vDateShort = util.VN_CURDATE() - INTERVAL 1 MONTH; - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; + DELETE FROM cache.departure_limit WHERE Fecha < util.VN_CURDATE() - INTERVAL 1 MONTH; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/clean.sql b/db/routines/vn/procedures/clean.sql index c1cafc0fe..898a5c835 100644 --- a/db/routines/vn/procedures/clean.sql +++ b/db/routines/vn/procedures/clean.sql @@ -82,7 +82,7 @@ BEGIN DELETE c FROM claim c JOIN claimState cs ON cs.id = c.claimStateFk - WHERE cs.description = "Anulado" + WHERE cs.description = 'Anulado' AND c.created < v2Months; DELETE FROM expeditionTruck WHERE eta < v3Months; @@ -94,69 +94,71 @@ BEGIN FROM travel t LEFT JOIN entry e ON e.travelFk = t.id JOIN travelThermograph th ON th.travelFk = t.id - WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL; + WHERE t.shipped < v3Months + AND e.travelFk IS NULL; SELECT dt.id INTO vTrashId FROM dmsType dt WHERE dt.code = 'trash'; UPDATE tThermographToDelete th - JOIN dms d ON d.id = th.dmsFk + JOIN dms d ON d.id = th.dmsFk SET d.dmsTypeFk = vTrashId; DELETE th FROM tThermographToDelete tmp - JOIN travelThermograph th ON th.id = tmp.id; + JOIN travelThermograph th ON th.id = tmp.id; DELETE t FROM travel t - LEFT JOIN entry e ON e.travelFk = t.id - WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL; + LEFT JOIN entry e ON e.travelFk = t.id + WHERE t.shipped < v3Months AND e.travelFk IS NULL; UPDATE dms d JOIN dmsType dt ON dt.id = d.dmsTypeFk SET d.dmsTypeFk = vTrashId - WHERE created < TIMESTAMPADD(MONTH, -dt.monthToDelete, util.VN_CURDATE()); + WHERE created < util.VN_CURDATE() - INTERVAL dt.monthToDelete MONTH; -- borrar entradas sin compras CREATE OR REPLACE TEMPORARY TABLE tEntryToDelete SELECT e.* FROM entry e - LEFT JOIN buy b ON b.entryFk = e.id - JOIN entryConfig ec ON e.id <> ec.defaultEntry - WHERE e.dated < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND b.entryFK IS NULL; + LEFT JOIN buy b ON b.entryFk = e.id + JOIN entryConfig ec ON e.id <> ec.defaultEntry + WHERE e.dated < v3Months + AND b.entryFK IS NULL; DELETE e FROM entry e - JOIN tEntryToDelete tmp ON tmp.id = e.id; + JOIN tEntryToDelete tmp ON tmp.id = e.id; -- borrar de route registros menores a 4 años CREATE OR REPLACE TEMPORARY TABLE tRouteToDelete SELECT * - FROM route r - WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); + FROM route r + WHERE created < v4Years; UPDATE tRouteToDelete tmp - JOIN dms d ON d.id = tmp.gestdocFk + JOIN dms d ON d.id = tmp.gestdocFk SET d.dmsTypeFk = vTrashId; DELETE r FROM tRouteToDelete tmp - JOIN route r ON r.id = tmp.id; + JOIN route r ON r.id = tmp.id; -- borrar registros de dua y awb menores a 2 años CREATE OR REPLACE TEMPORARY TABLE tDuaToDelete SELECT * FROM dua - WHERE operated < TIMESTAMPADD(YEAR,-2,CURDATE()); + WHERE operated < v2Years; - UPDATE tDuaToDelete tm - JOIN dms d ON d.id = tm.gestdocFk + UPDATE tDuaToDelete tm + JOIN dms d ON d.id = tm.gestdocFk SET d.dmsTypeFk = vTrashId; DELETE d FROM tDuaToDelete tmp - JOIN dua d ON d.id = tmp.id; + JOIN dua d ON d.id = tmp.id; DELETE a FROM awb a @@ -165,17 +167,16 @@ BEGIN AND t.id IS NULL; -- Borra los registros de collection y ticketcollection - DELETE FROM collection WHERE created < v2Months; + DELETE FROM collection WHERE created < v2Months; DELETE FROM travelLog WHERE creationDate < v3Months; CALL shelving_clean(); DELETE FROM chat WHERE dated < v5Years; DELETE tt FROM ticketTracking tt - JOIN ticket t ON tt.ticketFk = t.id + JOIN ticket t ON tt.ticketFk = t.id WHERE t.shipped <= v2Months; - -- Clean vn2008 DELETE FROM mail WHERE creationDate < v2Months; DELETE FROM split WHERE dated < v18Months; DELETE FROM remittance WHERE dated < v18Months; From 96bab9b27d039a04b246f01dc1439642f39b8a02 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 29 Feb 2024 07:37:23 +0100 Subject: [PATCH 115/150] refactor: refs #6496 Requested changes --- db/routines/vn/procedures/balanceNestTree_move.sql | 6 +++--- db/routines/vn/procedures/pay.sql | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/balanceNestTree_move.sql b/db/routines/vn/procedures/balanceNestTree_move.sql index e4f0b9de4..ce29de1d9 100644 --- a/db/routines/vn/procedures/balanceNestTree_move.sql +++ b/db/routines/vn/procedures/balanceNestTree_move.sql @@ -1,14 +1,14 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_move`( vSelf INT, - vSelfFather INT + vFather INT ) BEGIN /** * Mueve un nodo dentro de la estructura de árbol de vn.balanceNestTree. * * @param vSelf Identificador del nodo - * @param vSelfFather Identificador del nuevo padre del nodo + * @param vFather Identificador del nuevo padre del nodo */ DECLARE vTable VARCHAR(45) DEFAULT util.quoteIdentifier('balanceNestTree'); DECLARE vRight INT; @@ -36,7 +36,7 @@ BEGIN SET a.frg = t.rgt, a.flf = t.lft WHERE t.id = ?') - USING vSelfFather; + USING vFather; SELECT wdt, frg, flf INTO vWidth, vFatherRight, vFatherLeft diff --git a/db/routines/vn/procedures/pay.sql b/db/routines/vn/procedures/pay.sql index c868bfb53..2ef9ca2d6 100644 --- a/db/routines/vn/procedures/pay.sql +++ b/db/routines/vn/procedures/pay.sql @@ -4,7 +4,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`pay`( vSupplierFk INT, vAmount DOUBLE, vCurrencyFk INT, - vDivisa DOUBLE, + vForeignValue DOUBLE, vBankFk INT, vPayMethodFk INT, vExpenseFk DOUBLE, @@ -18,7 +18,7 @@ BEGIN * @param vSupplierFk Id del proveedor * @param vAmount Cantidad a pagar * @param vCurrencyFk Id de la moneda - * @param vDivisa Tipo de cambio utilizado + * @param vForeignValue Tipo de cambio utilizado * @param vBankFk Id del banco * @param vPayMethodFk Id del método de pago * @param vExpenseFk Id de gasto @@ -70,7 +70,7 @@ BEGIN vSupplierFk, vAmount, vCurrencyFk, - IF(NOT vDivisa, NULL, vDivisa), + IF(NOT vForeignValue, NULL, vForeignValue), vBankFk, vPayMethodFk, vExpenseFk, From feeb9eece7f68dbf4b209ec3f39f5abcee8994e3 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 29 Feb 2024 08:12:17 +0100 Subject: [PATCH 116/150] feat: refs #6401 Added QR and CIF in the CMR report --- .../reports/cmr/assets/css/style.css | 17 +++- print/templates/reports/cmr/cmr.html | 22 +++++- print/templates/reports/cmr/cmr.js | 77 +++++++++++-------- print/templates/reports/cmr/sql/data.sql | 1 + 4 files changed, 78 insertions(+), 39 deletions(-) diff --git a/print/templates/reports/cmr/assets/css/style.css b/print/templates/reports/cmr/assets/css/style.css index 201afc3b6..8b007b3b0 100644 --- a/print/templates/reports/cmr/assets/css/style.css +++ b/print/templates/reports/cmr/assets/css/style.css @@ -3,7 +3,7 @@ html { margin: 10px; font-size: 22px; } -.mainTable, .specialTable, .categoryTable { +.mainTable, .specialTable, .categoryTable, .observationTable { width: 100%; border-collapse: collapse; font-size: inherit; @@ -98,4 +98,19 @@ img { #merchandiseLabels td { padding-bottom: 11px; max-width: 300px; +} + +.observationTable tr td { + border: none; + padding: 5px; +} + +#qrSection { + text-align: center; + width: 30%; +} + +#truckPlateQr { + width: 125px; + margin-bottom: 10px; } \ No newline at end of file diff --git a/print/templates/reports/cmr/cmr.html b/print/templates/reports/cmr/cmr.html index c6a9e79d6..a8f302086 100644 --- a/print/templates/reports/cmr/cmr.html +++ b/print/templates/reports/cmr/cmr.html @@ -30,8 +30,11 @@ 16. Transportista / Transporteur / Carrier
{{data.carrierName}}
- {{data.carrierStreet}}
- {{data.carrierPostalCode}} {{data.carrierCity}} {{(data.carrierCountry) ? `(${data.carrierCountry})` : null}} + {{data.carrierStreet}} {{data.carrierPostalCode}} + {{data.carrierCity}} {{(data.carrierCountry) + ? `(${data.carrierCountry})` + : null}}
+ CIF: {{data.carrierCif}} @@ -71,8 +74,19 @@ Carrier's reservations and observations
- {{data.truckPlate}}
- {{data.observations}} + + + + + +
+ {{data.observations}} + + +
+ {{data.truckPlate}} +
+ diff --git a/print/templates/reports/cmr/cmr.js b/print/templates/reports/cmr/cmr.js index c939e5152..2ee855ce0 100644 --- a/print/templates/reports/cmr/cmr.js +++ b/print/templates/reports/cmr/cmr.js @@ -2,44 +2,53 @@ const config = require(`vn-print/core/config`); const vnReport = require('../../../core/mixins/vn-report.js'); const md5 = require('md5'); const fs = require('fs-extra'); +const qrcode = require('qrcode'); const prefixBase64 = 'data:image/png;base64,'; module.exports = { - name: 'cmr', - mixins: [vnReport], - async serverPrefetch() { - this.data = await this.findOneFromDef('data', [this.id]); - if (this.data.ticketFk) { - this.merchandises = await this.rawSqlFromDef('merchandise', [this.data.ticketFk]); - this.signature = await this.findOneFromDef('signature', [this.data.ticketFk]); - } else - this.merchandises = null; + name: 'cmr', + mixins: [vnReport], + async serverPrefetch() { + this.data = await this.findOneFromDef('data', [this.id]); + if (this.data.ticketFk) { + this.merchandises = await this.rawSqlFromDef('merchandise', [this.data.ticketFk]); + this.signature = await this.findOneFromDef('signature', [this.data.ticketFk]); + } else + this.merchandises = null; - this.senderStamp = (this.data.senderStamp) - ? `${prefixBase64} ${this.data.senderStamp.toString('base64')}` - : null; - this.deliveryStamp = (this.data.deliveryStamp) - ? `${prefixBase64} ${this.data.deliveryStamp.toString('base64')}` - : null; - }, - props: { - id: { - type: Number, - required: true, - description: 'The cmr id' - }, - }, - computed: { - signPath() { - if (!this.signature) return; + this.senderStamp = (this.data.senderStamp) + ? `${prefixBase64} ${this.data.senderStamp.toString('base64')}` + : null; + this.deliveryStamp = (this.data.deliveryStamp) + ? `${prefixBase64} ${this.data.deliveryStamp.toString('base64')}` + : null; + this.truckPlateQr = await this.getQR(this.data.truckPlate); + }, + props: { + id: { + type: Number, + required: true, + description: 'The cmr id' + }, + }, + computed: { + signPath() { + if (!this.signature) return; - const signatureName = this.signature.signature - const hash = md5(signatureName.toString()).substring(0, 3); - const file = `${config.storage.root}/${hash}/${signatureName}.png`; - if (!fs.existsSync(file)) return null; + const signatureName = this.signature.signature; + const hash = md5(signatureName.toString()).substring(0, 3); + const file = `${config.storage.root}/${hash}/${signatureName}.png`; + if (!fs.existsSync(file)) return null; - return `${prefixBase64} ${Buffer.from(fs.readFileSync(file), 'utf8').toString('base64')}`; - }, - } -}; \ No newline at end of file + return `${prefixBase64} ${Buffer.from(fs.readFileSync(file), 'utf8').toString('base64')}`; + }, + }, + methods: { + getQR(id) { + const data = String(id); + + return qrcode.toDataURL(data, {margin: 0}); + }, + } +}; diff --git a/print/templates/reports/cmr/sql/data.sql b/print/templates/reports/cmr/sql/data.sql index 9708c4483..e9500cc4b 100644 --- a/print/templates/reports/cmr/sql/data.sql +++ b/print/templates/reports/cmr/sql/data.sql @@ -10,6 +10,7 @@ SELECT c.id cmrFk, c.merchandiseDetail, c.ead, s.name carrierName, + s.nif carrierCif, s.street carrierStreet, s.postCode carrierPostCode, s.city carrierCity, From 3736d0708bd99873b34e2d5b5a791b7c9148173c Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 29 Feb 2024 08:16:07 +0100 Subject: [PATCH 117/150] feat: refs #6401 Minor change --- print/templates/reports/cmr/cmr.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/print/templates/reports/cmr/cmr.js b/print/templates/reports/cmr/cmr.js index 2ee855ce0..ef99a08a0 100644 --- a/print/templates/reports/cmr/cmr.js +++ b/print/templates/reports/cmr/cmr.js @@ -46,9 +46,7 @@ module.exports = { }, methods: { getQR(id) { - const data = String(id); - - return qrcode.toDataURL(data, {margin: 0}); + return qrcode.toDataURL(String(id), {margin: 0}); }, } }; From 6e4b4537d368a0acef7ab4306c318a4478c7579c Mon Sep 17 00:00:00 2001 From: pablone Date: Thu, 29 Feb 2024 12:22:04 +0100 Subject: [PATCH 118/150] fix(style): refs #6684 add wordBreak --- .../reports/driver-route/assets/css/style.css | 11 ----------- .../templates/reports/driver-route/driver-route.html | 4 ++-- 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/print/templates/reports/driver-route/assets/css/style.css b/print/templates/reports/driver-route/assets/css/style.css index 101ef7b3f..a3bcae789 100644 --- a/print/templates/reports/driver-route/assets/css/style.css +++ b/print/templates/reports/driver-route/assets/css/style.css @@ -40,17 +40,6 @@ table.repeatable > tbody > tr > td { padding-top: 0.5em; } -section.text-area { - margin-top: 1em; - padding: 0.19em; - padding-left: 1em; - padding-right: 1em; - background-color: #e5e5e5; - & > p { - word-break: break-all; - } -} - .route-block { margin-bottom: 100px; page-break-after: always; diff --git a/print/templates/reports/driver-route/driver-route.html b/print/templates/reports/driver-route/driver-route.html index 1475b8e77..109afd2f5 100644 --- a/print/templates/reports/driver-route/driver-route.html +++ b/print/templates/reports/driver-route/driver-route.html @@ -128,8 +128,8 @@ -
-

{{ticket.description}}

+
+

{{ticket.description}}

From 594780d6cb57b4f0119651a6be3c34907ae37f09 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 29 Feb 2024 13:44:49 +0100 Subject: [PATCH 119/150] feat: refs #6958 delete sale_checkNoComponents --- .../vn/events/sale_checkWithoutComponents.sql | 8 --- .../vn/procedures/sale_checkNoComponents.sql | 70 ------------------- 2 files changed, 78 deletions(-) delete mode 100644 db/routines/vn/events/sale_checkWithoutComponents.sql delete mode 100644 db/routines/vn/procedures/sale_checkNoComponents.sql diff --git a/db/routines/vn/events/sale_checkWithoutComponents.sql b/db/routines/vn/events/sale_checkWithoutComponents.sql deleted file mode 100644 index 2a1ced6ca..000000000 --- a/db/routines/vn/events/sale_checkWithoutComponents.sql +++ /dev/null @@ -1,8 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`sale_checkWithoutComponents` - ON SCHEDULE EVERY 10 MINUTE - STARTS '2020-05-04 11:56:23.000' - ON COMPLETION PRESERVE - ENABLE -DO call sale_checkNoComponents(DATE_ADD(util.VN_NOW(), INTERVAL -10 MINUTE),DATE_ADD(util.VN_NOW(), INTERVAL -1 MINUTE))$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/sale_checkNoComponents.sql b/db/routines/vn/procedures/sale_checkNoComponents.sql deleted file mode 100644 index 79abbbf92..000000000 --- a/db/routines/vn/procedures/sale_checkNoComponents.sql +++ /dev/null @@ -1,70 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_checkNoComponents`(vCreatedFrom DATETIME, vCreatedTo DATETIME) -BEGIN -/** - * Comprueba que las ventas creadas entre un rango de fechas tienen componentes - * - * @param vCreatedFrom inicio del rango - * @param vCreatedTo fin del rango - */ - DECLARE v_done BOOL DEFAULT FALSE; - DECLARE vSaleFk INTEGER; - DECLARE vTicketFk INTEGER; - DECLARE vConcept VARCHAR(50); - DECLARE vCur CURSOR FOR - SELECT s.id - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN item i ON i.id = s.itemFk - JOIN itemType tp ON tp.id = i.typeFk - JOIN itemCategory ic ON ic.id = tp.categoryFk - LEFT JOIN tmp.coste c ON c.id = s.id - WHERE s.created >= vCreatedFrom AND s.created <= vCreatedTo - AND c.id IS NULL - AND t.agencyModeFk IS NOT NULL - AND t.isDeleted IS FALSE - AND t.warehouseFk = 60 - AND ic.merchandise != FALSE - GROUP BY s.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.coste; - - DROP TEMPORARY TABLE IF EXISTS tmp.coste; - CREATE TEMPORARY TABLE tmp.coste - (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT s.id - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemType tp ON tp.id = i.typeFk - JOIN itemCategory ic ON ic.id = tp.categoryFk - JOIN saleComponent sc ON sc.saleFk = s.id - JOIN component c ON c.id = sc.componentFk - JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 6 - WHERE s.created >= vCreatedFrom - AND ic.merchandise != FALSE; - - OPEN vCur; - - l: LOOP - SET v_done = FALSE; - FETCH vCur INTO vSaleFk; - - IF v_done THEN - LEAVE l; - END IF; - - SELECT ticketFk, concept - INTO vTicketFk, vConcept - FROM sale - WHERE id = vSaleFk; - - CALL sale_calculateComponent(vSaleFk, 'renewPrices'); - END LOOP; - - CLOSE vCur; - DROP TEMPORARY TABLE tmp.coste; -END$$ -DELIMITER ; From 625d19e88c90a1c1c971c4c5547b156d80f6d7f6 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 29 Feb 2024 13:44:58 +0100 Subject: [PATCH 120/150] hotfix: Autoincrement warehouse --- db/versions/10922-salmonCordyline/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/10922-salmonCordyline/00-firstScript.sql diff --git a/db/versions/10922-salmonCordyline/00-firstScript.sql b/db/versions/10922-salmonCordyline/00-firstScript.sql new file mode 100644 index 000000000..37557d326 --- /dev/null +++ b/db/versions/10922-salmonCordyline/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.warehouse AUTO_INCREMENT=92; From f4aa5cea915eefc0b8872a41f16a72a660176f31 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 1 Mar 2024 07:32:45 +0100 Subject: [PATCH 121/150] refactor: refs #6499 Grants --- db/versions/10924-pinkCordyline/00-firstScript.sql | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 db/versions/10924-pinkCordyline/00-firstScript.sql diff --git a/db/versions/10924-pinkCordyline/00-firstScript.sql b/db/versions/10924-pinkCordyline/00-firstScript.sql new file mode 100644 index 000000000..ea04623cd --- /dev/null +++ b/db/versions/10924-pinkCordyline/00-firstScript.sql @@ -0,0 +1,4 @@ +GRANT EXECUTE ON PROCEDURE vn.balanceNestTree_addChild TO adminBoss; +GRANT EXECUTE ON PROCEDURE vn.balanceNestTree_delete TO adminBoss; +GRANT EXECUTE ON PROCEDURE vn.balanceNestTree_move TO adminBoss; +GRANT EXECUTE ON PROCEDURE vn.pay TO financial; From 1f9f10323b9b738bb2238412381b25a8b042aeb9 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 1 Mar 2024 11:21:04 +0100 Subject: [PATCH 122/150] refactor: refs #6494 Migrated and deleted residual procs --- .../procedures/confection_controlSource.sql | 112 ++++++++++++++++++ db/routines/vn/procedures/remittance_calc.sql | 70 +++++++++++ .../vn2008/procedures/CalculoRemesas.sql | 66 ----------- db/routines/vn2008/procedures/cacheReset.sql | 11 -- db/routines/vn2008/procedures/camiones.sql | 23 ---- db/routines/vn2008/procedures/cobro.sql | 79 ------------ .../procedures/confection_control_source.sql | 105 ---------------- .../10925-orangeLaurel/00-firstScript.sql | 15 +++ 8 files changed, 197 insertions(+), 284 deletions(-) create mode 100644 db/routines/vn/procedures/confection_controlSource.sql create mode 100644 db/routines/vn/procedures/remittance_calc.sql delete mode 100644 db/routines/vn2008/procedures/CalculoRemesas.sql delete mode 100644 db/routines/vn2008/procedures/cacheReset.sql delete mode 100644 db/routines/vn2008/procedures/camiones.sql delete mode 100644 db/routines/vn2008/procedures/cobro.sql delete mode 100644 db/routines/vn2008/procedures/confection_control_source.sql create mode 100644 db/versions/10925-orangeLaurel/00-firstScript.sql diff --git a/db/routines/vn/procedures/confection_controlSource.sql b/db/routines/vn/procedures/confection_controlSource.sql new file mode 100644 index 000000000..6cd43036f --- /dev/null +++ b/db/routines/vn/procedures/confection_controlSource.sql @@ -0,0 +1,112 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`confection_controlSource`( + vDated DATE, + vScopeDays INT, + vMaxAlertLevel INT, + vWarehouseFk INT +) +BEGIN +/** + * Obtiene la información para el control de confección, + * ya sean tickets y/o entradas. + * + * @param vDated Fecha a calcular + * @param vScopeDays Número de días desde hoy en adelante que entran en el cálculo. + * @param vMaxAlertLevel Id nivel de alerta + * @param vWarehouseFk Id de almacén + */ + DECLARE vMidnight DATETIME DEFAULT util.dayEnd(vDated); + DECLARE vEndingDate DATETIME DEFAULT vMidnight + INTERVAL vScopeDays DAY; + + CREATE OR REPLACE TEMPORARY TABLE tConfectionControlSource + ENGINE = MEMORY + SELECT t.shipped, + t.id ticketFk, + s.id saleFk, + s.quantity, + s.concept, + ABS(s.reserved) isReserved, + i.category, + it.name itemType, + t.nickname, + wh.name warehouse, + t.warehouseFk warehouseFk, + a.provinceFk, + am.agencyFk, + ct.description, + stock.visible, + stock.available + FROM ticket t + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN warehouse wh ON wh.id = t.warehouseFk + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN confectionType ct ON ct.id = it.making + JOIN `address` a on a.id = t.addressFk + LEFT JOIN ticketState tls on tls.ticketFk = t.id + LEFT JOIN + ( + SELECT item_id, + SUM(visible) visible, + SUM(available) available + FROM ( + SELECT a.item_id, + 0 visible, + a.available + FROM cache.cache_calc cc + LEFT JOIN cache.available a ON a.calc_id = cc.id + WHERE cc.cache_id IN ('visible', 'available') + AND cc.params = CONCAT(vWarehouseFk, "/", util.VN_CURDATE()) + UNION ALL + SELECT v.item_id, + v.visible, + 0 + FROM cache.cache_calc cc + LEFT JOIN cache.visible v ON v.calc_id = cc.id + WHERE cc.cacheName IN ('visible', 'available') + AND cc.params = vWarehouseFk + ) sub + GROUP BY item_id + ) stock ON stock.item_id = s.itemFk + WHERE it.making + AND tls.alertLevel < vMaxAlertLevel + AND wh.hasConfectionTeam + AND t.shipped BETWEEN vDated AND vEndingDate + AND s.quantity > 0; + + -- Entradas + INSERT INTO tConfectionControlSource( + shipped, + ticketFk, + quantity, + concept, + category, + nickname, + warehouse, + description + ) + SELECT tr.shipped, + e.id, + b.quantity, + i.name, + i.category, + whi.name, + who.name, + ct.description + FROM buy b + JOIN `entry` e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + JOIN warehouse whi ON whi.id = tr.warehouseInFk + JOIN warehouse who ON who.id = tr.warehouseOutFk + JOIN item i ON i.id = b.itemFk + JOIN itemType it ON it.id = i.typeFk + JOIN confectionType ct ON ct.id = it.making + WHERE who.hasConfectionTeam + AND it.making + AND tr.shipped BETWEEN vDated AND vEndingDate; + + SELECT * FROM tConfectionControlSource; + DROP TEMPORARY TABLE tConfectionControlSource; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/remittance_calc.sql b/db/routines/vn/procedures/remittance_calc.sql new file mode 100644 index 000000000..ed0a18662 --- /dev/null +++ b/db/routines/vn/procedures/remittance_calc.sql @@ -0,0 +1,70 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`remittance_calc`( + vDated DATE +) +BEGIN +/** +* Calcula los datos de remesa, incluyendo el importe, +* el vencimiento, y otros datos relevantes. +* +* @param vDated Fecha a calcular +* @return tmp.remittance +*/ + CREATE OR REPLACE TEMPORARY TABLE tmp.remittance + SELECT CONCAT(s.nif, REPEAT('0', 12 - LENGTH(s.nif))) cif, + c.id clientFk, + c.name client, + c.fi, + sub.paymentDate, + 0 invoiceAmount, + CAST(sub.receipt AS DECIMAL(10,2)) receiptAmount, + 0 currentAmount, + sub.companyFk, + c.socialName, + CAST(sub.receipt AS DECIMAL(10,2)) totalAmount, + CAST(sub.receipt AS DECIMAL(10,2)) balance, + s.name company, + co.code companyCode, + c.accountingAccount, + c.iban, + c.hasSepaVnl, + c.hasCoreVnl, + c.hasLcr, + be.bic, + be.`name` entityName + FROM client c + JOIN ( + SELECT risk.companyFk, + c.id, + SUM(risk.amount) receipt, + IF((c.dueDay + graceDays) MOD 30.001 <= DAY(vDated), + LAST_DAY(vDated - INTERVAL 1 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY, + LAST_DAY(vDated - INTERVAL 2 MONTH) + INTERVAL (c.dueDay + graceDays) MOD 30.001 DAY + ) paymentDate + FROM client c + JOIN payMethod pm ON pm.id = c.payMethodFk + JOIN ( + SELECT cr.companyFk, cr.clientFk, cr.amount + FROM client c + JOIN clientRisk cr ON cr.clientFk = c.id + JOIN payMethod pm ON pm.id = c.payMethodFk + WHERE pm.code = 'bankDraft' + UNION ALL + SELECT io.companyFk, io.clientFk, - io.amount + FROM invoiceOut io + JOIN client c ON c.id = io.clientFk + JOIN payMethod pm ON pm.id = c.payMethodFk + WHERE io.dued > vDated + AND pm.code = 'bankDraft' + AND pm.outstandingDebt + AND io.amount > 0 + + ) risk ON risk.clientFk = c.id + GROUP BY risk.companyFk, c.id + HAVING receipt > 10 + ) sub ON sub.id = c.id + JOIN supplier s ON s.id = sub.companyFk + JOIN company co ON co.id = sub.companyFk + LEFT JOIN bankEntity be ON be.id = c.bankEntityFk; +END$$ +DELIMITER ; diff --git a/db/routines/vn2008/procedures/CalculoRemesas.sql b/db/routines/vn2008/procedures/CalculoRemesas.sql deleted file mode 100644 index a4c191a80..000000000 --- a/db/routines/vn2008/procedures/CalculoRemesas.sql +++ /dev/null @@ -1,66 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`CalculoRemesas`(IN vFechaRemesa DATE) -BEGIN - - DROP TEMPORARY TABLE IF EXISTS TMP_REMESAS; - CREATE TEMPORARY TABLE TMP_REMESAS - SELECT - CONCAT(p.NIF,REPEAT('0', 12-LENGTH(p.NIF))) as CIF1, - cli.Id_Cliente, - cli.Cliente, - cli.`IF` as NIF, - c.PaymentDate as Vencimiento, - 0 ImporteFac, - cast(c.Recibo as decimal(10,2)) as ImporteRec, - 0 as ImporteActual, - c.companyFk empresa_id, - cli.RazonSocial, - cast(c.Recibo as decimal(10,2)) as ImporteTotal, - cast(c.Recibo as decimal(10,2)) as Saldo, - p.Proveedor as Empresa, - e.abbreviation as EMP, - cli.cuenta, - iban AS Iban, - CONVERT(SUBSTRING(iban,5,4),UNSIGNED INT) AS nrbe, - sepavnl as SEPA, - corevnl as RecibidoCORE, - hasLcr, - be.bic, - be.`name` entityName - FROM Clientes cli - JOIN - (SELECT risk.companyFk, - c.Id_Cliente, - sum(risk.amount) as Recibo, - IF((c.Vencimiento + graceDays) mod 30.001 <= day(vFechaRemesa) - ,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-1,vFechaRemesa))) - ,TIMESTAMPADD(DAY, (c.Vencimiento + graceDays) MOD 30.001, LAST_DAY(TIMESTAMPADD(MONTH,-2,vFechaRemesa))) - ) as PaymentDate - FROM Clientes c - JOIN pay_met pm on pm.id = pay_met_id - JOIN - ( - SELECT companyFk, clientFk, amount - FROM Clientes c - JOIN vn.clientRisk cr ON cr.clientFk = c.Id_Cliente - WHERE pay_met_id = 4 - - UNION ALL - - SELECT io.companyFk, io.clientFk Id_Cliente, - io.amount - FROM vn.invoiceOut io - JOIN Clientes c ON c.Id_Cliente = io.clientFk - JOIN pay_met pm on pm.id = pay_met_id - WHERE io.dued > vFechaRemesa - AND pay_met_id = 4 AND pm.deudaviva - AND io.amount > 0 - - ) risk ON c.Id_Cliente = risk.clientFk - GROUP BY risk.companyFk, Id_Cliente - HAVING Recibo > 10 - ) c on c.Id_Cliente = cli.Id_Cliente - JOIN Proveedores p on p.Id_Proveedor = c.companyFk - JOIN empresa e on e.id = c.companyFk - LEFT JOIN vn.bankEntity be ON be.id = cli.bankEntityFk; -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/procedures/cacheReset.sql b/db/routines/vn2008/procedures/cacheReset.sql deleted file mode 100644 index f36169fda..000000000 --- a/db/routines/vn2008/procedures/cacheReset.sql +++ /dev/null @@ -1,11 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`cacheReset`(vCacheName VARCHAR(10), vParams VARCHAR(15)) -BEGIN - - UPDATE cache.cache_calc - SET expires = util.VN_NOW() - WHERE cacheName = vCacheName collate utf8_unicode_ci - AND params = vParams collate utf8_unicode_ci; - -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/procedures/camiones.sql b/db/routines/vn2008/procedures/camiones.sql deleted file mode 100644 index 4c37cf9da..000000000 --- a/db/routines/vn2008/procedures/camiones.sql +++ /dev/null @@ -1,23 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`camiones`(vWarehouse INT, vDate DATE) -BEGIN - SELECT Temperatura - ,ROUND(SUM(Etiquetas * volume)) AS cm3 - ,ROUND(SUM(IF(scanned, Etiquetas, 0) * volume)) AS cm3s - ,ROUND(SUM(Vida * volume)) AS cm3e - FROM ( - SELECT t.Temperatura, c.Etiquetas, b.scanned, c.Vida, - IF(cu.Volumen > 0, cu.Volumen, cu.x * cu.y * IF(cu.z > 0, cu.z, a.Medida + 10)) volume - FROM Compres c - LEFT JOIN buy_edi b ON b.id = c.buy_edi_id - JOIN Articles a ON a.Id_Article = c.Id_Article - JOIN Tipos t ON t.tipo_id = a.tipo_id - JOIN Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN travel tr ON tr.id = e.travel_id - JOIN Cubos cu ON cu.Id_Cubo = c.Id_Cubo - WHERE tr.warehouse_id = vWarehouse - AND tr.landing = vDate - ) sub - GROUP BY Temperatura; -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/procedures/cobro.sql b/db/routines/vn2008/procedures/cobro.sql deleted file mode 100644 index 26d906813..000000000 --- a/db/routines/vn2008/procedures/cobro.sql +++ /dev/null @@ -1,79 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`cobro`(IN datFEC DATE - , IN idCLI INT - , IN dblIMPORTE DOUBLE - , IN idCAJA INT - , IN idPAYMET INT - , IN strCONCEPTO VARCHAR(40) - , IN idEMP INT - , IN idWH INT - , IN idTRABAJADOR INT) -BEGIN - - DECLARE bolCASH BOOLEAN; - DECLARE cuenta_banco BIGINT; - DECLARE cuenta_cliente BIGINT; - DECLARE max_asien INT; - -- XDIARIO - -- No se asientan los cobros directamente, salvo en el caso de las cajas de CASH - SELECT (at2.code = 'cash') INTO bolCASH FROM Bancos b JOIN vn.accountingType at2 ON at2.id = b.cash WHERE b.Id_Banco = idCAJA; - IF bolCASH THEN - SELECT Cuenta INTO cuenta_banco - FROM Bancos - WHERE Id_Banco = idCAJA; - SELECT Cuenta INTO cuenta_cliente - FROM Clientes - WHERE Id_Cliente = idCLI; - CALL vn.ledger_next(max_asien); - INSERT INTO vn.XDiario (ASIEN,FECHA,SUBCTA,CONTRA,CONCEPTO,EURODEBE,EUROHABER,empresa_id) - SELECT max_asien,datFEC,SUBCTA,CONTRA,strCONCEPTO,EURODEBE,EUROHABER,idEMP - FROM(SELECT cuenta_banco SUBCTA, cuenta_cliente CONTRA, 0 EURODEBE, dblIMPORTE EUROHABER - UNION ALL - SELECT cuenta_cliente SUBCTA, cuenta_banco CONTRA, dblIMPORTE EURODEBE, 0 EUROHABER - ) gf; - END IF; - - -- CAJERA - INSERT INTO Cajas(Id_Trabajador, - Id_Banco, - Entrada, - Concepto, - Cajafecha, - Serie, - Partida, - Numero, - empresa_id, - warehouse_id - ) - VALUES (idTRABAJADOR, - idCAJA, - dblIMPORTE, - strCONCEPTO, - datFEC, - 'A', - TRUE, - idCLI, - idEMP, - idWH - ); - - -- RECIBO - INSERT INTO Recibos(Entregado, - Fechacobro, - Id_Trabajador, - Id_Banco, - Id_Cliente, - Id_Factura, - empresa_id - ) - VALUES ( dblIMPORTE, - datFEC, - idTRABAJADOR, - idCAJA, - idCLI, - strCONCEPTO, - idEMP - ); - -END$$ -DELIMITER ; diff --git a/db/routines/vn2008/procedures/confection_control_source.sql b/db/routines/vn2008/procedures/confection_control_source.sql deleted file mode 100644 index 77b4df5f3..000000000 --- a/db/routines/vn2008/procedures/confection_control_source.sql +++ /dev/null @@ -1,105 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn2008`.`confection_control_source`(vDated DATE, vScopeDays TINYINT) -BEGIN - - DECLARE vMidnight DATETIME DEFAULT TIMESTAMP(vDated,'23:59:59'); - DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,vMidnight); - DECLARE maxAlertLevel INT DEFAULT 2; - - DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; - - CREATE TEMPORARY TABLE tmp.production_buffer - ENGINE = MEMORY - SELECT - date(t.Fecha) as Fecha, - hour(t.Fecha) as Hora, - hour(t.Fecha) as Departure, - t.Id_Ticket, - m.Id_Movimiento, - m.Cantidad, - m.Concepte, - ABS(m.Reservado) Reservado, - i.Categoria, - tp.Tipo, - t.Alias as Cliente, - wh.name as Almacen, - t.warehouse_id, - cs.province_id, - a.agency_id, - ct.description as Taller, - stock.visible, - stock.available - FROM vn2008.Tickets t - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - JOIN vn.warehouse wh ON wh.id = t.warehouse_id - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles i ON i.Id_Article = m.Id_Article - JOIN vn2008.Tipos tp ON tp.tipo_id = i.tipo_id - JOIN vn.confectionType ct ON ct.id = tp.confeccion - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - LEFT JOIN vn.ticketState tls on tls.ticketFk = t.Id_Ticket - LEFT JOIN - ( - SELECT item_id, sum(visible) visible, sum(available) available - FROM - ( - SELECT a.item_id, 0 as visible, a.available - FROM cache.cache_calc cc - LEFT JOIN cache.available a ON a.calc_id = cc.id - WHERE cc.cache_id IN (2,8) - AND cc.params IN (concat("1/", util.VN_CURDATE()),concat("44/", util.VN_CURDATE())) - - UNION ALL - - SELECT v.item_id, v.visible, 0 as available - FROM cache.cache_calc cc - LEFT JOIN cache.visible v ON v.calc_id = cc.id - where cc.cache_id IN (2,8) and cc.params IN ("1","44") - ) sub - GROUP BY item_id - ) stock ON stock.item_id = m.Id_Article - WHERE tp.confeccion - AND tls.alertLevel < maxAlertLevel - AND wh.hasConfectionTeam - AND t.Fecha BETWEEN vDated AND vEndingDate - AND m.Cantidad > 0; - - -- Entradas - - INSERT INTO tmp.production_buffer( - Fecha, - Id_Ticket, - Cantidad, - Concepte, - Categoria, - Cliente, - Almacen, - Taller - ) - SELECT - tr.shipment AS Fecha, - e.Id_Entrada AS Id_Ticket, - c.Cantidad, - a.Article, - a.Categoria, - whi.name as Cliente, - who.name as Almacen, - ct.description as Taller - FROM vn2008.Compres c - JOIN vn2008.Entradas e ON e.Id_Entrada = c.Id_Entrada - JOIN vn2008.travel tr ON tr.id = e.travel_id - JOIN vn.warehouse whi ON whi.id = tr.warehouse_id - JOIN vn.warehouse who ON who.id = tr.warehouse_id_out - JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article - JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id - JOIN vn.confectionType ct ON ct.id = tp.confeccion - WHERE who.hasConfectionTeam - AND tp.confeccion - AND tr.shipment BETWEEN vDated AND vEndingDate; - - - SELECT * FROM tmp.production_buffer; - - -END$$ -DELIMITER ; diff --git a/db/versions/10925-orangeLaurel/00-firstScript.sql b/db/versions/10925-orangeLaurel/00-firstScript.sql new file mode 100644 index 000000000..049627082 --- /dev/null +++ b/db/versions/10925-orangeLaurel/00-firstScript.sql @@ -0,0 +1,15 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`confection_controlSource`() +BEGIN + SELECT 1; +END$$ +DELIMITER ; +GRANT EXECUTE ON PROCEDURE vn.confection_controlSource TO handmadeBoss, productionAssi, artificialBoss; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`remittance_calc`() +BEGIN + SELECT 1; +END$$ +DELIMITER ; +GRANT EXECUTE ON PROCEDURE vn.remittance_calc TO financial; \ No newline at end of file From 97f76c64ffd99b0abfbbdb15b8b693196e65cc3a Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 1 Mar 2024 13:35:07 +0100 Subject: [PATCH 123/150] refactor: refs #6276 drop sendRocket method --- back/methods/collection/getSales.js | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index cf0496600..a5e7aeefa 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -58,24 +58,22 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); - if (tickets.length) await sendRocketTickets(tickets, $t); - - return getCollection(id, tickets, sales, placements, myOptions); - }; - async function sendRocketTickets(tickets, $t) { for (let ticket of tickets) { let observations = ticket.observaciones.split(' '); for (let observation of observations) { const salesPerson = ticket.salesPersonFk; - if (!observation.startsWith('#') && !observation.startsWith('@')) return; - await models.Chat.send(ctx, - observation, - $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) - ); + if (observation.startsWith('#') || observation.startsWith('@')) { + await models.Chat.send(ctx, + observation, + $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) + ); + } } } - } + + return getCollection(id, tickets, sales, placements, myOptions); + }; async function getCollection(id, tickets, sales, placements, options) { const collection = { From a3052c1cf98c325ceee9d2437e3d3bdc6f3ee398 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 1 Mar 2024 15:05:12 +0100 Subject: [PATCH 124/150] refs #6925 hotFix(invoice) parenthesis & handle incoterms error --- db/routines/vn/procedures/ticket_closeByTicket.sql | 2 +- loopback/locale/es.json | 5 +++-- .../reports/invoice-incoterms/invoice-incoterms.js | 6 +++++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/db/routines/vn/procedures/ticket_closeByTicket.sql b/db/routines/vn/procedures/ticket_closeByTicket.sql index 93772225b..6e32a3e76 100644 --- a/db/routines/vn/procedures/ticket_closeByTicket.sql +++ b/db/routines/vn/procedures/ticket_closeByTicket.sql @@ -15,7 +15,7 @@ BEGIN JOIN agencyMode am ON am.id = t.agencyModeFk LEFT JOIN ticketState ts ON ts.ticketFk = t.id JOIN alertLevel al ON al.id = ts.alertLevel - WHERE al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered') + WHERE (al.code = 'PACKED' OR (am.code = 'refund' AND al.code != 'delivered')) AND t.id = vTicketFk AND t.refFk IS NULL GROUP BY t.id); diff --git a/loopback/locale/es.json b/loopback/locale/es.json index b14358e85..49283e633 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -344,5 +344,6 @@ "CountryFK cannot be empty": "El país no puede estar vacío", "Cmr file does not exist": "El archivo del cmr no existe", "You are not allowed to modify the alias": "No estás autorizado a modificar el alias", - "No tickets to invoice": "No hay tickets para facturar" -} \ No newline at end of file + "No tickets to invoice": "No hay tickets para facturar", + "The address of the customer must have information about Incoterms and Customs Agent": "El consignatario del cliente debe tener informado Incoterms y Agente de aduanas" +} diff --git a/print/templates/reports/invoice-incoterms/invoice-incoterms.js b/print/templates/reports/invoice-incoterms/invoice-incoterms.js index 9cc2600af..cfe29169b 100755 --- a/print/templates/reports/invoice-incoterms/invoice-incoterms.js +++ b/print/templates/reports/invoice-incoterms/invoice-incoterms.js @@ -1,4 +1,5 @@ const vnReport = require('../../../core/mixins/vn-report.js'); +const UserError = require('vn-loopback/util/user-error'); module.exports = { name: 'invoice-incoterms', @@ -7,7 +8,10 @@ module.exports = { this.invoice = await this.findOneFromDef('invoice', [this.reference]); this.checkMainEntity(this.invoice); this.client = await this.findOneFromDef('client', [this.reference]); - this.incoterms = await this.findOneFromDef('incoterms', [this.reference, this.reference, this.reference, this.reference]); + this.incoterms = + await this.findOneFromDef('incoterms', [this.reference, this.reference, this.reference, this.reference]); + if (!this.incoterms) + throw new UserError(`The address of the customer must have information about Incoterms and Customs Agent`); }, props: { reference: { From 28dbb200fcb51350b641c4e462cfd6ece24549fc Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 4 Mar 2024 08:38:24 +0100 Subject: [PATCH 125/150] refactor: refs #6874 Proc itemProposal --- db/routines/vn/procedures/itemProposal.sql | 97 ++++++++++++++-------- 1 file changed, 63 insertions(+), 34 deletions(-) diff --git a/db/routines/vn/procedures/itemProposal.sql b/db/routines/vn/procedures/itemProposal.sql index 74d356d77..cc58715ad 100644 --- a/db/routines/vn/procedures/itemProposal.sql +++ b/db/routines/vn/procedures/itemProposal.sql @@ -1,19 +1,23 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemProposal`(vItemFk INT, vTicketFk INT,vShowType BOOL) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemProposal`( + vItemFk INT, + vTicketFk INT, + vShowType BOOL +) BEGIN - /** - * Propone articulos disponible ordenado, con la cantidad de veces usado y segun sus caracteristicas - * - * @param vItemFk item id - * @param vTicketFk ticket id - * @param vShowType mostrar tipos - */ - +* Propone articulos disponibles ordenados, con la cantidad +* de veces usado y segun sus caracteristicas. +* +* @param vItemFk Id de artículo +* @param vTicketFk Id de ticket +* @param vShowType Mostrar tipos +*/ DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vCalcFk INT; DECLARE vTypeFk INT; + DECLARE vPriority INT DEFAULT 1; DECLARE vTag1 VARCHAR(25); DECLARE vTag5 VARCHAR(25); @@ -27,15 +31,37 @@ BEGIN DECLARE vValue7 VARCHAR(50); DECLARE vValue8 VARCHAR(50); - SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped - FROM vn.ticket + SELECT warehouseFk, shipped + INTO vWarehouseFk, vShipped + FROM ticket WHERE id = vTicketFk; - SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value - INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 - FROM vn.item i - LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk + SELECT typeFk, + tag5, + value5, + tag6, + value6, + tag7, + value7, + tag8, + value8, + t.name, + it.value + INTO vTypeFk, + vTag5, + vValue5, + vTag6, + vValue6, + vTag7, + vValue7, + vTag8, + vValue8, + vTag1, + vValue1 + FROM item i + LEFT JOIN itemTag it ON it.itemFk = i.id + AND it.priority = vPriority + LEFT JOIN tag t ON t.id = it.tagFk WHERE i.id = vItemFk; CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); @@ -56,32 +82,35 @@ BEGIN i.value8, (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, a.available, - IFNULL(ip.counter,0) counter, - IF(b.groupingMode = 1, b.grouping, b.packing) as minQuantity, + IFNULL(ip.counter, 0) `counter`, + IF(b.groupingMode = 1, b.grouping, b.packing) minQuantity, iss.visible located FROM item i JOIN cache.available a ON a.item_id = i.id - LEFT JOIN itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk - LEFT JOIN itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN tag t1 ON t1.id = it1.tagFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk + LEFT JOIN itemProposal ip ON ip.mateFk = i.id + AND ip.itemFk = vItemFk + LEFT JOIN itemTag it ON it.itemFk = i.id + AND it.priority = vPriority + LEFT JOIN tag t ON t.id = it.tagFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + AND lb.warehouse_id = vWarehouseFk LEFT JOIN buy b ON b.id = lb.buy_id - LEFT JOIN itemShelvingStock iss ON iss.itemFk = i.id AND iss.warehouseFk = vWarehouseFk + LEFT JOIN itemShelvingStock iss ON iss.itemFk = i.id + AND iss.warehouseFk = vWarehouseFk WHERE a.calc_id = vCalcFk - AND available > 0 - AND IF(vShowType,i.typeFk = vTypeFk,true) - AND i.id != vItemFk - ORDER BY counter DESC, - (t1.name = vTag1 COLLATE utf8_general_ci) DESC, - (it1.value = vValue1 COLLATE utf8_general_ci) DESC, + AND a.available > 0 + AND IF(vShowType, i.typeFk = vTypeFk, TRUE) + AND i.id <> vItemFk + ORDER BY `counter` DESC, + (t.name = vTag1 COLLATE utf8_general_ci) DESC, + (it.value = vValue1 COLLATE utf8_general_ci) DESC, (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, - (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, + match5 DESC, (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, - (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, + match6 DESC, (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, - (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, + match7 DESC, (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, - (i.value8 = vValue8 COLLATE utf8_general_ci) DESC; - + match8 DESC; END$$ DELIMITER ; From bd5d88f5ef1a6163c9a289caa904f56db7c88eaa Mon Sep 17 00:00:00 2001 From: ivanm Date: Mon, 4 Mar 2024 08:41:09 +0100 Subject: [PATCH 126/150] refs #6969 Error packaging --- db/routines/vn/procedures/buyUltimateFromInterval.sql | 1 - 1 file changed, 1 deletion(-) diff --git a/db/routines/vn/procedures/buyUltimateFromInterval.sql b/db/routines/vn/procedures/buyUltimateFromInterval.sql index 92434a47b..f78174482 100644 --- a/db/routines/vn/procedures/buyUltimateFromInterval.sql +++ b/db/routines/vn/procedures/buyUltimateFromInterval.sql @@ -39,7 +39,6 @@ BEGIN WHERE t.landed BETWEEN vStarted AND vEnded AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND b.price2 > 0 - AND b.quantity > 0 ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC LIMIT 10000000000000000000) sub GROUP BY itemFk, warehouseFk; From 854a9b62af94160de9933c74e7d21a54407aa6cf Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 4 Mar 2024 09:21:41 +0100 Subject: [PATCH 127/150] fix: refs #6276 refactor updateInTime & changes --- back/methods/machine-worker/updateInTime.js | 10 +++++----- modules/item/back/methods/item-barcode/delete.js | 2 +- .../item/back/methods/item-shelving/getAlternative.js | 4 ++-- .../methods/item-shelving/specs/getAlternative.spec.js | 2 +- modules/ticket/back/methods/sale-tracking/setPicked.js | 6 +++--- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/back/methods/machine-worker/updateInTime.js b/back/methods/machine-worker/updateInTime.js index cfeda4425..8f663302d 100644 --- a/back/methods/machine-worker/updateInTime.js +++ b/back/methods/machine-worker/updateInTime.js @@ -47,9 +47,10 @@ module.exports = Self => { } }, myOptions); + const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); + const hoursDifference = (Date.vnNow() - machineWorker.inTime.getTime()) / (60 * 60 * 1000); + if (machineWorker) { - const {maxHours} = await models.MachineWorkerConfig.findOne({fields: ['maxHours']}, myOptions); - const hoursDifference = (Date.vnNow() - machineWorker.inTime.getTime()) / (60 * 60 * 1000); const isHimself = userId == machineWorker.workerFk; const isSameMachine = machine.id == machineWorker.machineFk; @@ -62,10 +63,9 @@ module.exports = Self => { await machineWorker.updateAttributes({ outTime: Date.vnNew() }, myOptions); + } - if (hoursDifference >= maxHours) - await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); - } else + if (!machineWorker || hoursDifference >= maxHours) await models.MachineWorker.create({machineFk: machine.id, workerFk: userId}, myOptions); if (tx) await tx.commit(); diff --git a/modules/item/back/methods/item-barcode/delete.js b/modules/item/back/methods/item-barcode/delete.js index b27782b1b..0eea651d3 100644 --- a/modules/item/back/methods/item-barcode/delete.js +++ b/modules/item/back/methods/item-barcode/delete.js @@ -1,7 +1,7 @@ module.exports = Self => { Self.remoteMethod('delete', { description: 'Delete an ItemBarcode by itemFk and code', - accessType: 'READ', + accessType: 'WRITE', accepts: [ { arg: 'barcode', diff --git a/modules/item/back/methods/item-shelving/getAlternative.js b/modules/item/back/methods/item-shelving/getAlternative.js index dd497d580..8108bfa6e 100644 --- a/modules/item/back/methods/item-shelving/getAlternative.js +++ b/modules/item/back/methods/item-shelving/getAlternative.js @@ -47,7 +47,7 @@ module.exports = Self => { return itemShelvings.map(itemShelving => { const item = itemShelving.item(); - const carros = alternatives.filter(alternative => alternative.itemFk == itemShelving.itemFk); + const shelvings = alternatives.filter(alternative => alternative.itemFk == itemShelving.itemFk); return { id: itemShelving.id, @@ -56,7 +56,7 @@ module.exports = Self => { size: item.size, longName: item.longName, quantity: itemShelving.visible, - carros + shelvings }; }); } diff --git a/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js index 8c8d8a33d..3f4917477 100644 --- a/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js @@ -13,7 +13,7 @@ describe('itemShelving getAlternative()', () => { const shelvingFk = 'HEJ'; const itemShelvings = await models.ItemShelving.getAlternative(shelvingFk); - expect(itemShelvings[0].carros.length).toEqual(0); + expect(itemShelvings[0].shelvings.length).toEqual(0); }); it('should return an empty list', async() => { diff --git a/modules/ticket/back/methods/sale-tracking/setPicked.js b/modules/ticket/back/methods/sale-tracking/setPicked.js index 990768197..828f6eb7e 100644 --- a/modules/ticket/back/methods/sale-tracking/setPicked.js +++ b/modules/ticket/back/methods/sale-tracking/setPicked.js @@ -73,7 +73,7 @@ module.exports = Self => { userFk: userId }, myOptions); - const itemShelving = await models.ItemShelving.findById(itemShelvingFk, myOptions); + const itemShelving = await models.ItemShelving.findById(itemShelvingFk, null, myOptions); await itemShelving.updateAttributes({visible: itemShelving.visible - quantity}, myOptions); @@ -86,8 +86,8 @@ module.exports = Self => { await Self.updateTracking(ctx, saleFk, originalQuantity, code, isChecked, null, isScanned, myOptions); try { - const buy = await models.Buy.findById(buyFk, myOptions); - if (buy.itemOriginalFk) await models.SaleBuy.create({saleFk, buyFk}, myOptions); + const {itemOriginalFk} = await models.Buy.findById(buyFk, {fields: ['itemOriginalFk']}, myOptions); + if (itemOriginalFk) await models.SaleBuy.create({saleFk, buyFk}, myOptions); } catch (e) { throw new UserError('The sale cannot be tracked'); } From 9cff06ae3d9718417996bad6238c208f5a08376a Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 4 Mar 2024 09:30:07 +0100 Subject: [PATCH 128/150] feat: refs #6276 acl itemBarcode delete --- db/versions/10832-purpleAralia/00-newWareHouse.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/versions/10832-purpleAralia/00-newWareHouse.sql b/db/versions/10832-purpleAralia/00-newWareHouse.sql index 448c69322..dd2c16bdb 100644 --- a/db/versions/10832-purpleAralia/00-newWareHouse.sql +++ b/db/versions/10832-purpleAralia/00-newWareHouse.sql @@ -8,4 +8,5 @@ INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalTyp ('SaleTracking','updateTracking','WRITE','ALLOW','ROLE','production'), ('SaleTracking','setPicked','WRITE','ALLOW','ROLE','production'), ('ExpeditionPallet', '*', 'READ', 'ALLOW', 'ROLE', 'production'), - ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file + ('Sale', 'getFromSectorCollection', 'READ', 'ALLOW', 'ROLE', 'production'), + ('ItemBarcode', 'delete', 'WRITE', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file From cf810fe4977e42d0de9a46334132eecb9d623e9f Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 4 Mar 2024 13:14:41 +0100 Subject: [PATCH 129/150] refactor: refs #6874 Proc itemProposal --- db/routines/vn/procedures/itemProposal.sql | 116 ------------- .../vn/procedures/itemProposal_beta.sql | 76 -------- db/routines/vn/procedures/item_getSimilar.sql | 162 +++++++++++------- 3 files changed, 97 insertions(+), 257 deletions(-) delete mode 100644 db/routines/vn/procedures/itemProposal.sql delete mode 100644 db/routines/vn/procedures/itemProposal_beta.sql diff --git a/db/routines/vn/procedures/itemProposal.sql b/db/routines/vn/procedures/itemProposal.sql deleted file mode 100644 index cc58715ad..000000000 --- a/db/routines/vn/procedures/itemProposal.sql +++ /dev/null @@ -1,116 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemProposal`( - vItemFk INT, - vTicketFk INT, - vShowType BOOL -) -BEGIN -/** -* Propone articulos disponibles ordenados, con la cantidad -* de veces usado y segun sus caracteristicas. -* -* @param vItemFk Id de artículo -* @param vTicketFk Id de ticket -* @param vShowType Mostrar tipos -*/ - DECLARE vWarehouseFk INT; - DECLARE vShipped DATE; - DECLARE vCalcFk INT; - DECLARE vTypeFk INT; - DECLARE vPriority INT DEFAULT 1; - - DECLARE vTag1 VARCHAR(25); - DECLARE vTag5 VARCHAR(25); - DECLARE vTag6 VARCHAR(25); - DECLARE vTag7 VARCHAR(25); - DECLARE vTag8 VARCHAR(25); - - DECLARE vValue1 VARCHAR(50); - DECLARE vValue5 VARCHAR(50); - DECLARE vValue6 VARCHAR(50); - DECLARE vValue7 VARCHAR(50); - DECLARE vValue8 VARCHAR(50); - - SELECT warehouseFk, shipped - INTO vWarehouseFk, vShipped - FROM ticket - WHERE id = vTicketFk; - - SELECT typeFk, - tag5, - value5, - tag6, - value6, - tag7, - value7, - tag8, - value8, - t.name, - it.value - INTO vTypeFk, - vTag5, - vValue5, - vTag6, - vValue6, - vTag7, - vValue7, - vTag8, - vValue8, - vTag1, - vValue1 - FROM item i - LEFT JOIN itemTag it ON it.itemFk = i.id - AND it.priority = vPriority - LEFT JOIN tag t ON t.id = it.tagFk - WHERE i.id = vItemFk; - - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - - SELECT i.id itemFk, - i.longName, - i.subName, - i.tag5, - i.value5, - (i.value5 <=> vValue5 COLLATE utf8_general_ci) match5, - i.tag6, - i.value6, - (i.value6 <=> vValue6 COLLATE utf8_general_ci) match6, - i.tag7, - i.value7, - (i.value7 <=> vValue7 COLLATE utf8_general_ci) match7, - i.tag8, - i.value8, - (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, - a.available, - IFNULL(ip.counter, 0) `counter`, - IF(b.groupingMode = 1, b.grouping, b.packing) minQuantity, - iss.visible located - FROM item i - JOIN cache.available a ON a.item_id = i.id - LEFT JOIN itemProposal ip ON ip.mateFk = i.id - AND ip.itemFk = vItemFk - LEFT JOIN itemTag it ON it.itemFk = i.id - AND it.priority = vPriority - LEFT JOIN tag t ON t.id = it.tagFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - AND lb.warehouse_id = vWarehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id - LEFT JOIN itemShelvingStock iss ON iss.itemFk = i.id - AND iss.warehouseFk = vWarehouseFk - WHERE a.calc_id = vCalcFk - AND a.available > 0 - AND IF(vShowType, i.typeFk = vTypeFk, TRUE) - AND i.id <> vItemFk - ORDER BY `counter` DESC, - (t.name = vTag1 COLLATE utf8_general_ci) DESC, - (it.value = vValue1 COLLATE utf8_general_ci) DESC, - (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, - match5 DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, - match6 DESC, - (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, - match7 DESC, - (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, - match8 DESC; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/itemProposal_beta.sql b/db/routines/vn/procedures/itemProposal_beta.sql deleted file mode 100644 index 4a6f761a9..000000000 --- a/db/routines/vn/procedures/itemProposal_beta.sql +++ /dev/null @@ -1,76 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemProposal_beta`(vItemFk INT, vTicketFk INT) -BEGIN - - DECLARE vWarehouseFk INT; - DECLARE vShipped DATE; - DECLARE vCalcFk INT; - DECLARE vTypeFk INT; - DECLARE vResultsMax INT DEFAULT 10; - - DECLARE vTag1 VARCHAR(25); - DECLARE vTag5 VARCHAR(25); - DECLARE vTag6 VARCHAR(25); - DECLARE vTag7 VARCHAR(25); - DECLARE vTag8 VARCHAR(25); - - DECLARE vValue1 VARCHAR(50); - DECLARE vValue5 VARCHAR(50); - DECLARE vValue6 VARCHAR(50); - DECLARE vValue7 VARCHAR(50); - DECLARE vValue8 VARCHAR(50); - - SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped - FROM vn.ticket - WHERE id = vTicketFk; - - SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value - INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 - FROM vn.item i - LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk - WHERE i.id = vItemFk; - - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - - SELECT i.id itemFk, - i.longName, - i.subName, - i.tag5, - i.value5, - (i.value5 <=> vValue5 COLLATE utf8_general_ci) match5, - i.tag6, - i.value6, - (i.value6 <=> vValue6 COLLATE utf8_general_ci) match6, - i.tag7, - i.value7, - (i.value7 <=> vValue7 COLLATE utf8_general_ci) match7, - i.tag8, - i.value8, - (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, - a.available, - IFNULL(ip.counter,0) counter - FROM vn.item i - JOIN cache.available a ON a.item_id = i.id - LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk - LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk - WHERE a.calc_id = vCalcFk - AND available > 0 - AND i.typeFk = vTypeFk - AND i.id != vItemFk - ORDER BY counter DESC, - (t1.name = vTag1 COLLATE utf8_general_ci) DESC, - (it1.value = vValue1 COLLATE utf8_general_ci) DESC, - (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, - (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, - (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, - (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, - (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, - (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, - (i.value8 = vValue8 COLLATE utf8_general_ci) DESC - LIMIT vResultsMax; - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 7cc9ad63e..2522280f7 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -1,20 +1,24 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getSimilar`(vItemFk INT, vWarehouseFk INT, vDate DATE, vIsShowedByType BOOL) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getSimilar`( + vSelf INT, + vTicketFk INT, + vShowType BOOL +) BEGIN - /** - * Propone articulos similares para posible cambio, - * ordenado con la cantidad de veces usado y segun sus caracteristicas - * - * @param vItemFk item id - * @param vWarehouseFk warehouse id - * @param vDate fecha para revisar disponible - * @param vIsShowedByType para mostrar solo artículos de ese tipo - */ +* Propone articulos disponibles ordenados, con la cantidad +* de veces usado y segun sus caracteristicas. +* +* @param vSelf Id de artículo +* @param vTicketFk Id de ticket +* @param vShowType Mostrar tipos +*/ + DECLARE vWarehouseFk INT; + DECLARE vShipped DATE; + DECLARE vCalcFk INT; + DECLARE vTypeFk INT; + DECLARE vPriority INT DEFAULT 1; - DECLARE vCalcFk INT; - DECLARE vTypeFk INT; - DECLARE vTag1 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag5 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag6 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; @@ -27,58 +31,86 @@ BEGIN DECLARE vValue7 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue8 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - - SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value - INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 - FROM vn.item i - LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk - WHERE i.id = vItemFk; - - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDate); - - SELECT i.id itemFk, - i.longName, - i.subName, - i.tag5, - i.value5, - (i.value5 <=> vValue5) match5, - i.tag6, - i.value6, - (i.value6 <=> vValue6) match6, - i.tag7, - i.value7, - (i.value7 <=> vValue7) match7, - i.tag8, - i.value8, - (i.value8 <=> vValue8) match8, - a.available, - IFNULL(ip.counter,0) counter, - IF(b.groupingMode = 1, b.grouping, b.packing) as minQuantity - FROM vn.item i - JOIN cache.available a ON a.item_id = i.id - LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk - LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - WHERE a.calc_id = vCalcFk - AND available > 0 - AND IF(vIsShowedByType, i.typeFk = vTypeFk, TRUE) - AND i.id != vItemFk - ORDER BY counter DESC, - (t1.name = vTag1) DESC, - (it1.value = vValue1) DESC, - (i.tag6 = vTag6) DESC, - (i.value6 = vValue6) DESC, - (i.tag5 = vTag5) DESC, - (i.value5 = vValue5) DESC, - (i.tag7 = vTag7) DESC, - (i.value7 = vValue7) DESC, - (i.tag8 = vTag8) DESC, - (i.value8 = vValue8) DESC - LIMIT 30; - + SELECT warehouseFk, shipped + INTO vWarehouseFk, vShipped + FROM ticket + WHERE id = vTicketFk; + SELECT typeFk, + tag5, + value5, + tag6, + value6, + tag7, + value7, + tag8, + value8, + t.name, + it.value + INTO vTypeFk, + vTag5, + vValue5, + vTag6, + vValue6, + vTag7, + vValue7, + vTag8, + vValue8, + vTag1, + vValue1 + FROM item i + LEFT JOIN itemTag it ON it.itemFk = i.id + AND it.priority = vPriority + LEFT JOIN tag t ON t.id = it.tagFk + WHERE i.id = vSelf; + + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); + + SELECT i.id itemFk, + i.longName, + i.subName, + i.tag5, + i.value5, + (i.value5 <=> vValue5) match5, + i.tag6, + i.value6, + (i.value6 <=> vValue6) match6, + i.tag7, + i.value7, + (i.value7 <=> vValue7) match7, + i.tag8, + i.value8, + (i.value8 <=> vValue8) match8, + a.available, + IFNULL(ip.counter, 0) `counter`, + IF(b.groupingMode = 1, b.grouping, b.packing) minQuantity, + iss.visible located + FROM item i + JOIN cache.available a ON a.item_id = i.id + LEFT JOIN itemProposal ip ON ip.mateFk = i.id + AND ip.itemFk = vSelf + LEFT JOIN itemTag it ON it.itemFk = i.id + AND it.priority = vPriority + LEFT JOIN tag t ON t.id = it.tagFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + AND lb.warehouse_id = vWarehouseFk + LEFT JOIN buy b ON b.id = lb.buy_id + LEFT JOIN itemShelvingStock iss ON iss.itemFk = i.id + AND iss.warehouseFk = vWarehouseFk + WHERE a.calc_id = vCalcFk + AND a.available > 0 + AND IF(vShowType, i.typeFk = vTypeFk, TRUE) + AND i.id <> vSelf + ORDER BY `counter` DESC, + (t.name = vTag1) DESC, + (it.value = vValue1) DESC, + (i.tag5 = vTag5) DESC, + match5 DESC, + (i.tag6 = vTag6) DESC, + match6 DESC, + (i.tag7 = vTag7) DESC, + match7 DESC, + (i.tag8 = vTag8) DESC, + match8 DESC; END$$ DELIMITER ; From a96743c3b96c81be2ee2a742de056c302c26acac Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 4 Mar 2024 13:34:42 +0100 Subject: [PATCH 130/150] refactor: refs #6494 Requested changes --- .../procedures/confection_controlSource.sql | 33 +++++++------------ 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/db/routines/vn/procedures/confection_controlSource.sql b/db/routines/vn/procedures/confection_controlSource.sql index 6cd43036f..f011a52e9 100644 --- a/db/routines/vn/procedures/confection_controlSource.sql +++ b/db/routines/vn/procedures/confection_controlSource.sql @@ -15,11 +15,8 @@ BEGIN * @param vMaxAlertLevel Id nivel de alerta * @param vWarehouseFk Id de almacén */ - DECLARE vMidnight DATETIME DEFAULT util.dayEnd(vDated); - DECLARE vEndingDate DATETIME DEFAULT vMidnight + INTERVAL vScopeDays DAY; + DECLARE vEndingDate DATETIME DEFAULT util.dayEnd(vDated) + INTERVAL vScopeDays DAY; - CREATE OR REPLACE TEMPORARY TABLE tConfectionControlSource - ENGINE = MEMORY SELECT t.shipped, t.id ticketFk, s.id saleFk, @@ -73,27 +70,24 @@ BEGIN AND tls.alertLevel < vMaxAlertLevel AND wh.hasConfectionTeam AND t.shipped BETWEEN vDated AND vEndingDate - AND s.quantity > 0; - - -- Entradas - INSERT INTO tConfectionControlSource( - shipped, - ticketFk, - quantity, - concept, - category, - nickname, - warehouse, - description - ) + AND s.quantity > 0 + UNION ALL SELECT tr.shipped, e.id, + NULL, b.quantity, i.name, + NULL, i.category, + NULL, whi.name, who.name, - ct.description + NULL, + NULL, + NULL, + ct.description, + NULL, + NULL FROM buy b JOIN `entry` e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk @@ -105,8 +99,5 @@ BEGIN WHERE who.hasConfectionTeam AND it.making AND tr.shipped BETWEEN vDated AND vEndingDate; - - SELECT * FROM tConfectionControlSource; - DROP TEMPORARY TABLE tConfectionControlSource; END$$ DELIMITER ; From fa70eeb75c78b95960c0ce265e038d77f52c4b2b Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 4 Mar 2024 13:42:11 +0100 Subject: [PATCH 131/150] refactor: refs #6499 Requested changes --- .../procedures/{pay.sql => payment_add.sql} | 5 ++-- .../10924-pinkCordyline/00-firstScript.sql | 29 ++++++++++++++++++- 2 files changed, 31 insertions(+), 3 deletions(-) rename db/routines/vn/procedures/{pay.sql => payment_add.sql} (93%) diff --git a/db/routines/vn/procedures/pay.sql b/db/routines/vn/procedures/payment_add.sql similarity index 93% rename from db/routines/vn/procedures/pay.sql rename to db/routines/vn/procedures/payment_add.sql index 2ef9ca2d6..061a75848 100644 --- a/db/routines/vn/procedures/pay.sql +++ b/db/routines/vn/procedures/payment_add.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`pay`( +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`payment_add`( vDated DATE, vSupplierFk INT, vAmount DOUBLE, @@ -12,7 +12,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`pay`( vCompanyFk INT) BEGIN /** - * Registra un pago realizado a un proveedor. + * Registra un pago realizado a un proveedor y + * su correspondiente registro en caja. * * @param vDated Fecha del pago * @param vSupplierFk Id del proveedor diff --git a/db/versions/10924-pinkCordyline/00-firstScript.sql b/db/versions/10924-pinkCordyline/00-firstScript.sql index ea04623cd..1c6c1c0f8 100644 --- a/db/versions/10924-pinkCordyline/00-firstScript.sql +++ b/db/versions/10924-pinkCordyline/00-firstScript.sql @@ -1,4 +1,31 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_addChild`() +BEGIN + SELECT 1; +END$$ +DELIMITER ; GRANT EXECUTE ON PROCEDURE vn.balanceNestTree_addChild TO adminBoss; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_delete`() +BEGIN + SELECT 1; +END$$ +DELIMITER ; GRANT EXECUTE ON PROCEDURE vn.balanceNestTree_delete TO adminBoss; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`balanceNestTree_move`() +BEGIN + SELECT 1; +END$$ +DELIMITER ; GRANT EXECUTE ON PROCEDURE vn.balanceNestTree_move TO adminBoss; -GRANT EXECUTE ON PROCEDURE vn.pay TO financial; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`payment_add`() +BEGIN + SELECT 1; +END$$ +DELIMITER ; +GRANT EXECUTE ON PROCEDURE vn.payment_add TO financial; From b761c258a1589fa11e312a99484c59dbdd2cf7d5 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 4 Mar 2024 14:12:56 +0100 Subject: [PATCH 132/150] refs #6336 feat(claimState): delete without using --- db/dump/fixtures.before.sql | 11 ++++------- db/versions/10926-limeFern/00-refactorClaimState.sql | 8 ++++++++ e2e/paths/06-claim/01_basic_data.spec.js | 4 ++-- .../back/methods/claim-state/specs/isEditable.spec.js | 2 +- .../methods/claim/specs/updateClaimAction.spec.js | 2 +- 5 files changed, 16 insertions(+), 11 deletions(-) create mode 100644 db/versions/10926-limeFern/00-refactorClaimState.sql diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index aef0f13e3..c7f177742 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1819,19 +1819,16 @@ INSERT INTO `vn`.`clientSample`(`id`, `clientFk`, `typeFk`, `created`, `workerFk INSERT INTO `vn`.`claimState`(`id`, `code`, `description`, `roleFk`, `priority`, `hasToNotify`) VALUES ( 1, 'pending', 'Pendiente', 1, 1, 0), - ( 2, 'managed', 'Gestionado', 72, 5, 0), ( 3, 'resolved', 'Resuelto', 72, 7, 0), ( 4, 'canceled', 'Anulado', 72, 6, 1), - ( 5, 'incomplete', 'Incompleta', 1, 3, 1), - ( 6, 'mana', 'Mana', 72, 4, 0), - ( 7, 'lack', 'Faltas', 72, 2, 0); + ( 5, 'incomplete', 'Incompleta', 1, 3, 1); INSERT INTO `vn`.`claim`(`id`, `ticketCreated`, `claimStateFk`, `clientFk`, `workerFk`, `responsibility`, `isChargedToMana`, `created`, `packages`, `ticketFk`) VALUES (1, util.VN_CURDATE(), 1, 1101, 18, 3, 0, util.VN_CURDATE(), 0, 11), - (2, util.VN_CURDATE(), 2, 1101, 18, 3, 0, util.VN_CURDATE(), 1, 16), - (3, util.VN_CURDATE(), 3, 1101, 18, 1, 1, util.VN_CURDATE(), 5, 7), - (4, util.VN_CURDATE(), 3, 1104, 18, 5, 0, util.VN_CURDATE(), 10, 8); + (2, util.VN_CURDATE(), 4, 1101, 18, 3, 0, util.VN_CURDATE(), 1, 16), + (3, util.VN_CURDATE(), 3, 1101, 18, 1, 1, util.VN_CURDATE(), 5, 7), + (4, util.VN_CURDATE(), 3, 1104, 18, 5, 0, util.VN_CURDATE(), 10, 8); INSERT INTO `vn`.`claimObservation` (`claimFk`, `workerFk`, `text`, `created`) VALUES diff --git a/db/versions/10926-limeFern/00-refactorClaimState.sql b/db/versions/10926-limeFern/00-refactorClaimState.sql new file mode 100644 index 000000000..bb2dc349a --- /dev/null +++ b/db/versions/10926-limeFern/00-refactorClaimState.sql @@ -0,0 +1,8 @@ +UPDATE vn.claim c + JOIN vn.claimState cs ON cs.id = c.claimStateFk + JOIN vn.claimState ns ON ns.code = 'resolved' + SET c.claimStateFk = ns.id + WHERE cs.code IN ('managed', 'mana', 'lack', 'relocation'); + +DELETE FROM vn.claimState + WHERE code IN ('managed', 'mana', 'lack', 'relocation'); diff --git a/e2e/paths/06-claim/01_basic_data.spec.js b/e2e/paths/06-claim/01_basic_data.spec.js index 0a08cad9f..2df95bd4a 100644 --- a/e2e/paths/06-claim/01_basic_data.spec.js +++ b/e2e/paths/06-claim/01_basic_data.spec.js @@ -21,7 +21,7 @@ describe('Claim edit basic data path', () => { }); it(`should edit claim state and observation fields`, async() => { - await page.autocompleteSearch(selectors.claimBasicData.claimState, 'Gestionado'); + await page.autocompleteSearch(selectors.claimBasicData.claimState, 'Resuelto'); await page.clearInput(selectors.claimBasicData.packages); await page.write(selectors.claimBasicData.packages, '2'); await page.waitToClick(selectors.claimBasicData.saveButton); @@ -48,7 +48,7 @@ describe('Claim edit basic data path', () => { await page.waitForSelector(selectors.claimBasicData.claimState); const result = await page.waitToGetProperty(selectors.claimBasicData.claimState, 'value'); - expect(result).toEqual('Gestionado'); + expect(result).toEqual('Resuelto'); }); it('should confirm the "is paid with mana" and "Pick up" checkbox are checked', async() => { diff --git a/modules/claim/back/methods/claim-state/specs/isEditable.spec.js b/modules/claim/back/methods/claim-state/specs/isEditable.spec.js index 1fb8e1536..6d97eed06 100644 --- a/modules/claim/back/methods/claim-state/specs/isEditable.spec.js +++ b/modules/claim/back/methods/claim-state/specs/isEditable.spec.js @@ -64,7 +64,7 @@ describe('claimstate isEditable()', () => { const options = {transaction: tx}; const ctx = {req: {accessToken: {userId: claimManagerId}}}; - const result = await app.models.ClaimState.isEditable(ctx, 7, options); + const result = await app.models.ClaimState.isEditable(ctx, 5, options); expect(result).toEqual(true); diff --git a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js index 2f16d002c..99436fed6 100644 --- a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js @@ -21,7 +21,7 @@ describe('Update Claim', () => { clientFk: 1101, ticketCreated: newDate, workerFk: 18, - claimStateFk: 2, + claimStateFk: 1, isChargedToMana: true, responsibility: 4, observation: 'observation' From d979e36686e7db370c6ded1a1afd47c5be12631b Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 4 Mar 2024 14:13:37 +0100 Subject: [PATCH 133/150] refs #6336 feat(claimState): delete without using & refactor: unnecessary test --- .../methods/claim/specs/updateClaim.spec.js | 126 +----------------- 1 file changed, 4 insertions(+), 122 deletions(-) diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index e2d5fcfeb..bd77ae406 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -21,12 +21,13 @@ describe('Update Claim', () => { claimStatesMap = claimStates.reduce((acc, state) => ({...acc, [state.code]: state.id}), {}); }); const newDate = Date.vnNew(); + const claimManagerId = 72; const originalData = { ticketFk: 3, clientFk: 1101, ticketCreated: newDate, workerFk: 18, - claimStateFk: 2, + claimStateFk: 5, isChargedToMana: true, responsibility: 4, observation: 'observation' @@ -77,7 +78,6 @@ describe('Update Claim', () => { spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); const pendingState = claimStatesMap.pending; - const claimManagerId = 72; const ctx = { req: { accessToken: {userId: claimManagerId}, @@ -104,85 +104,7 @@ describe('Update Claim', () => { } }); - it(`should success to update the claimState to 'managed' and send a rocket message`, async() => { - const tx = await app.models.Claim.beginTransaction({}); - - try { - const options = {transaction: tx}; - - const newClaim = await app.models.Claim.create(originalData, options); - - const chatModel = app.models.Chat; - spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); - - const managedState = claimStatesMap.managed; - const claimManagerId = 72; - const ctx = { - req: { - accessToken: {userId: claimManagerId}, - headers: {origin: url} - }, - args: { - observation: 'valid observation', - claimStateFk: managedState, - hasToPickUp: false - } - }; - ctx.req.__ = i18n.__; - await app.models.Claim.updateClaim(ctx, newClaim.id, options); - - let updatedClaim = await app.models.Claim.findById(newClaim.id, null, options); - - expect(updatedClaim.observation).toEqual(ctx.args.observation); - expect(chatModel.sendCheckingPresence).toHaveBeenCalled(); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it(`should success to update the claimState to 'resolved' and send a rocket message`, async() => { - const tx = await app.models.Claim.beginTransaction({}); - - try { - const options = {transaction: tx}; - - const newClaim = await app.models.Claim.create(originalData, options); - - const chatModel = app.models.Chat; - spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); - - const resolvedState = claimStatesMap.resolved; - const claimManagerId = 72; - const ctx = { - req: { - accessToken: {userId: claimManagerId}, - headers: {origin: url} - }, - args: { - observation: 'valid observation', - claimStateFk: resolvedState, - hasToPickUp: false - } - }; - ctx.req.__ = i18n.__; - await app.models.Claim.updateClaim(ctx, newClaim.id, options); - - let updatedClaim = await app.models.Claim.findById(newClaim.id, null, options); - - expect(updatedClaim.observation).toEqual(ctx.args.observation); - expect(chatModel.sendCheckingPresence).toHaveBeenCalled(); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it(`should success to update the claimState to 'canceled' and send a rocket message`, async() => { + it(`should success to update the claimState to 'canceled' and send two rocket message`, async() => { const tx = await app.models.Claim.beginTransaction({}); try { @@ -194,7 +116,6 @@ describe('Update Claim', () => { spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); const canceledState = claimStatesMap.canceled; - const claimManagerId = 72; const ctx = { req: { accessToken: {userId: claimManagerId}, @@ -212,46 +133,7 @@ describe('Update Claim', () => { let updatedClaim = await app.models.Claim.findById(newClaim.id, null, options); expect(updatedClaim.observation).toEqual(ctx.args.observation); - expect(chatModel.sendCheckingPresence).toHaveBeenCalled(); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it(`should success to update the claimState to 'incomplete' and send a rocket message`, async() => { - const tx = await app.models.Claim.beginTransaction({}); - - try { - const options = {transaction: tx}; - - const newClaim = await app.models.Claim.create(originalData, options); - - const chatModel = app.models.Chat; - spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); - - const incompleteState = 5; - const claimManagerId = 72; - const ctx = { - req: { - accessToken: {userId: claimManagerId}, - headers: {origin: url} - }, - args: { - observation: 'valid observation', - claimStateFk: incompleteState, - hasToPickUp: false - } - }; - ctx.req.__ = i18n.__; - await app.models.Claim.updateClaim(ctx, newClaim.id, options); - - let updatedClaim = await app.models.Claim.findById(newClaim.id, null, options); - - expect(updatedClaim.observation).toEqual(ctx.args.observation); - expect(chatModel.sendCheckingPresence).toHaveBeenCalled(); + expect(chatModel.sendCheckingPresence).toHaveBeenCalledTimes(2); await tx.rollback(); } catch (e) { From 2b299eb32b4db2527e16f21d76c753e96d14c281 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 5 Mar 2024 09:48:53 +0100 Subject: [PATCH 134/150] refs #6980 fix iban --- loopback/util/validateIban.js | 1 - modules/client/front/billing-data/index.html | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/loopback/util/validateIban.js b/loopback/util/validateIban.js index ed3e00426..2386538b5 100644 --- a/loopback/util/validateIban.js +++ b/loopback/util/validateIban.js @@ -3,7 +3,6 @@ module.exports = function(iban, countryCode) { if (typeof iban != 'string') return false; if (countryCode?.toLowerCase() != 'es') return true; - iban = iban.toUpperCase(); iban = trim(iban); iban = iban.replace(/\s/g, ''); diff --git a/modules/client/front/billing-data/index.html b/modules/client/front/billing-data/index.html index bd4f86d1c..39c0fc428 100644 --- a/modules/client/front/billing-data/index.html +++ b/modules/client/front/billing-data/index.html @@ -33,6 +33,7 @@ Date: Tue, 5 Mar 2024 10:09:32 +0100 Subject: [PATCH 135/150] fix: refs #6276 options --- back/methods/collection/getSales.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index a5e7aeefa..78945dc80 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -44,7 +44,7 @@ module.exports = Self => { if (source) { await Self.rawSql( - 'CALL vn.ticketStateToday_setState(?,?)', [id, source], options + 'CALL vn.ticketStateToday_setState(?,?)', [id, source], myOptions ); } From e0732835d040cc0e20cab7ad1c6e3ac8e6da2a92 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 5 Mar 2024 10:25:23 +0100 Subject: [PATCH 136/150] refactor: refs #6948 Bank to Accouting --- back/model-config.json | 2 +- back/models/{bank.json => accounting.json} | 9 +++------ back/models/payment.json | 2 +- db/routines/bs/procedures/manaCustomerUpdate.sql | 2 +- .../hedera/procedures/tpvTransaction_undo.sql | 2 +- .../sage/procedures/accountingMovements_add.sql | 4 ++-- db/routines/sage/procedures/pgc_add.sql | 12 ++++++------ db/routines/vn/functions/till_new.sql | 2 +- .../vn/procedures/bankPolicy_notifyExpired.sql | 12 +++++------- db/routines/vn/procedures/client_getMana.sql | 3 ++- db/routines/vn/procedures/supplier_statement.sql | 2 +- db/routines/vn/triggers/payment_beforeInsert.sql | 10 +++++----- db/routines/vn/views/bank.sql | 12 ------------ db/routines/vn/views/exchangeInsuranceOut.sql | 4 ++-- db/routines/vn2008/views/Bancos.sql | 16 ++++++++-------- .../10928-orangeEucalyptus/00-firstScript.sql | 2 ++ .../client/back/methods/client/createReceipt.js | 2 +- .../methods/receipt/balanceCompensationEmail.js | 2 +- modules/client/back/models/receipt.json | 2 +- modules/client/back/models/till.json | 2 +- .../back/models/invoice-in-due-day.json | 2 +- 21 files changed, 46 insertions(+), 60 deletions(-) rename back/models/{bank.json => accounting.json} (85%) delete mode 100644 db/routines/vn/views/bank.sql create mode 100644 db/versions/10928-orangeEucalyptus/00-firstScript.sql diff --git a/back/model-config.json b/back/model-config.json index c4eefd932..cc260760e 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -13,7 +13,7 @@ "AuthCode": { "dataSource": "vn" }, - "Bank": { + "Accounting": { "dataSource": "vn" }, "Buyer": { diff --git a/back/models/bank.json b/back/models/accounting.json similarity index 85% rename from back/models/bank.json rename to back/models/accounting.json index da73b1141..979947471 100644 --- a/back/models/bank.json +++ b/back/models/accounting.json @@ -1,9 +1,9 @@ { - "name": "Bank", + "name": "Accounting", "base": "VnModel", "options": { "mysql": { - "table": "bank" + "table": "accounting" } }, "properties": { @@ -22,10 +22,7 @@ }, "accountingTypeFk": { "type": "number", - "required": true, - "mysql": { - "columnName": "cash" - } + "required": true }, "entityFk": { "type": "number", diff --git a/back/models/payment.json b/back/models/payment.json index 7eca36e4d..ed354969e 100644 --- a/back/models/payment.json +++ b/back/models/payment.json @@ -47,7 +47,7 @@ }, "bank": { "type": "belongsTo", - "model": "Bank", + "model": "Accounting", "foreignKey": "bankFk" }, "payMethod": { diff --git a/db/routines/bs/procedures/manaCustomerUpdate.sql b/db/routines/bs/procedures/manaCustomerUpdate.sql index 2cb25d135..2038f976a 100644 --- a/db/routines/bs/procedures/manaCustomerUpdate.sql +++ b/db/routines/bs/procedures/manaCustomerUpdate.sql @@ -22,7 +22,7 @@ BEGIN FROM vn.component WHERE code = 'manaClaim'; SELECT id INTO vManaBankId - FROM vn.bank WHERE code = 'mana'; + FROM vn.accounting WHERE code = 'mana'; SELECT id INTO vManaGreugeTypeId FROM vn.greugeType WHERE code = 'mana'; diff --git a/db/routines/hedera/procedures/tpvTransaction_undo.sql b/db/routines/hedera/procedures/tpvTransaction_undo.sql index ed72dd76d..f31ba6a80 100644 --- a/db/routines/hedera/procedures/tpvTransaction_undo.sql +++ b/db/routines/hedera/procedures/tpvTransaction_undo.sql @@ -54,7 +54,7 @@ p: BEGIN FROM vn.`client` WHERE id = vCustomer; SELECT account INTO vAccount - FROM vn.bank WHERE id = vBank; + FROM vn.accounting WHERE id = vBank; DELETE FROM vn.XDiario WHERE SUBCTA = vSubaccount diff --git a/db/routines/sage/procedures/accountingMovements_add.sql b/db/routines/sage/procedures/accountingMovements_add.sql index bd86e132d..ffb20c3ee 100644 --- a/db/routines/sage/procedures/accountingMovements_add.sql +++ b/db/routines/sage/procedures/accountingMovements_add.sql @@ -254,8 +254,8 @@ BEGIN ) sub GROUP BY ASIEN )sub2 ON sub2.ASIEN = x.ASIEN LEFT JOIN ( SELECT DISTINCT(account),cu.code - FROM vn.bank b - JOIN vn.currency cu ON cu.id = b.currencyFk + FROM vn.accounting a + JOIN vn.currency cu ON cu.id = a.currencyFk WHERE cu.code <> 'EUR' -- no se informa cuando la divisa en EUR )sub3 ON sub3.account = x.SUBCTA WHERE x.enlazadoSage = FALSE diff --git a/db/routines/sage/procedures/pgc_add.sql b/db/routines/sage/procedures/pgc_add.sql index 6dd5bc72d..ebcb2d043 100644 --- a/db/routines/sage/procedures/pgc_add.sql +++ b/db/routines/sage/procedures/pgc_add.sql @@ -17,15 +17,15 @@ BEGIN e.id accountFk, UCASE(e.name), '' - FROM vn.expense e + FROM expense e UNION SELECT company_getCode(vCompanyFk), - b.account, - UCASE(b.bank), + a.account, + UCASE(a.bank), '' - FROM vn.bank b - WHERE b.isActive - AND b.`account` + FROM accounting a + WHERE a.isActive + AND a.`account` UNION SELECT CodigoEmpresa, CodigoCuenta, diff --git a/db/routines/vn/functions/till_new.sql b/db/routines/vn/functions/till_new.sql index cfca5945d..24f4f2b79 100644 --- a/db/routines/vn/functions/till_new.sql +++ b/db/routines/vn/functions/till_new.sql @@ -34,7 +34,7 @@ BEGIN -- Inserta los asientos contables SELECT account INTO vAccount - FROM bank WHERE id = vBank; + FROM accounting WHERE id = vBank; SELECT accountingAccount INTO vSubaccount FROM `client` WHERE id = vClient; diff --git a/db/routines/vn/procedures/bankPolicy_notifyExpired.sql b/db/routines/vn/procedures/bankPolicy_notifyExpired.sql index 52b747659..61216938d 100644 --- a/db/routines/vn/procedures/bankPolicy_notifyExpired.sql +++ b/db/routines/vn/procedures/bankPolicy_notifyExpired.sql @@ -10,13 +10,11 @@ BEGIN INSERT INTO mail (receiver,replyTo,subject,body) SELECT 'administracion@verdnatura.es' receiver, 'noreply@verdnatura.es' replyTo, - CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') subject, - CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') body - FROM vn.bankPolicy bp - LEFT JOIN vn.supplier s - ON s.id = bp.supplierFk - LEFT JOIN vn.bank b - ON b.id = bp.accountingFk + CONCAT('El seguro de la poliza ',a.id,' ',a.bank,' ha finalizado.') subject, + CONCAT('El seguro de la poliza ',a.id,' ',a.bank,' ha finalizado.') body + FROM bankPolicy bp + LEFT JOIN supplier s ON s.id = bp.supplierFk + LEFT JOIN accounting a ON a.id = bp.accountingFk WHERE bp.insuranceExpired = util.VN_CURDATE(); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/client_getMana.sql b/db/routines/vn/procedures/client_getMana.sql index 99b00c6df..f5bb5747d 100644 --- a/db/routines/vn/procedures/client_getMana.sql +++ b/db/routines/vn/procedures/client_getMana.sql @@ -39,7 +39,8 @@ BEGIN FROM receipt r JOIN `client` c ON c.id = r.clientFk JOIN tmp.client tc ON tc.id = c.id - JOIN bank b ON r.bankFk = b.id AND b.code = 'mana' + JOIN accounting a ON r.bankFk = a.id + AND a.code = 'mana' WHERE r.payed > vFromDated AND r.payed <= util.VN_CURDATE() UNION ALL diff --git a/db/routines/vn/procedures/supplier_statement.sql b/db/routines/vn/procedures/supplier_statement.sql index 406286e9d..a03a7770c 100644 --- a/db/routines/vn/procedures/supplier_statement.sql +++ b/db/routines/vn/procedures/supplier_statement.sql @@ -94,7 +94,7 @@ BEGIN 'payment' FROM payment p LEFT JOIN currency c ON c.id = p.currencyFk - LEFT JOIN bank b ON b.id = p.bankFk + LEFT JOIN accounting a ON a.id = p.bankFk LEFT JOIN payMethod pm ON pm.id = p.payMethodFk LEFT JOIN promissoryNote pn ON pn.paymentFk = p.id WHERE p.received > '2014-12-31' diff --git a/db/routines/vn/triggers/payment_beforeInsert.sql b/db/routines/vn/triggers/payment_beforeInsert.sql index 6a28a1382..1b343712f 100644 --- a/db/routines/vn/triggers/payment_beforeInsert.sql +++ b/db/routines/vn/triggers/payment_beforeInsert.sql @@ -10,21 +10,21 @@ BEGIN -- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH SELECT (at2.code = 'cash') INTO bolCASH - FROM vn.bank b - JOIN vn.accountingType at2 ON at2.id = b.cash - WHERE b.id = NEW.bankFk; + FROM accounting a + JOIN accountingType at2 ON at2.id = a.accountingTypeFk + WHERE a.id = NEW.bankFk; IF bolCASH THEN SELECT account INTO cuenta_banco - FROM bank + FROM accounting WHERE id = NEW.bankFk; SELECT account INTO cuenta_proveedor FROM supplier WHERE id = NEW.supplierFk; - CALL vn.ledger_next(vNewBookEntry); + CALL ledger_next(vNewBookEntry); INSERT INTO XDiario ( ASIEN, FECHA, diff --git a/db/routines/vn/views/bank.sql b/db/routines/vn/views/bank.sql deleted file mode 100644 index fa0d9a4f0..000000000 --- a/db/routines/vn/views/bank.sql +++ /dev/null @@ -1,12 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`bank` -AS SELECT `a`.`id` AS `id`, - `a`.`bank` AS `bank`, - `a`.`account` AS `account`, - `a`.`accountingTypeFk` AS `cash`, - `a`.`entityFk` AS `entityFk`, - `a`.`isActive` AS `isActive`, - `a`.`currencyFk` AS `currencyFk`, - `a`.`code` AS `code` -FROM `vn`.`accounting` `a` diff --git a/db/routines/vn/views/exchangeInsuranceOut.sql b/db/routines/vn/views/exchangeInsuranceOut.sql index f93b65331..5c41dbb24 100644 --- a/db/routines/vn/views/exchangeInsuranceOut.sql +++ b/db/routines/vn/views/exchangeInsuranceOut.sql @@ -7,9 +7,9 @@ AS SELECT `p`.`received` AS `received`, FROM ( ( `vn`.`payment` `p` - JOIN `vn`.`bank` `b` ON(`b`.`id` = `p`.`bankFk`) + JOIN `vn`.`accounting` `a` ON(`a`.`id` = `p`.`bankFk`) ) - JOIN `vn`.`accountingType` `at2` ON(`at2`.`id` = `b`.`cash`) + JOIN `vn`.`accountingType` `at2` ON(`at2`.`id` = `a`.`accountingTypeFk`) ) WHERE `p`.`currencyFk` = 2 AND `at2`.`code` = 'wireTransfer' diff --git a/db/routines/vn2008/views/Bancos.sql b/db/routines/vn2008/views/Bancos.sql index 0c6f8d1bd..6e850f365 100644 --- a/db/routines/vn2008/views/Bancos.sql +++ b/db/routines/vn2008/views/Bancos.sql @@ -1,11 +1,11 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn2008`.`Bancos` -AS SELECT `b`.`id` AS `Id_Banco`, - `b`.`bank` AS `Banco`, - `b`.`account` AS `Cuenta`, - `b`.`cash` AS `cash`, - `b`.`entityFk` AS `entity_id`, - `b`.`isActive` AS `activo`, - `b`.`currencyFk` AS `currencyFk` -FROM `vn`.`bank` `b` +AS SELECT `a`.`id` AS `Id_Banco`, + `a`.`bank` AS `Banco`, + `a`.`account` AS `Cuenta`, + `a`.`accountingTypeFk` AS `cash`, + `a`.`entityFk` AS `entity_id`, + `a`.`isActive` AS `activo`, + `a`.`currencyFk` AS `currencyFk` +FROM `vn`.`accounting` `a` diff --git a/db/versions/10928-orangeEucalyptus/00-firstScript.sql b/db/versions/10928-orangeEucalyptus/00-firstScript.sql new file mode 100644 index 000000000..5f56f580b --- /dev/null +++ b/db/versions/10928-orangeEucalyptus/00-firstScript.sql @@ -0,0 +1,2 @@ +REVOKE SELECT ON TABLE vn.bank FROM administrative, hr; +GRANT SELECT ON TABLE vn.accounting TO administrative, hr; diff --git a/modules/client/back/methods/client/createReceipt.js b/modules/client/back/methods/client/createReceipt.js index b70b9bbe0..debdaf066 100644 --- a/modules/client/back/methods/client/createReceipt.js +++ b/modules/client/back/methods/client/createReceipt.js @@ -69,7 +69,7 @@ module.exports = function(Self) { delete args.ctx; // Remove unwanted properties const originalClient = await models.Client.findById(args.clientFk, null, myOptions); - const bank = await models.Bank.findById(args.bankFk, null, myOptions); + const bank = await models.Accounting.findById(args.bankFk, null, myOptions); const accountingType = await models.AccountingType.findById(bank.accountingTypeFk, null, myOptions); if (accountingType.code == 'compensation') { diff --git a/modules/client/back/methods/receipt/balanceCompensationEmail.js b/modules/client/back/methods/receipt/balanceCompensationEmail.js index afae5dabc..994d5124a 100644 --- a/modules/client/back/methods/receipt/balanceCompensationEmail.js +++ b/modules/client/back/methods/receipt/balanceCompensationEmail.js @@ -28,7 +28,7 @@ module.exports = Self => { const models = Self.app.models; const receipt = await models.Receipt.findById(id, {fields: ['clientFk', 'bankFk']}); - const bank = await models.Bank.findById(receipt.bankFk); + const bank = await models.Accounting.findById(receipt.bankFk); if (!bank) throw new UserError(`Receipt's bank was not found`); diff --git a/modules/client/back/models/receipt.json b/modules/client/back/models/receipt.json index da7879df9..6ade21ac5 100644 --- a/modules/client/back/models/receipt.json +++ b/modules/client/back/models/receipt.json @@ -60,7 +60,7 @@ }, "bank": { "type": "belongsTo", - "model": "Bank", + "model": "Accounting", "foreignKey": "bankFk" }, "supplier": { diff --git a/modules/client/back/models/till.json b/modules/client/back/models/till.json index 4b86e50e2..6677b27d4 100644 --- a/modules/client/back/models/till.json +++ b/modules/client/back/models/till.json @@ -46,7 +46,7 @@ "relations": { "bank": { "type": "belongsTo", - "model": "Bank", + "model": "Accounting", "foreignKey": "bankFk" }, "worker": { diff --git a/modules/invoiceIn/back/models/invoice-in-due-day.json b/modules/invoiceIn/back/models/invoice-in-due-day.json index d2cffc81b..ca3616ef8 100644 --- a/modules/invoiceIn/back/models/invoice-in-due-day.json +++ b/modules/invoiceIn/back/models/invoice-in-due-day.json @@ -34,7 +34,7 @@ "relations": { "bank": { "type": "belongsTo", - "model": "Bank", + "model": "Accounting", "foreignKey": "bankFk" } } From 55ba315858a4400ccd0729d5a298638b912574e3 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 5 Mar 2024 10:30:25 +0100 Subject: [PATCH 137/150] refactor: refs #6948 Bank to Accouting --- db/versions/10928-orangeEucalyptus/00-firstScript.sql | 3 +++ front/salix/components/user-popover/index.html | 2 +- modules/client/front/balance/create/index.html | 2 +- modules/invoiceIn/front/dueDay/index.html | 2 +- 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/db/versions/10928-orangeEucalyptus/00-firstScript.sql b/db/versions/10928-orangeEucalyptus/00-firstScript.sql index 5f56f580b..58d3605de 100644 --- a/db/versions/10928-orangeEucalyptus/00-firstScript.sql +++ b/db/versions/10928-orangeEucalyptus/00-firstScript.sql @@ -1,2 +1,5 @@ REVOKE SELECT ON TABLE vn.bank FROM administrative, hr; GRANT SELECT ON TABLE vn.accounting TO administrative, hr; +UPDATE salix.ACL + SET model = 'Accounting' + WHERE model = 'Bank'; diff --git a/front/salix/components/user-popover/index.html b/front/salix/components/user-popover/index.html index 0fa6800c5..06a4af1e0 100644 --- a/front/salix/components/user-popover/index.html +++ b/front/salix/components/user-popover/index.html @@ -58,7 +58,7 @@ label="Local bank" id="localBank" ng-model="$ctrl.localBankFk" - url="Banks" + url="Accountings" select-fields="['id','bank']" show-field="bank" order="id" diff --git a/modules/client/front/balance/create/index.html b/modules/client/front/balance/create/index.html index 27b182c9a..25789b01a 100644 --- a/modules/client/front/balance/create/index.html +++ b/modules/client/front/balance/create/index.html @@ -29,7 +29,7 @@ Date: Tue, 5 Mar 2024 10:37:15 +0100 Subject: [PATCH 138/150] refs #6607 feat:[checking boxes] --- db/routines/vn/procedures/sale_getFromTicketOrCollection.sql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql b/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql index e0cff202f..39c82d4ca 100644 --- a/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql +++ b/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql @@ -80,6 +80,9 @@ DECLARE vIsCollection BOOL; MIN(iss.created) picked, IF(sm.id, TRUE, FALSE) hasMistake, sg.sectorFk + b.packing, + b.grouping, + o.code FROM tmp.ticket t JOIN sale s ON s.ticketFk = t.id JOIN ticket tt ON tt.id = t.id From d2f451c613d0f1a447cd61558aefda9b1ea6040e Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 5 Mar 2024 12:33:28 +0100 Subject: [PATCH 139/150] ticket #162561 hotfix --- db/routines/vn/procedures/itemProposal.sql | 137 +++++++++++++-------- 1 file changed, 83 insertions(+), 54 deletions(-) diff --git a/db/routines/vn/procedures/itemProposal.sql b/db/routines/vn/procedures/itemProposal.sql index 74d356d77..47a4e9779 100644 --- a/db/routines/vn/procedures/itemProposal.sql +++ b/db/routines/vn/procedures/itemProposal.sql @@ -1,42 +1,68 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemProposal`(vItemFk INT, vTicketFk INT,vShowType BOOL) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemProposal`( + vSelf INT, + vTicketFk INT, + vShowType BOOL +) BEGIN - /** - * Propone articulos disponible ordenado, con la cantidad de veces usado y segun sus caracteristicas - * - * @param vItemFk item id - * @param vTicketFk ticket id - * @param vShowType mostrar tipos - */ - +* Propone articulos disponibles ordenados, con la cantidad +* de veces usado y segun sus caracteristicas. +* +* @param vSelf Id de artículo +* @param vTicketFk Id de ticket +* @param vShowType Mostrar tipos +*/ DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vCalcFk INT; DECLARE vTypeFk INT; + DECLARE vPriority INT DEFAULT 1; - DECLARE vTag1 VARCHAR(25); - DECLARE vTag5 VARCHAR(25); - DECLARE vTag6 VARCHAR(25); - DECLARE vTag7 VARCHAR(25); - DECLARE vTag8 VARCHAR(25); + DECLARE vTag1 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; + DECLARE vTag5 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; + DECLARE vTag6 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; + DECLARE vTag7 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; + DECLARE vTag8 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; + + DECLARE vValue1 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; + DECLARE vValue5 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; + DECLARE vValue6 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; + DECLARE vValue7 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; + DECLARE vValue8 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - DECLARE vValue1 VARCHAR(50); - DECLARE vValue5 VARCHAR(50); - DECLARE vValue6 VARCHAR(50); - DECLARE vValue7 VARCHAR(50); - DECLARE vValue8 VARCHAR(50); - - SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped - FROM vn.ticket + SELECT warehouseFk, shipped + INTO vWarehouseFk, vShipped + FROM ticket WHERE id = vTicketFk; - SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value - INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 - FROM vn.item i - LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk - WHERE i.id = vItemFk; + SELECT typeFk, + tag5, + value5, + tag6, + value6, + tag7, + value7, + tag8, + value8, + t.name, + it.value + INTO vTypeFk, + vTag5, + vValue5, + vTag6, + vValue6, + vTag7, + vValue7, + vTag8, + vValue8, + vTag1, + vValue1 + FROM item i + LEFT JOIN itemTag it ON it.itemFk = i.id + AND it.priority = vPriority + LEFT JOIN tag t ON t.id = it.tagFk + WHERE i.id = vSelf; CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); @@ -45,43 +71,46 @@ BEGIN i.subName, i.tag5, i.value5, - (i.value5 <=> vValue5 COLLATE utf8_general_ci) match5, + (i.value5 <=> vValue5) match5, i.tag6, i.value6, - (i.value6 <=> vValue6 COLLATE utf8_general_ci) match6, + (i.value6 <=> vValue6) match6, i.tag7, i.value7, - (i.value7 <=> vValue7 COLLATE utf8_general_ci) match7, + (i.value7 <=> vValue7) match7, i.tag8, i.value8, - (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, + (i.value8 <=> vValue8) match8, a.available, - IFNULL(ip.counter,0) counter, - IF(b.groupingMode = 1, b.grouping, b.packing) as minQuantity, + IFNULL(ip.counter, 0) `counter`, + IF(b.groupingMode = 1, b.grouping, b.packing) minQuantity, iss.visible located FROM item i JOIN cache.available a ON a.item_id = i.id - LEFT JOIN itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk - LEFT JOIN itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 - LEFT JOIN tag t1 ON t1.id = it1.tagFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk + LEFT JOIN itemProposal ip ON ip.mateFk = i.id + AND ip.itemFk = vSelf + LEFT JOIN itemTag it ON it.itemFk = i.id + AND it.priority = vPriority + LEFT JOIN tag t ON t.id = it.tagFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + AND lb.warehouse_id = vWarehouseFk LEFT JOIN buy b ON b.id = lb.buy_id - LEFT JOIN itemShelvingStock iss ON iss.itemFk = i.id AND iss.warehouseFk = vWarehouseFk + LEFT JOIN itemShelvingStock iss ON iss.itemFk = i.id + AND iss.warehouseFk = vWarehouseFk WHERE a.calc_id = vCalcFk - AND available > 0 - AND IF(vShowType,i.typeFk = vTypeFk,true) - AND i.id != vItemFk - ORDER BY counter DESC, - (t1.name = vTag1 COLLATE utf8_general_ci) DESC, - (it1.value = vValue1 COLLATE utf8_general_ci) DESC, - (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, - (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, - (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, - (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, - (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, - (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, - (i.value8 = vValue8 COLLATE utf8_general_ci) DESC; - + AND a.available > 0 + AND IF(vShowType, i.typeFk = vTypeFk, TRUE) + AND i.id <> vSelf + ORDER BY `counter` DESC, + (t.name = vTag1) DESC, + (it.value = vValue1) DESC, + (i.tag5 = vTag5) DESC, + match5 DESC, + (i.tag6 = vTag6) DESC, + match6 DESC, + (i.tag7 = vTag7) DESC, + match7 DESC, + (i.tag8 = vTag8) DESC, + match8 DESC; END$$ DELIMITER ; From 950d7a24612e95f01a156e2ec63b1ee33859b14a Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 5 Mar 2024 12:48:39 +0100 Subject: [PATCH 140/150] refactor: refs #6874 Changed params item_getSimilar --- db/routines/vn/procedures/item_getSimilar.sql | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 2522280f7..e87e77819 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -1,7 +1,8 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getSimilar`( vSelf INT, - vTicketFk INT, + vWarehouseFk INT, + vDated DATE, vShowType BOOL ) BEGIN @@ -10,11 +11,10 @@ BEGIN * de veces usado y segun sus caracteristicas. * * @param vSelf Id de artículo -* @param vTicketFk Id de ticket +* @param vWarehouseFk Id de almacen +* @param vDated Fecha * @param vShowType Mostrar tipos */ - DECLARE vWarehouseFk INT; - DECLARE vShipped DATE; DECLARE vCalcFk INT; DECLARE vTypeFk INT; DECLARE vPriority INT DEFAULT 1; @@ -31,11 +31,6 @@ BEGIN DECLARE vValue7 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue8 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - SELECT warehouseFk, shipped - INTO vWarehouseFk, vShipped - FROM ticket - WHERE id = vTicketFk; - SELECT typeFk, tag5, value5, @@ -64,7 +59,7 @@ BEGIN LEFT JOIN tag t ON t.id = it.tagFk WHERE i.id = vSelf; - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); SELECT i.id itemFk, i.longName, From 9c14836bc7301c7171cefdd0c9374136f3d2d252 Mon Sep 17 00:00:00 2001 From: Pako Date: Tue, 5 Mar 2024 13:18:13 +0100 Subject: [PATCH 141/150] BlueMonkey --- db/routines/vn/procedures/sale_getBoxPickingList.sql | 4 +--- db/versions/10929-orangeAnthurium/00-firstScript.sql | 2 ++ 2 files changed, 3 insertions(+), 3 deletions(-) create mode 100644 db/versions/10929-orangeAnthurium/00-firstScript.sql diff --git a/db/routines/vn/procedures/sale_getBoxPickingList.sql b/db/routines/vn/procedures/sale_getBoxPickingList.sql index 0af23e945..ff0e85259 100644 --- a/db/routines/vn/procedures/sale_getBoxPickingList.sql +++ b/db/routines/vn/procedures/sale_getBoxPickingList.sql @@ -27,7 +27,7 @@ BEGIN s.quantity, MAKETIME(pb.HH,pb.mm,0) etd, pb.routeFk, - FLOOR(s.quantity / ish.packing) stickers, + FLOOR(s.quantity / IF(i.isBoxPickingMode, ish.packing, i.packingOut)) stickers, IF(i.isBoxPickingMode, ish.packing, i.packingOut) packing, b.packagingFk FROM sale s @@ -71,5 +71,3 @@ BEGIN DROP TEMPORARY TABLE tmp.sale; END$$ DELIMITER ; - -CALL `vn`.`sale_getBoxPickingList`(1, curdate()); \ No newline at end of file diff --git a/db/versions/10929-orangeAnthurium/00-firstScript.sql b/db/versions/10929-orangeAnthurium/00-firstScript.sql new file mode 100644 index 000000000..299ac63c7 --- /dev/null +++ b/db/versions/10929-orangeAnthurium/00-firstScript.sql @@ -0,0 +1,2 @@ +-- Place your SQL code here +ALTER TABLE dipole.expedition_PrintOut MODIFY COLUMN street varchar(42) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT ' ' NOT NULL; \ No newline at end of file From f601c12468edb74cc81e9741baa0717ab855359a Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 5 Mar 2024 15:02:09 +0100 Subject: [PATCH 142/150] refactor: refs #6948 Requested changes --- db/routines/sage/procedures/accountingMovements_add.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/sage/procedures/accountingMovements_add.sql b/db/routines/sage/procedures/accountingMovements_add.sql index ffb20c3ee..575c63f6c 100644 --- a/db/routines/sage/procedures/accountingMovements_add.sql +++ b/db/routines/sage/procedures/accountingMovements_add.sql @@ -253,7 +253,7 @@ BEGIN LIMIT 10000000000000000000 ) sub GROUP BY ASIEN )sub2 ON sub2.ASIEN = x.ASIEN - LEFT JOIN ( SELECT DISTINCT(account),cu.code + LEFT JOIN ( SELECT DISTINCT(a.account),cu.code FROM vn.accounting a JOIN vn.currency cu ON cu.id = a.currencyFk WHERE cu.code <> 'EUR' -- no se informa cuando la divisa en EUR From d397980efb791b979bb41a0a79204c5c9980b67f Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 5 Mar 2024 16:10:56 +0100 Subject: [PATCH 143/150] refs #6607 feat:[checking boxes] --- db/routines/vn/procedures/sale_getFromTicketOrCollection.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql b/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql index 39c82d4ca..5308bdd28 100644 --- a/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql +++ b/db/routines/vn/procedures/sale_getFromTicketOrCollection.sql @@ -79,7 +79,7 @@ DECLARE vIsCollection BOOL; IF(SUM(iss.quantity) IS NULL, 0, SUM(iss.quantity)) pickedQuantity, MIN(iss.created) picked, IF(sm.id, TRUE, FALSE) hasMistake, - sg.sectorFk + sg.sectorFk, b.packing, b.grouping, o.code From 117e550bf2cf49eda2314667bf8924f4e019efa4 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 6 Mar 2024 08:58:30 +0100 Subject: [PATCH 144/150] refs #6990 hotFix: puppeteer cluster --- print/package.json | 1 + print/pnpm-lock.yaml | 135 ++++++++++++++++++++++++++++++------------- 2 files changed, 95 insertions(+), 41 deletions(-) diff --git a/print/package.json b/print/package.json index 8a01312b0..2adb7f1e0 100755 --- a/print/package.json +++ b/print/package.json @@ -22,6 +22,7 @@ "log4js": "^6.7.0", "mysql2": "^1.7.0", "nodemailer": "^4.7.0", + "puppeteer": "^22.4.0", "puppeteer-cluster": "^0.23.0", "qrcode": "^1.4.2", "strftime": "^0.10.0", diff --git a/print/pnpm-lock.yaml b/print/pnpm-lock.yaml index ddf00f08d..185dd89de 100644 --- a/print/pnpm-lock.yaml +++ b/print/pnpm-lock.yaml @@ -32,9 +32,12 @@ dependencies: nodemailer: specifier: ^4.7.0 version: 4.7.0 + puppeteer: + specifier: ^22.4.0 + version: 22.4.0 puppeteer-cluster: specifier: ^0.23.0 - version: 0.23.0(puppeteer@21.10.0) + version: 0.23.0(puppeteer@22.4.0) qrcode: specifier: ^1.4.2 version: 1.5.3 @@ -100,16 +103,17 @@ packages: to-fast-properties: 2.0.0 dev: false - /@puppeteer/browsers@1.9.1: - resolution: {integrity: sha512-PuvK6xZzGhKPvlx3fpfdM2kYY3P/hB1URtK8wA7XUJ6prn6pp22zvJHu48th0SGcHL9SutbPHrFuQgfXTFobWA==} - engines: {node: '>=16.3.0'} + /@puppeteer/browsers@2.1.0: + resolution: {integrity: sha512-xloWvocjvryHdUjDam/ZuGMh7zn4Sn3ZAaV4Ah2e2EwEt90N3XphZlSsU3n0VDc1F7kggCjMuH0UuxfPQ5mD9w==} + engines: {node: '>=18'} hasBin: true dependencies: debug: 4.3.4 extract-zip: 2.0.1 progress: 2.0.3 - proxy-agent: 6.3.1 - tar-fs: 3.0.4 + proxy-agent: 6.4.0 + semver: 7.6.0 + tar-fs: 3.0.5 unbzip2-stream: 1.4.3 yargs: 17.7.2 transitivePeerDependencies: @@ -243,6 +247,37 @@ packages: resolution: {integrity: sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw==} dev: false + /bare-events@2.2.1: + resolution: {integrity: sha512-9GYPpsPFvrWBkelIhOhTWtkeZxVxZOdb3VnFTCzlOo3OjvmTvzLoZFUT8kNFACx0vJej6QPney1Cf9BvzCNE/A==} + requiresBuild: true + dev: false + optional: true + + /bare-fs@2.2.1: + resolution: {integrity: sha512-+CjmZANQDFZWy4PGbVdmALIwmt33aJg8qTkVjClU6X4WmZkTPBDxRHiBn7fpqEWEfF3AC2io++erpViAIQbSjg==} + requiresBuild: true + dependencies: + bare-events: 2.2.1 + bare-os: 2.2.0 + bare-path: 2.1.0 + streamx: 2.15.6 + dev: false + optional: true + + /bare-os@2.2.0: + resolution: {integrity: sha512-hD0rOPfYWOMpVirTACt4/nK8mC55La12K5fY1ij8HAdfQakD62M+H4o4tpfKzVGLgRDTuk3vjA4GqGXXCeFbag==} + requiresBuild: true + dev: false + optional: true + + /bare-path@2.1.0: + resolution: {integrity: sha512-DIIg7ts8bdRKwJRJrUMy/PICEaQZaPGZ26lsSx9MJSwIhSrcdHn7/C8W+XmnG/rKi6BaRcz+JO00CjZteybDtw==} + requiresBuild: true + dependencies: + bare-os: 2.2.0 + dev: false + optional: true + /base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} dev: false @@ -326,12 +361,12 @@ packages: lodash.some: 4.6.0 dev: false - /chromium-bidi@0.5.6(devtools-protocol@0.0.1232444): - resolution: {integrity: sha512-ber8smgoAs4EqSUHRb0I8fpx371ZmvsdQav8HRM9oO4fk5Ox16vQiNYXlsZkRj4FfvVL2dCef+zBFQixp+79CA==} + /chromium-bidi@0.5.12(devtools-protocol@0.0.1249869): + resolution: {integrity: sha512-sZMgEBWKbupD0Q7lyFu8AWkrE+rs5ycE12jFkGwIgD/VS8lDPtelPlXM7LYaq4zrkZ/O2L3f4afHUHL0ICdKog==} peerDependencies: devtools-protocol: '*' dependencies: - devtools-protocol: 0.0.1232444 + devtools-protocol: 0.0.1249869 mitt: 3.0.1 urlpattern-polyfill: 10.0.0 dev: false @@ -545,8 +580,8 @@ packages: resolution: {integrity: sha512-3NdhDuEXnfun/z7x9GOElY49LoqVHoGScmOKwmxhsS8N5Y+Z8KyPPDnaSzqWgYt/ji4mqwfTS34Htrk0zPIXVg==} dev: false - /devtools-protocol@0.0.1232444: - resolution: {integrity: sha512-pM27vqEfxSxRkTMnF+XCmxSEb6duO5R+t8A9DEEJgy4Wz2RVanje2mmj99B6A3zv2r/qGfYlOvYznUhuokizmg==} + /devtools-protocol@0.0.1249869: + resolution: {integrity: sha512-Ctp4hInA0BEavlUoRy9mhGq0i+JSo/AwVyX2EFgZmV1kYB+Zq+EMBAn52QWu6FbRr10hRb6pBl420upbp4++vg==} dev: false /dijkstrajs@1.0.3: @@ -968,8 +1003,8 @@ packages: statuses: 1.3.1 dev: false - /http-proxy-agent@7.0.0: - resolution: {integrity: sha512-+ZT+iBxVUQ1asugqnD6oWoRiS25AkjNfG085dKJGtGxkdwLQrMKU5wJr2bOOFAXzKcTuqq+7fZlTMgG3SRfIYQ==} + /http-proxy-agent@7.0.2: + resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} engines: {node: '>= 14'} dependencies: agent-base: 7.1.0 @@ -987,8 +1022,8 @@ packages: sshpk: 1.18.0 dev: false - /https-proxy-agent@7.0.2: - resolution: {integrity: sha512-NmLNjm6ucYwtcUmL7JQC1ZQ57LmHP4lT15FQ8D61nak1rO6DH+fz5qNK2Ap5UN4ZapYICE3/0KodcLYSPsPbaA==} + /https-proxy-agent@7.0.4: + resolution: {integrity: sha512-wlwpilI7YdjSkWaQ/7omYBMTliDcmCN8OLihO6I9B86g06lMyAoqgoDpV0XqoaPOKj+0DIdAvnsWfyAAhmimcg==} engines: {node: '>= 14'} dependencies: agent-base: 7.1.0 @@ -1258,6 +1293,13 @@ packages: yallist: 3.1.1 dev: false + /lru-cache@6.0.0: + resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} + engines: {node: '>=10'} + dependencies: + yallist: 4.0.0 + dev: false + /lru-cache@7.18.3: resolution: {integrity: sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==} engines: {node: '>=12'} @@ -1308,10 +1350,6 @@ packages: resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==} dev: false - /mkdirp-classic@0.5.3: - resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} - dev: false - /ms@0.7.1: resolution: {integrity: sha512-lRLiIR9fSNpnP6TC4v8+4OU7oStC01esuNowdQ34L+Gk8e5Puoc88IqJ+XAY/B3Mn2ZKis8l8HX90oU8ivzUHg==} dev: false @@ -1432,8 +1470,8 @@ packages: agent-base: 7.1.0 debug: 4.3.4 get-uri: 6.0.2 - http-proxy-agent: 7.0.0 - https-proxy-agent: 7.0.2 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.4 pac-resolver: 7.0.0 socks-proxy-agent: 8.0.2 transitivePeerDependencies: @@ -1536,14 +1574,14 @@ packages: ipaddr.js: 1.4.0 dev: false - /proxy-agent@6.3.1: - resolution: {integrity: sha512-Rb5RVBy1iyqOtNl15Cw/llpeLH8bsb37gM1FUfKQ+Wck6xHlbAhWGUFiTRHtkjqGTA5pSHz6+0hrPW/oECihPQ==} + /proxy-agent@6.4.0: + resolution: {integrity: sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==} engines: {node: '>= 14'} dependencies: agent-base: 7.1.0 debug: 4.3.4 - http-proxy-agent: 7.0.0 - https-proxy-agent: 7.0.2 + http-proxy-agent: 7.0.2 + https-proxy-agent: 7.0.4 lru-cache: 7.18.3 pac-proxy-agent: 7.0.1 proxy-from-env: 1.1.0 @@ -1572,26 +1610,26 @@ packages: engines: {node: '>=6'} dev: false - /puppeteer-cluster@0.23.0(puppeteer@21.10.0): + /puppeteer-cluster@0.23.0(puppeteer@22.4.0): resolution: {integrity: sha512-108terIWDzPrQopmoYSPd5yDoy3FGJ2dNnoGMkGYPs6xtkdhgaECwpfZkzaRToMQPZibUOz0/dSSGgPEdXEhkQ==} peerDependencies: puppeteer: '>=1.5.0' dependencies: debug: 4.3.4 - puppeteer: 21.10.0 + puppeteer: 22.4.0 transitivePeerDependencies: - supports-color dev: false - /puppeteer-core@21.10.0: - resolution: {integrity: sha512-NVaqO3K462qwMuLO4Gurs/Mau1Wss+08QgNYzF0dIqZWMvpskrt/TbxbmHU+7zMTUOvPEq/lR4BLJmjMBgBGfQ==} - engines: {node: '>=16.13.2'} + /puppeteer-core@22.4.0: + resolution: {integrity: sha512-MZttAbttrxi6O/B//rY6zQihjFe/vXeCLb5YvKH2xG6yrcVESo0Hc5/Cv49omwZyZzAJ1BK8BnDeatDsj+3hMw==} + engines: {node: '>=18'} dependencies: - '@puppeteer/browsers': 1.9.1 - chromium-bidi: 0.5.6(devtools-protocol@0.0.1232444) + '@puppeteer/browsers': 2.1.0 + chromium-bidi: 0.5.12(devtools-protocol@0.0.1249869) cross-fetch: 4.0.0 debug: 4.3.4 - devtools-protocol: 0.0.1232444 + devtools-protocol: 0.0.1249869 ws: 8.16.0 transitivePeerDependencies: - bufferutil @@ -1600,15 +1638,15 @@ packages: - utf-8-validate dev: false - /puppeteer@21.10.0: - resolution: {integrity: sha512-Y1yQjcLE00hHTDAmv3M3A6hhW0Ytjdp6xr6nyjl7FZ7E7hzp/6Rsw80FbaTJzJHFCplBNi082wrgynbmD7RlYw==} - engines: {node: '>=16.13.2'} + /puppeteer@22.4.0: + resolution: {integrity: sha512-tR+JsDbA2qD1DqRX4F9k9SxQhk6UzcaCN+Qux7+WrDceS7wcR7tlFmMNB8+g8zE4Fmr/iRTOtf5wNnTW9cGUFQ==} + engines: {node: '>=18'} hasBin: true requiresBuild: true dependencies: - '@puppeteer/browsers': 1.9.1 + '@puppeteer/browsers': 2.1.0 cosmiconfig: 9.0.0 - puppeteer-core: 21.10.0 + puppeteer-core: 22.4.0 transitivePeerDependencies: - bufferutil - encoding @@ -1640,6 +1678,7 @@ packages: /queue-tick@1.0.1: resolution: {integrity: sha512-kJt5qhMxoszgU/62PLP1CJytzd2NKetjSRnyuj31fDd3Rlcz3fzlFdFLD1SItunPwyqEOkca6GbV612BWfaBag==} + requiresBuild: true dev: false /randombytes@2.1.0: @@ -1729,6 +1768,14 @@ packages: hasBin: true dev: false + /semver@7.6.0: + resolution: {integrity: sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==} + engines: {node: '>=10'} + hasBin: true + dependencies: + lru-cache: 6.0.0 + dev: false + /send@0.14.1: resolution: {integrity: sha512-1Ru269QpUVUgD32Y9jdyBXiX+pHYuYnTzR17w+DhyOWvGMPjJILrnLhl9c4LQjtIy2BSAa6Ykq0ZdGcAjaXlwQ==} engines: {node: '>= 0.8.0'} @@ -1950,12 +1997,14 @@ packages: engines: {node: '>= 0.4'} dev: false - /tar-fs@3.0.4: - resolution: {integrity: sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==} + /tar-fs@3.0.5: + resolution: {integrity: sha512-JOgGAmZyMgbqpLwct7ZV8VzkEB6pxXFBVErLtb+XCOqzc6w1xiWKI9GVd6bwk68EX7eJ4DWmfXVmq8K2ziZTGg==} dependencies: - mkdirp-classic: 0.5.3 pump: 3.0.0 tar-stream: 3.1.7 + optionalDependencies: + bare-fs: 2.2.1 + bare-path: 2.1.0 dev: false /tar-stream@3.1.7: @@ -2200,6 +2249,10 @@ packages: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} dev: false + /yallist@4.0.0: + resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} + dev: false + /yargs-parser@18.1.3: resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==} engines: {node: '>=6'} From 8b32a19233e04c61e6e248227708c4623d6c0f86 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 6 Mar 2024 09:01:08 +0100 Subject: [PATCH 145/150] fix: puppeteer --- Jenkinsfile | 1 - 1 file changed, 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 9ca7f5d19..821316c87 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -71,7 +71,6 @@ pipeline { stage('Back') { steps { sh 'pnpm install --prefer-offline' - sh 'pnpx puppeteer browsers install chrome' } } stage('Print') { From 492c6f4dd6aa596f2e2b10b0c96c1604fee3e2f7 Mon Sep 17 00:00:00 2001 From: ivanm Date: Wed, 6 Mar 2024 12:50:44 +0100 Subject: [PATCH 146/150] refs #6969 test --- db/routines/vn/procedures/buyUltimateFromInterval.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db/routines/vn/procedures/buyUltimateFromInterval.sql b/db/routines/vn/procedures/buyUltimateFromInterval.sql index f78174482..e264b500d 100644 --- a/db/routines/vn/procedures/buyUltimateFromInterval.sql +++ b/db/routines/vn/procedures/buyUltimateFromInterval.sql @@ -43,6 +43,7 @@ BEGIN LIMIT 10000000000000000000) sub GROUP BY itemFk, warehouseFk; + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) SELECT b.itemFk, From c81749da78e6878afa400e35dfd22312a04a39ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 6 Mar 2024 16:38:34 +0100 Subject: [PATCH 147/150] feat: add column department.pbxQueue refs #6387 --- db/versions/10940-aquaLilium/00-firstScript.sql | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 db/versions/10940-aquaLilium/00-firstScript.sql diff --git a/db/versions/10940-aquaLilium/00-firstScript.sql b/db/versions/10940-aquaLilium/00-firstScript.sql new file mode 100644 index 000000000..fb4fa33ff --- /dev/null +++ b/db/versions/10940-aquaLilium/00-firstScript.sql @@ -0,0 +1,8 @@ + + ALTER TABLE vn.department + ADD COLUMN pbxQueue varchar(128) CHARACTER + SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL NULL; + + ALTER TABLE vn.department + ADD CONSTRAINT department_queue_FK + FOREIGN KEY (pbxQueue) REFERENCES pbx.queue(name) ON DELETE RESTRICT ON UPDATE CASCADE; From a59d45b28c2ab93dfcb6e6a923131ef9d5b80a90 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 7 Mar 2024 07:26:31 +0100 Subject: [PATCH 148/150] refs #6990 hotFix: puppeteer cluster --- package.json | 2 +- pnpm-lock.yaml | 2 +- print/package.json | 64 +++++++++++++++++++++++----------------------- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/package.json b/package.json index 302738524..6956cabeb 100644 --- a/package.json +++ b/package.json @@ -42,7 +42,7 @@ "mysql": "2.18.1", "node-ssh": "^11.0.0", "object.pick": "^1.3.0", - "puppeteer": "^21.11.0", + "puppeteer": "21.11.0", "read-chunk": "^3.2.0", "require-yaml": "0.0.1", "smbhash": "0.0.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3e335c06c..b1f68378d 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -93,7 +93,7 @@ dependencies: specifier: ^1.3.0 version: 1.3.0 puppeteer: - specifier: ^21.11.0 + specifier: 21.11.0 version: 21.11.0 read-chunk: specifier: ^3.2.0 diff --git a/print/package.json b/print/package.json index 2adb7f1e0..408990706 100755 --- a/print/package.json +++ b/print/package.json @@ -1,34 +1,34 @@ { - "name": "vn-print", - "version": "2.0.0", - "description": "Print service", - "scripts": { - "start": "node server/server.js", - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "https://git.verdnatura.es/salix" - }, - "license": "GPL-3.0", - "packageManager": "pnpm@8.15.1", - "dependencies": { - "express": "4.14.0", - "fs-extra": "^7.0.1", - "intl": "^1.2.5", - "js-yaml": "^3.13.1", - "jsbarcode": "^3.11.5", - "juice": "^5.2.0", - "log4js": "^6.7.0", - "mysql2": "^1.7.0", - "nodemailer": "^4.7.0", - "puppeteer": "^22.4.0", - "puppeteer-cluster": "^0.23.0", - "qrcode": "^1.4.2", - "strftime": "^0.10.0", - "vue": "^2.6.10", - "vue-i18n": "^8.15.0", - "vue-server-renderer": "^2.6.10", - "xmldom": "^0.6.0" - } + "name": "vn-print", + "version": "2.0.0", + "description": "Print service", + "scripts": { + "start": "node server/server.js", + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://git.verdnatura.es/salix" + }, + "license": "GPL-3.0", + "packageManager": "pnpm@8.15.1", + "dependencies": { + "express": "4.14.0", + "fs-extra": "^7.0.1", + "intl": "^1.2.5", + "js-yaml": "^3.13.1", + "jsbarcode": "^3.11.5", + "juice": "^5.2.0", + "log4js": "^6.7.0", + "mysql2": "^1.7.0", + "nodemailer": "^4.7.0", + "puppeteer": "22.4.0", + "puppeteer-cluster": "0.23.0", + "qrcode": "^1.4.2", + "strftime": "^0.10.0", + "vue": "^2.6.10", + "vue-i18n": "^8.15.0", + "vue-server-renderer": "^2.6.10", + "xmldom": "^0.6.0" + } } From e127457ed6deb0252f4d33d79987c6de6974b23f Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 7 Mar 2024 07:27:18 +0100 Subject: [PATCH 149/150] refs #6990 hotFix: puppeteer cluster --- print/pnpm-lock.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/print/pnpm-lock.yaml b/print/pnpm-lock.yaml index 185dd89de..5f0b8cd02 100644 --- a/print/pnpm-lock.yaml +++ b/print/pnpm-lock.yaml @@ -33,10 +33,10 @@ dependencies: specifier: ^4.7.0 version: 4.7.0 puppeteer: - specifier: ^22.4.0 + specifier: 22.4.0 version: 22.4.0 puppeteer-cluster: - specifier: ^0.23.0 + specifier: 0.23.0 version: 0.23.0(puppeteer@22.4.0) qrcode: specifier: ^1.4.2 From 702792ace09e9e6605141a802a92d83717a71b76 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 7 Mar 2024 07:28:55 +0100 Subject: [PATCH 150/150] refs #6990 hotFix: puppeteer cluster --- print/package.json | 2 +- print/pnpm-lock.yaml | 119 +++++++++++++------------------------------ 2 files changed, 36 insertions(+), 85 deletions(-) diff --git a/print/package.json b/print/package.json index 408990706..ea0e37f99 100755 --- a/print/package.json +++ b/print/package.json @@ -22,7 +22,7 @@ "log4js": "^6.7.0", "mysql2": "^1.7.0", "nodemailer": "^4.7.0", - "puppeteer": "22.4.0", + "puppeteer": "21.11.0", "puppeteer-cluster": "0.23.0", "qrcode": "^1.4.2", "strftime": "^0.10.0", diff --git a/print/pnpm-lock.yaml b/print/pnpm-lock.yaml index 5f0b8cd02..13b2fe827 100644 --- a/print/pnpm-lock.yaml +++ b/print/pnpm-lock.yaml @@ -33,11 +33,11 @@ dependencies: specifier: ^4.7.0 version: 4.7.0 puppeteer: - specifier: 22.4.0 - version: 22.4.0 + specifier: 21.11.0 + version: 21.11.0 puppeteer-cluster: specifier: 0.23.0 - version: 0.23.0(puppeteer@22.4.0) + version: 0.23.0(puppeteer@21.11.0) qrcode: specifier: ^1.4.2 version: 1.5.3 @@ -103,17 +103,16 @@ packages: to-fast-properties: 2.0.0 dev: false - /@puppeteer/browsers@2.1.0: - resolution: {integrity: sha512-xloWvocjvryHdUjDam/ZuGMh7zn4Sn3ZAaV4Ah2e2EwEt90N3XphZlSsU3n0VDc1F7kggCjMuH0UuxfPQ5mD9w==} - engines: {node: '>=18'} + /@puppeteer/browsers@1.9.1: + resolution: {integrity: sha512-PuvK6xZzGhKPvlx3fpfdM2kYY3P/hB1URtK8wA7XUJ6prn6pp22zvJHu48th0SGcHL9SutbPHrFuQgfXTFobWA==} + engines: {node: '>=16.3.0'} hasBin: true dependencies: debug: 4.3.4 extract-zip: 2.0.1 progress: 2.0.3 - proxy-agent: 6.4.0 - semver: 7.6.0 - tar-fs: 3.0.5 + proxy-agent: 6.3.1 + tar-fs: 3.0.4 unbzip2-stream: 1.4.3 yargs: 17.7.2 transitivePeerDependencies: @@ -247,37 +246,6 @@ packages: resolution: {integrity: sha512-fpWrvyVHEKyeEvbKZTVOeZF3VSKKWtJxFIxX/jaVPf+cLbGUSitjb49pHLqPV2BUNNZ0LcoeEGfE/YCpyDYHIw==} dev: false - /bare-events@2.2.1: - resolution: {integrity: sha512-9GYPpsPFvrWBkelIhOhTWtkeZxVxZOdb3VnFTCzlOo3OjvmTvzLoZFUT8kNFACx0vJej6QPney1Cf9BvzCNE/A==} - requiresBuild: true - dev: false - optional: true - - /bare-fs@2.2.1: - resolution: {integrity: sha512-+CjmZANQDFZWy4PGbVdmALIwmt33aJg8qTkVjClU6X4WmZkTPBDxRHiBn7fpqEWEfF3AC2io++erpViAIQbSjg==} - requiresBuild: true - dependencies: - bare-events: 2.2.1 - bare-os: 2.2.0 - bare-path: 2.1.0 - streamx: 2.15.6 - dev: false - optional: true - - /bare-os@2.2.0: - resolution: {integrity: sha512-hD0rOPfYWOMpVirTACt4/nK8mC55La12K5fY1ij8HAdfQakD62M+H4o4tpfKzVGLgRDTuk3vjA4GqGXXCeFbag==} - requiresBuild: true - dev: false - optional: true - - /bare-path@2.1.0: - resolution: {integrity: sha512-DIIg7ts8bdRKwJRJrUMy/PICEaQZaPGZ26lsSx9MJSwIhSrcdHn7/C8W+XmnG/rKi6BaRcz+JO00CjZteybDtw==} - requiresBuild: true - dependencies: - bare-os: 2.2.0 - dev: false - optional: true - /base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} dev: false @@ -361,12 +329,12 @@ packages: lodash.some: 4.6.0 dev: false - /chromium-bidi@0.5.12(devtools-protocol@0.0.1249869): - resolution: {integrity: sha512-sZMgEBWKbupD0Q7lyFu8AWkrE+rs5ycE12jFkGwIgD/VS8lDPtelPlXM7LYaq4zrkZ/O2L3f4afHUHL0ICdKog==} + /chromium-bidi@0.5.8(devtools-protocol@0.0.1232444): + resolution: {integrity: sha512-blqh+1cEQbHBKmok3rVJkBlBxt9beKBgOsxbFgs7UJcoVbbeZ+K7+6liAsjgpc8l1Xd55cQUy14fXZdGSb4zIw==} peerDependencies: devtools-protocol: '*' dependencies: - devtools-protocol: 0.0.1249869 + devtools-protocol: 0.0.1232444 mitt: 3.0.1 urlpattern-polyfill: 10.0.0 dev: false @@ -580,8 +548,8 @@ packages: resolution: {integrity: sha512-3NdhDuEXnfun/z7x9GOElY49LoqVHoGScmOKwmxhsS8N5Y+Z8KyPPDnaSzqWgYt/ji4mqwfTS34Htrk0zPIXVg==} dev: false - /devtools-protocol@0.0.1249869: - resolution: {integrity: sha512-Ctp4hInA0BEavlUoRy9mhGq0i+JSo/AwVyX2EFgZmV1kYB+Zq+EMBAn52QWu6FbRr10hRb6pBl420upbp4++vg==} + /devtools-protocol@0.0.1232444: + resolution: {integrity: sha512-pM27vqEfxSxRkTMnF+XCmxSEb6duO5R+t8A9DEEJgy4Wz2RVanje2mmj99B6A3zv2r/qGfYlOvYznUhuokizmg==} dev: false /dijkstrajs@1.0.3: @@ -1293,13 +1261,6 @@ packages: yallist: 3.1.1 dev: false - /lru-cache@6.0.0: - resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==} - engines: {node: '>=10'} - dependencies: - yallist: 4.0.0 - dev: false - /lru-cache@7.18.3: resolution: {integrity: sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==} engines: {node: '>=12'} @@ -1350,6 +1311,10 @@ packages: resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==} dev: false + /mkdirp-classic@0.5.3: + resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} + dev: false + /ms@0.7.1: resolution: {integrity: sha512-lRLiIR9fSNpnP6TC4v8+4OU7oStC01esuNowdQ34L+Gk8e5Puoc88IqJ+XAY/B3Mn2ZKis8l8HX90oU8ivzUHg==} dev: false @@ -1574,8 +1539,8 @@ packages: ipaddr.js: 1.4.0 dev: false - /proxy-agent@6.4.0: - resolution: {integrity: sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==} + /proxy-agent@6.3.1: + resolution: {integrity: sha512-Rb5RVBy1iyqOtNl15Cw/llpeLH8bsb37gM1FUfKQ+Wck6xHlbAhWGUFiTRHtkjqGTA5pSHz6+0hrPW/oECihPQ==} engines: {node: '>= 14'} dependencies: agent-base: 7.1.0 @@ -1610,26 +1575,26 @@ packages: engines: {node: '>=6'} dev: false - /puppeteer-cluster@0.23.0(puppeteer@22.4.0): + /puppeteer-cluster@0.23.0(puppeteer@21.11.0): resolution: {integrity: sha512-108terIWDzPrQopmoYSPd5yDoy3FGJ2dNnoGMkGYPs6xtkdhgaECwpfZkzaRToMQPZibUOz0/dSSGgPEdXEhkQ==} peerDependencies: puppeteer: '>=1.5.0' dependencies: debug: 4.3.4 - puppeteer: 22.4.0 + puppeteer: 21.11.0 transitivePeerDependencies: - supports-color dev: false - /puppeteer-core@22.4.0: - resolution: {integrity: sha512-MZttAbttrxi6O/B//rY6zQihjFe/vXeCLb5YvKH2xG6yrcVESo0Hc5/Cv49omwZyZzAJ1BK8BnDeatDsj+3hMw==} - engines: {node: '>=18'} + /puppeteer-core@21.11.0: + resolution: {integrity: sha512-ArbnyA3U5SGHokEvkfWjW+O8hOxV1RSJxOgriX/3A4xZRqixt9ZFHD0yPgZQF05Qj0oAqi8H/7stDorjoHY90Q==} + engines: {node: '>=16.13.2'} dependencies: - '@puppeteer/browsers': 2.1.0 - chromium-bidi: 0.5.12(devtools-protocol@0.0.1249869) + '@puppeteer/browsers': 1.9.1 + chromium-bidi: 0.5.8(devtools-protocol@0.0.1232444) cross-fetch: 4.0.0 debug: 4.3.4 - devtools-protocol: 0.0.1249869 + devtools-protocol: 0.0.1232444 ws: 8.16.0 transitivePeerDependencies: - bufferutil @@ -1638,15 +1603,15 @@ packages: - utf-8-validate dev: false - /puppeteer@22.4.0: - resolution: {integrity: sha512-tR+JsDbA2qD1DqRX4F9k9SxQhk6UzcaCN+Qux7+WrDceS7wcR7tlFmMNB8+g8zE4Fmr/iRTOtf5wNnTW9cGUFQ==} - engines: {node: '>=18'} + /puppeteer@21.11.0: + resolution: {integrity: sha512-9jTHuYe22TD3sNxy0nEIzC7ZrlRnDgeX3xPkbS7PnbdwYjl2o/z/YuCrRBwezdKpbTDTJ4VqIggzNyeRcKq3cg==} + engines: {node: '>=16.13.2'} hasBin: true requiresBuild: true dependencies: - '@puppeteer/browsers': 2.1.0 + '@puppeteer/browsers': 1.9.1 cosmiconfig: 9.0.0 - puppeteer-core: 22.4.0 + puppeteer-core: 21.11.0 transitivePeerDependencies: - bufferutil - encoding @@ -1768,14 +1733,6 @@ packages: hasBin: true dev: false - /semver@7.6.0: - resolution: {integrity: sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==} - engines: {node: '>=10'} - hasBin: true - dependencies: - lru-cache: 6.0.0 - dev: false - /send@0.14.1: resolution: {integrity: sha512-1Ru269QpUVUgD32Y9jdyBXiX+pHYuYnTzR17w+DhyOWvGMPjJILrnLhl9c4LQjtIy2BSAa6Ykq0ZdGcAjaXlwQ==} engines: {node: '>= 0.8.0'} @@ -1997,14 +1954,12 @@ packages: engines: {node: '>= 0.4'} dev: false - /tar-fs@3.0.5: - resolution: {integrity: sha512-JOgGAmZyMgbqpLwct7ZV8VzkEB6pxXFBVErLtb+XCOqzc6w1xiWKI9GVd6bwk68EX7eJ4DWmfXVmq8K2ziZTGg==} + /tar-fs@3.0.4: + resolution: {integrity: sha512-5AFQU8b9qLfZCX9zp2duONhPmZv0hGYiBPJsyUdqMjzq/mqVpy/rEUSeHk1+YitmxugaptgBh5oDGU3VsAJq4w==} dependencies: + mkdirp-classic: 0.5.3 pump: 3.0.0 tar-stream: 3.1.7 - optionalDependencies: - bare-fs: 2.2.1 - bare-path: 2.1.0 dev: false /tar-stream@3.1.7: @@ -2249,10 +2204,6 @@ packages: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} dev: false - /yallist@4.0.0: - resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==} - dev: false - /yargs-parser@18.1.3: resolution: {integrity: sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==} engines: {node: '>=6'}