From 7f563f99bbe3254b5d2170b98618e1d52a4e241c Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 31 Jan 2024 07:11:03 +0100 Subject: [PATCH 001/413] refs #5890 feat:reserves --- .../vn/events/itemShelvingSale_doReserve.sql | 8 + .../collection_addWithReservation.sql | 87 +++++++ .../vn/procedures/collection_getAssigned.sql | 77 ++++++ .../itemShelvingSale_addByCollection.sql | 51 ++++ .../procedures/itemShelvingSale_addBySale.sql | 100 +++++++ .../procedures/itemShelvingSale_doReserve.sql | 52 ++++ .../itemShelvingSale_setQuantity.sql | 244 +++++++++--------- .../itemShelvingSale_setSaleGroup.sql | 34 +++ .../procedures/itemShelvingSale_unpicked.sql | 60 +++++ .../vn/procedures/itemShelvingTransfer.sql | 89 ++++--- .../vn/procedures/itemShelving_add.sql | 125 +++++---- .../vn/triggers/itemShelving_AFTER_INSERT.sql | 27 ++ .../vn/triggers/itemShelving_AFTER_UPDATE.sql | 16 ++ .../triggers/itemShelving_BEFORE_INSERT.sql | 10 + db/versions/10852-pinkOak/00-firstScript.sql | 23 ++ 15 files changed, 777 insertions(+), 226 deletions(-) create mode 100644 db/routines/vn/events/itemShelvingSale_doReserve.sql create mode 100644 db/routines/vn/procedures/collection_addWithReservation.sql create mode 100644 db/routines/vn/procedures/collection_getAssigned.sql create mode 100644 db/routines/vn/procedures/itemShelvingSale_addByCollection.sql create mode 100644 db/routines/vn/procedures/itemShelvingSale_addBySale.sql create mode 100644 db/routines/vn/procedures/itemShelvingSale_doReserve.sql create mode 100644 db/routines/vn/procedures/itemShelvingSale_setSaleGroup.sql create mode 100644 db/routines/vn/procedures/itemShelvingSale_unpicked.sql create mode 100644 db/routines/vn/triggers/itemShelving_AFTER_INSERT.sql create mode 100644 db/routines/vn/triggers/itemShelving_AFTER_UPDATE.sql create mode 100644 db/routines/vn/triggers/itemShelving_BEFORE_INSERT.sql create mode 100644 db/versions/10852-pinkOak/00-firstScript.sql diff --git a/db/routines/vn/events/itemShelvingSale_doReserve.sql b/db/routines/vn/events/itemShelvingSale_doReserve.sql new file mode 100644 index 000000000..228886556 --- /dev/null +++ b/db/routines/vn/events/itemShelvingSale_doReserve.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`itemShelvingSale_doReserve` + ON SCHEDULE EVERY 15 SECOND + STARTS '2023-10-16 00:00:00' + ON COMPLETION PRESERVE + ENABLE +DO CALL vn.itemShelvingSale_doReserve$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/collection_addWithReservation.sql b/db/routines/vn/procedures/collection_addWithReservation.sql new file mode 100644 index 000000000..ea2632b05 --- /dev/null +++ b/db/routines/vn/procedures/collection_addWithReservation.sql @@ -0,0 +1,87 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_addWithReservation`( + vItemFk INT, + vQuantity INT, + vTicketFk INT +) +BEGIN +/** + * En el ámbito de las colecciones se añade una línea de sale a un ticket + * de una colección en caso de tener disponible y se realiza la reserva. + * + * @param vItemFk id of item + * @param vQuantity quantity to be added to the ticket + * @param vTicketFk ticket to which the sales line is added + */ + DECLARE vWarehouseFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vAvailable INT; + DECLARE vSaleFk INT; + DECLARE vConcept VARCHAR(50); + DECLARE vItemName VARCHAR(50); + DECLARE vHasThrow BOOLEAN DEFAULT FALSE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT t.warehouseFk INTO vWarehouseFk + FROM ticket t + JOIN ticketCollection tc ON tc.ticketFk = t.id + WHERE t.id = vTicketFk; + + CALL cache.available_refresh( + vCacheAvailableFk, + FALSE, + vWarehouseFk, + util.VN_CURDATE()); + + SELECT available INTO vAvailable + FROM cache.available + WHERE calc_id = vCacheAvailableFk + AND item_id = vItemFk; + + IF vAvailable < vQuantity THEN + SET vHasThrow = TRUE; + SELECT vAvailable, vQuantity; + ELSE + START TRANSACTION; + + SELECT `name`, + CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) + INTO vItemName, vConcept + FROM item + WHERE id = vItemFk; + + INSERT INTO ticketLog + SET originFk = vTicketFk, + userFk = getUser(), + `action` = 'update', + `description` = CONCAT('Añadido articulo ', vItemName, ' cantidad:', vQuantity); + + INSERT INTO sale + SET itemFk = vItemFk, + ticketFk = vTicketFk, + concept = vConcept, + quantity = vQuantity, + isAdded = TRUE; + + SELECT LAST_INSERT_ID() INTO vSaleFk; + + CALL sale_calculateComponent(vSaleFk, NULL); + CALL itemShelvingSale_addBySale(vSaleFk); + + IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN + SET vHasThrow = TRUE; + END IF; + END IF; + + IF vHasThrow THEN + CALL util.throw("No hay disponibilidad para el artículo seleccionado"); + ELSE + COMMIT; + END IF; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/collection_getAssigned.sql b/db/routines/vn/procedures/collection_getAssigned.sql new file mode 100644 index 000000000..dead563ac --- /dev/null +++ b/db/routines/vn/procedures/collection_getAssigned.sql @@ -0,0 +1,77 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_getAssigned`( + vUserFk INT, + OUT vCollectionFk INT) +proc:BEGIN +/* Comprueba si existen colecciones libres que se ajustan al perfil del usuario + * y le asigna la más antigua. + * Añade un registro al semillero de colecciones y hace la reserva para la colección + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + DECLARE vLockTime INT DEFAULT 15; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 + INTO vHasTooMuchCollections + FROM tCollection + JOIN productionConfig pc ; + + DROP TEMPORARY TABLE tCollection; + + IF vHasTooMuchCollections THEN + CALL util.throw('Hay colecciones pendientes'); + LEAVE proc; + END IF; + + IF NOT GET_LOCK('collection_getAssigned', vLockTime) THEN + LEAVE proc; + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN state s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c + FROM collection c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed + SET userFk = vUserFk; + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM collection c + JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk + OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE collection + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + CALL itemShelvingSale_addByCollection(vCollectionFk); + + DO RELEASE_LOCK('collection_getAssigned'); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql b/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql new file mode 100644 index 000000000..4e57fed0b --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql @@ -0,0 +1,51 @@ + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addByCollection`( + vCollectionFk INT(11) +) +BEGIN +/** + * Guarda la ubicación para el contenido de una colección + * + * @param vCollectionFk Identificador de collection + */ + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + WITH sales AS ( + SELECT s.id saleFk, s.quantity, SUM(IFNULL(iss.quantity, 0)) quantityReserved + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + WHERE tc.collectionFk = vCollectionFk + GROUP BY s.id + HAVING quantity <> quantityReserved + ), trackedSales AS ( + SELECT sa.saleFk + FROM sales sa + JOIN vn.saleTracking st ON st.saleFk = sa.saleFk + JOIN vn.`state` s ON s.id = st.stateFk + WHERE st.isChecked + AND s.semaphore = 1 + GROUP BY sa.saleFk + ) SELECT s.saleFk + FROM sales s + LEFT JOIN trackedSales ts ON ts.saleFk = s.saleFk + WHERE ts.saleFk IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql new file mode 100644 index 000000000..3ad581b15 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql @@ -0,0 +1,100 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addBySale`( + vSaleFk INT +) +proc: BEGIN +/** + * Reserva una línea de venta en la ubicación más óptima + * + * @param vSaleFk Id de sale + * @param vItemShelvingSaleFk Id de reserva + */ + DECLARE vLastPickingOrder INT; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vItemShelvingFk INT; + DECLARE vAvailable INT; + DECLARE vReservedQuantity INT; + DECLARE vOutStanding INT; + DECLARE vUserFk INT; + + DECLARE vItemShelvingAvailable CURSOR FOR + SELECT ish.id itemShelvingFk, + ish.available + FROM sale s + JOIN itemShelving ish ON ish.itemFk = s.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector sc ON sc.id = p.sectorFk + JOIN productionConfig pc + WHERE s.id = vSaleFk + AND NOT sc.isHideForPickers + ORDER BY s.id, + p.pickingOrder >= vLastPickingOrder, + sh.priority DESC, + ish.available >= s.quantity DESC, + s.quantity MOD ish.grouping = 0 DESC, + ish.grouping DESC, + IF(pc.orderMode = 'Location', p.pickingOrder, ish.created); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; +/* DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; +*/ + SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)) + INTO vLastPickingOrder, vOutStanding + FROM sale s + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = sh.parkingFk + WHERE s.id = vSaleFk; + + IF vOutStanding <= 0 THEN + LEAVE proc; + END IF; + + SELECT getUser() INTO vUserFk; + + OPEN vItemShelvingAvailable; + l: LOOP + SET vDone = FALSE; + FETCH vItemShelvingAvailable INTO vItemShelvingFk, vAvailable; + + IF vOutStanding <= 0 OR vDone THEN + LEAVE l; + END IF; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + SELECT LEAST(vOutStanding, vAvailable) INTO vReservedQuantity; + SET vOutStanding = vOutStanding - vReservedQuantity; + + IF vReservedQuantity > 0 THEN + -- START TRANSACTION; + + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk) + SELECT vItemShelvingFk, + vSaleFk, + vReservedQuantity, + vUserFk; + + UPDATE itemShelving + SET available = available - vReservedQuantity + WHERE id = vItemShelvingFk; + + -- COMMIT; + END IF; + END LOOP; + CLOSE vItemShelvingAvailable; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_doReserve.sql b/db/routines/vn/procedures/itemShelvingSale_doReserve.sql new file mode 100644 index 000000000..d7bf4b181 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_doReserve.sql @@ -0,0 +1,52 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_doReserve`() +proc: BEGIN +/** + * Genera reservas de la tabla itemShelvingSaleReserv + */ + DECLARE vDone BOOL; + DECLARE vSaleFk INT; + + DECLARE vSales CURSOR FOR + SELECT DISTINCT saleFk FROM tSale; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); + ROLLBACK; + RESIGNAL; + END; + + IF !GET_LOCK('vn.itemShelvingSale_doReserve', 0) THEN + LEAVE proc; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tSale + ENGINE = MEMORY + SELECT id, saleFk FROM itemShelvingSaleReserv; + + OPEN vSales; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + CALL itemShelvingSale_addBySale (vSaleFk); + END LOOP; + + CLOSE vSales; + + DELETE iss FROM itemShelvingSaleReserv iss JOIN tSale s ON s.id = iss.id; + + DROP TEMPORARY TABLE tSale; + + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index b792534fb..13b8a16ad 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -1,118 +1,126 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setQuantity`( - vItemShelvingSaleFk INT(10), - vQuantity DECIMAL(10,0), - vIsItemShelvingSaleEmpty BOOLEAN -) -BEGIN -/** - * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity - * en vn.itemShelvingSale y vn.sale.isPicked en caso necesario. - * Si la reserva de la ubicación es fallida, se regulariza la situación - * - * @param vItemShelvingSaleFk Id itemShelvingSaleFK - * @param vQuantity Cantidad real que se ha cogido de la ubicación - * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha - * quedado vacio tras el movimiento - */ - DECLARE vSaleFk INT; - DECLARE vCursorSaleFk INT; - DECLARE vItemShelvingFk INT; - DECLARE vReservedQuantity INT; - DECLARE vRemainingQuantity INT; - DECLARE vItemFk INT; - DECLARE vUserFk INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE vSales CURSOR FOR - SELECT iss.saleFk, iss.userFk - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND s.itemFk = vItemFk - AND NOT iss.isPicked; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN - CALL util.throw('Booking completed'); - END IF; - - SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk - INTO vItemFk, vSaleFk, vItemShelvingFk - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND NOT iss.isPicked; - - UPDATE itemShelvingSale - SET isPicked = TRUE, - quantity = vQuantity - WHERE id = vItemShelvingSaleFk; - - UPDATE itemShelving - SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity)) - WHERE id = vItemShelvingFk; - - IF vIsItemShelvingSaleEmpty THEN - OPEN vSales; -l: LOOP - SET vDone = FALSE; - FETCH vSales INTO vCursorSaleFk, vUserFk; - IF vDone THEN - LEAVE l; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk, userFk)) - ENGINE = MEMORY - SELECT vCursorSaleFk, vUserFk; - - CALL itemShelvingSale_reserveWhitUser(); - DROP TEMPORARY TABLE tmp.sale; - - END LOOP; - CLOSE vSales; - - DELETE iss - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND s.itemFk = vItemFk - AND NOT iss.isPicked; - END IF; - - SELECT SUM(quantity) INTO vRemainingQuantity - FROM itemShelvingSale - WHERE saleFk = vSaleFk - AND NOT isPicked; - - IF vRemainingQuantity THEN - CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL); - - SELECT SUM(quantity) INTO vRemainingQuantity - FROM itemShelvingSale - WHERE saleFk = vSaleFk - AND NOT isPicked; - - IF NOT vRemainingQuantity <=> 0 THEN - SELECT SUM(iss.quantity) - INTO vReservedQuantity - FROM itemShelvingSale iss - WHERE iss.saleFk = vSaleFk; - - CALL saleTracking_new( - vSaleFk, - TRUE, - vReservedQuantity, - `account`.`myUser_getId`(), - NULL, - 'PREPARED', - TRUE); - - UPDATE sale s - SET s.quantity = vReservedQuantity - WHERE s.id = vSaleFk ; - END IF; - END IF; -END$$ -DELIMITER ; +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN +) +BEGIN +/** + * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity + * en itemShelvingSale y sale.isPicked en caso necesario. + * Si la reserva de la ubicación es fallida, se regulariza la situación + * + * @param vItemShelvingSaleFk Id itemShelvingSaleFK + * @param vQuantity Cantidad real que se ha cogido de la ubicación + * @param vIsItemShelvingSaleEmpty determina si la ubicación itemShelvingSale se ha + * quedado vacio tras el movimiento + */ + DECLARE vSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vTotalQuantity INT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN + CALL util.throw('Reserva completada'); + END IF; + + SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk, SUM(IFNULL(iss.quantity,0)) + INTO vItemFk, vSaleFk, vItemShelvingFk, vReservedQuantity + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + IF vQuantity > vReservedQuantity + OR (vQuantity < vReservedQuantity AND + (NOT vIsItemShelvingSaleEmpty OR vIsItemShelvingSaleEmpty IS NULL)) + OR (vIsItemShelvingSaleEmpty IS NOT NULL AND vQuantity = vReservedQuantity) THEN + CALL util.throw('La cantidad no puede distinta a la reserva'); + END IF; + + + START TRANSACTION; + + + UPDATE itemShelvingSale + SET isPicked = TRUE, + quantity = vQuantity + WHERE id = vItemShelvingSaleFk; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + AND FALSE + FOR UPDATE; + + UPDATE itemShelving + SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0, visible - vQuantity)) + WHERE id = vItemShelvingFk; + + COMMIT; + + IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN + + UPDATE itemShelving + SET visible = 0, + available = 0 + WHERE id = vItemShelvingFk + AND itemFk = vItemFk; + + CALL itemShelvingSale_addBySale(vSaleFk); + + START TRANSACTION; + + INSERT INTO itemShelvingSaleReserv (saleFk) + SELECT DISTINCT iss.saleFk + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + + DELETE iss + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + COMMIT; + + CALL itemShelvingSale_doReserve(); + END IF; + + SELECT SUM(IF(isPicked, 0, quantity)), SUM(quantity) + INTO vRemainingQuantity, vTotalQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk; + + IF vRemainingQuantity = 0 THEN + START TRANSACTION; + + CALL saleTracking_new( + vSaleFk, + TRUE, + vTotalQuantity, + `account`.`myUser_getId`(), + NULL, + 'PREPARED', + TRUE); + + UPDATE sale s + SET s.quantity = vTotalQuantity, + isPicked = TRUE + WHERE s.id = vSaleFk; + + COMMIT; + END IF; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_setSaleGroup.sql b/db/routines/vn/procedures/itemShelvingSale_setSaleGroup.sql new file mode 100644 index 000000000..911034ed1 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_setSaleGroup.sql @@ -0,0 +1,34 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setSaleGroup`( + vSaleGroupFk INT(10) +) +BEGIN +/** + * Gestiona la reserva de un vn.saleGroup actualizando vn.itemShelvingSale.isPicked + * y cambiando el estado de la vn.sale + * + * @param vSaleGroupFk Id saleGroupFk + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF NOT (SELECT COUNT(*) FROM saleGroup WHERE id = vSaleGroupFk) THEN + CALL util.throw('Sale group not exists'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + JOIN saleGroupDetail sg ON sg.saleFk = s.id + SET iss.isPicked = TRUE + WHERE sg.saleGroupFk = vSaleGroupFk; + + CALL saleTracking_addPreparedSaleGroup(vSaleGroupFk); + + COMMIT; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_unpicked.sql b/db/routines/vn/procedures/itemShelvingSale_unpicked.sql new file mode 100644 index 000000000..6813a65b1 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_unpicked.sql @@ -0,0 +1,60 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_unpicked`( + vSelf INT(11) +) +BEGIN +/** + * Desmarca una línea que ya estaba sacada, devolviendo la cantidad al itemShelving + * + * @param vSelf Identificador del itemShelvingSale + */ + DECLARE vSaleFk INT; + DECLARE vReservedQuantity INT; + DECLARE vIsSaleGroup BOOL; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT NOT isPicked FROM itemShelvingSale WHERE id = vSelf) THEN + CALL util.throw('Reserva no completada'); + END IF; + + SELECT ish.saleFk, ish.quantity, IF(sg.id, TRUE, FALSE) + INTO vSaleFk, vReservedQuantity, vIsSaleGroup + FROM itemShelvingSale ish + LEFT JOIN saleGroupDetail sg ON sg.saleFk = ish.saleFk + WHERE ish.id = vSelf; + + IF vIsSaleGroup THEN + CALL util.throw('Can not unpicked a sale group'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = FALSE + WHERE id = vSelf; + + UPDATE sale s + JOIN itemShelvingSale ish ON ish.saleFk = s.id + SET s.isPicked = FALSE + WHERE ish.id = vSelf; + + UPDATE itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + SET ish.visible = ish.visible + iss.quantity + WHERE iss.id = vSelf; + + CALL saleTracking_new( + vSaleFk, + FALSE, + vReservedQuantity, + `account`.`myUser_getId`(), + NULL, + 'ON_PREPARATION', + TRUE); + COMMIT; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingTransfer.sql b/db/routines/vn/procedures/itemShelvingTransfer.sql index 326f8108b..2a6f9fef1 100644 --- a/db/routines/vn/procedures/itemShelvingTransfer.sql +++ b/db/routines/vn/procedures/itemShelvingTransfer.sql @@ -1,45 +1,44 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingTransfer`(vItemShelvingFk INT, vShelvingFk VARCHAR(3)) -BEGIN -/** - * Transfiere producto de una ubicación a otra, fusionando si coincide el - * packing y la fecha. - * - * @param vItemShelvingFk Identificador de itemShelving - * @param vShelvingFk Identificador de shelving - */ - DECLARE vNewItemShelvingFk INT DEFAULT 0; - - SELECT MAX(ish.id) - INTO vNewItemShelvingFk - FROM itemShelving ish - JOIN ( - SELECT - itemFk, - packing, - created - FROM itemShelving - WHERE id = vItemShelvingFk - ) ish2 - ON ish2.itemFk = ish.itemFk - AND ish2.packing = ish.packing - AND date(ish2.created) = date(ish.created) - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; - - IF vNewItemShelvingFk THEN - UPDATE itemShelving ish - JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk - SET ish.visible = ish.visible + ish2.visible - WHERE ish.id = vNewItemShelvingFk; - - DELETE FROM itemShelving - WHERE id = vItemShelvingFk; - ELSE - UPDATE itemShelving - SET shelvingFk = vShelvingFk - WHERE id = vItemShelvingFk; - END IF; - - SELECT true; -END$$ -DELIMITER ; +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingTransfer`( + vItemShelvingFk INT, + vShelvingFk VARCHAR(3)) +BEGIN +/** + * Transfiere producto de una ubicación a otra, fusionando si coincide el + * packing y la fecha. + * + * @param vItemShelvingFk Identificador de itemShelving + * @param vShelvingFk Identificador de shelving + */ + DECLARE vNewItemShelvingFk INT DEFAULT 0; + + SELECT MAX(ish.id) + INTO vNewItemShelvingFk + FROM itemShelving ish + JOIN ( + SELECT itemFk, + packing, + created + FROM itemShelving + WHERE id = vItemShelvingFk + ) ish2 ON ish2.itemFk = ish.itemFk + AND ish2.packing = ish.packing + AND DATE(ish2.created) = DATE(ish.created) + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; + + IF vNewItemShelvingFk THEN + UPDATE itemShelving ish + JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk + SET ish.visible = ish.visible + ish2.visible + WHERE ish.id = vNewItemShelvingFk; + + DELETE FROM itemShelving + WHERE id = vItemShelvingFk; + ELSE + UPDATE itemShelving + SET shelvingFk = vShelvingFk + WHERE id = vItemShelvingFk; + END IF; + SELECT true; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelving_add.sql b/db/routines/vn/procedures/itemShelving_add.sql index 02762fa0b..9bfce27ea 100644 --- a/db/routines/vn/procedures/itemShelving_add.sql +++ b/db/routines/vn/procedures/itemShelving_add.sql @@ -1,63 +1,62 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) -BEGIN - - -/** - * Añade registro o lo actualiza si ya existe. - * - * @param vShelvingFk matrícula del carro - * @param vBarcode el id del registro - * @param vQuantity indica la cantidad del producto - * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra - * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra - * @param vPacking el packing del producto, NULL para coger el de la ultima compra - * @param vWarehouseFk indica el sector - * - **/ - - DECLARE vItemFk INT; - - SELECT barcodeToItem(vBarcode) INTO vItemFk; - - IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN - - INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); - INSERT INTO shelving(code, parkingFk) - SELECT vShelvingFk, id - FROM parking - WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; - - END IF; - - IF (SELECT COUNT(*) FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk - AND packing = vPacking) = 1 THEN - - UPDATE itemShelving - SET visible = visible+vQuantity - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; - - ELSE - CALL cache.last_buy_refresh(FALSE); - INSERT INTO itemShelving( itemFk, - shelvingFk, - visible, - grouping, - packing, - packagingFk) - - SELECT vItemFk, - vShelvingFk, - vQuantity, - IFNULL(vGrouping, b.grouping), - IFNULL(vPacking, b.packing), - IFNULL(vPackagingFk, b.packagingFk) - FROM item i - LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id - WHERE i.id = vItemFk; - END IF; -END$$ -DELIMITER ; +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) +BEGIN +/** + * Añade registro o lo actualiza si ya existe. + * + * @param vShelvingFk matrícula del carro + * @param vBarcode el id del registro + * @param vQuantity indica la cantidad del producto + * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra + * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra + * @param vPacking el packing del producto, NULL para coger el de la ultima compra + * @param vWarehouseFk indica el sector + * + **/ + + DECLARE vItemFk INT; + + SELECT barcodeToItem(vBarcode) INTO vItemFk; + + IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN + + INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); + INSERT INTO shelving(code, parkingFk) + SELECT vShelvingFk, id + FROM parking + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + IF (SELECT COUNT(*) FROM itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking) = 1 THEN + + UPDATE itemShelving + SET visible = visible + vQuantity + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + + ELSE + CALL cache.last_buy_refresh(FALSE); + INSERT INTO itemShelving( itemFk, + shelvingFk, + visible, + grouping, + packing, + packagingFk) + + SELECT vItemFk, + vShelvingFk, + vQuantity, + IFNULL(vGrouping, b.grouping), + IFNULL(vPacking, b.packing), + IFNULL(vPackagingFk, b.packagingFk), + vQuantity + FROM item i + LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk + LEFT JOIN buy b ON b.id = lb.buy_id + WHERE i.id = vItemFk; + END IF; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/itemShelving_AFTER_INSERT.sql b/db/routines/vn/triggers/itemShelving_AFTER_INSERT.sql new file mode 100644 index 000000000..784a736ec --- /dev/null +++ b/db/routines/vn/triggers/itemShelving_AFTER_INSERT.sql @@ -0,0 +1,27 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_AFTER_INSERT` + AFTER INSERT ON `itemShelving` + FOR EACH ROW +BEGIN + + INSERT INTO vn.itemShelvingLog( + itemShelvingFk, + workerFk, + accion, + itemFk, + shelvingFk, + visible, + `grouping`, + packing, + available) + VALUES( NEW.id, + NEW.userFk, + 'CREA REGISTRO', + NEW.itemFk, + NEW.shelvingFk, + NEW.visible, + NEW.`grouping`, + NEW.packing, + NEW.available); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/itemShelving_AFTER_UPDATE.sql b/db/routines/vn/triggers/itemShelving_AFTER_UPDATE.sql new file mode 100644 index 000000000..23ea14e85 --- /dev/null +++ b/db/routines/vn/triggers/itemShelving_AFTER_UPDATE.sql @@ -0,0 +1,16 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_AFTER_UPDATE` + AFTER UPDATE ON `itemShelving` + FOR EACH ROW +BEGIN + INSERT INTO itemShelvingLog + SET itemShelvingFk = NEW.id, + workerFk = account.myUser_getId(), + accion = 'CAMBIO', + itemFk = NEW.itemFk, + shelvingFk = NEW.shelvingFk, + visible = NEW.visible, + `grouping` = NEW.`grouping`, + packing = NEW.packing; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/itemShelving_BEFORE_INSERT.sql b/db/routines/vn/triggers/itemShelving_BEFORE_INSERT.sql new file mode 100644 index 000000000..0bed738d2 --- /dev/null +++ b/db/routines/vn/triggers/itemShelving_BEFORE_INSERT.sql @@ -0,0 +1,10 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_BEFORE_INSERT` + BEFORE INSERT ON `itemShelving` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); + SET NEW.userFk = account.myUser_getId(); + SET NEW.available = NEW.visible; +END$$ +DELIMITER ; diff --git a/db/versions/10852-pinkOak/00-firstScript.sql b/db/versions/10852-pinkOak/00-firstScript.sql new file mode 100644 index 000000000..3fd8f447b --- /dev/null +++ b/db/versions/10852-pinkOak/00-firstScript.sql @@ -0,0 +1,23 @@ +ALTER TABLE vn.itemShelvingSale DROP COLUMN IF EXISTS isPicked; + +ALTER TABLE vn.itemShelvingSale + ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; + +ALTER TABLE vn.productionConfig DROP COLUMN IF EXISTS orderMode; + +ALTER TABLE vn.productionConfig + ADD orderMode ENUM('Location', 'Age') NOT NULL DEFAULT 'Location'; + +ALTER TABLE vn.itemShelving DROP COLUMN IF EXISTS available; + +ALTER TABLE vn.itemShelving ADD available INT NULL; + +UPDATE vn.itemShelving SET available = visible; + +CREATE TABLE vn.itemShelvingSaleReserv ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `saleFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `itemShelvingSaleReserv_ibfk_1` (`saleFk`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci + COMMENT='Queue of changed itemShelvingSale to reserve'; -- 2.40.1 From 844bab3cc84e55b6884fc56a71b00502712080d7 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 6 Feb 2024 16:17:53 +0100 Subject: [PATCH 002/413] #refs 5890 feat:add assignCollection --- back/methods/collection/assignCollection.js | 29 ++++++++++++++ .../collection/spec/assignCollection.spec.js | 38 +++++++++++++++++++ back/models/collection.js | 1 + db/versions/10852-pinkOak/00-firstScript.sql | 5 +++ loopback/locale/es.json | 6 ++- 5 files changed, 77 insertions(+), 2 deletions(-) create mode 100644 back/methods/collection/assignCollection.js create mode 100644 back/methods/collection/spec/assignCollection.spec.js diff --git a/back/methods/collection/assignCollection.js b/back/methods/collection/assignCollection.js new file mode 100644 index 000000000..2ff37ab59 --- /dev/null +++ b/back/methods/collection/assignCollection.js @@ -0,0 +1,29 @@ +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'], + root: true + }, + }); + + Self.assignCollection = async(ctx, options) => { + const userId = ctx.req.accessToken.userId; + const myOptions = {userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const [info, info2, [{'@vCollectionFk': collectionFk}]] = await Self.rawSql( + 'CALL vn.collection_getAssigned(?, @vCollectionFk);SELECT @vCollectionFk', [userId], myOptions); + 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/collection/spec/assignCollection.spec.js b/back/methods/collection/spec/assignCollection.spec.js new file mode 100644 index 000000000..340bd6a93 --- /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'); + +fdescribe('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'); + } + }); +}); diff --git a/back/models/collection.js b/back/models/collection.js index 1c10d49fa..a0d34712f 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -4,4 +4,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/versions/10852-pinkOak/00-firstScript.sql b/db/versions/10852-pinkOak/00-firstScript.sql index 3fd8f447b..7af48148c 100644 --- a/db/versions/10852-pinkOak/00-firstScript.sql +++ b/db/versions/10852-pinkOak/00-firstScript.sql @@ -21,3 +21,8 @@ CREATE TABLE vn.itemShelvingSaleReserv ( KEY `itemShelvingSaleReserv_ibfk_1` (`saleFk`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed itemShelvingSale to reserve'; + +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + + ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 5c7dc41b6..394fca450 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -338,5 +338,7 @@ "The alias cant be modified": "Este alias de correo no puede ser modificado", "No tickets to invoice": "No hay tickets para facturar", "Name should be uppercase": "El nombre debe ir en mayúscula", - "An email is necessary": "Es necesario un email" -} + "An email is necessary": "Es necesario un email", + "printerNotExists": "printerNotExists", + "There are not picking tickets": "No hay tickets para sacar" +} \ No newline at end of file -- 2.40.1 From 3a6d4753dbf9ebb2484416049cfc3b56b66a7cc9 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 15 Feb 2024 12:48:17 +0100 Subject: [PATCH 003/413] feat: refs #5855 drop temporary table --- db/routines/bi/procedures/claim_ratio_routine.sql | 2 ++ .../cache/procedures/availableNoRaids_refresh.sql | 2 +- db/routines/cache/procedures/available_refresh.sql | 2 +- .../edi/procedures/floramondo_offerRefresh.sql | 11 ++++++----- db/routines/hedera/procedures/item_calcCatalog.sql | 3 ++- .../vn/procedures/copyComponentsFromSaleList.sql | 1 + db/routines/vn/procedures/itemShelvingRadar.sql | 2 +- db/routines/vn/procedures/itemShelving_inventory.sql | 2 ++ db/routines/vn/procedures/item_getMinacum.sql | 2 ++ db/routines/vn/procedures/productionSectorList.sql | 1 + db/routines/vn/procedures/ticket_DelayTruck.sql | 1 + db/routines/vn/procedures/ticket_add.sql | 2 ++ db/routines/vn/procedures/ticket_cloneWeekly.sql | 2 +- db/routines/vn/procedures/zone_getCollisions.sql | 3 ++- 14 files changed, 25 insertions(+), 11 deletions(-) diff --git a/db/routines/bi/procedures/claim_ratio_routine.sql b/db/routines/bi/procedures/claim_ratio_routine.sql index 10cb717cf..4ad028433 100644 --- a/db/routines/bi/procedures/claim_ratio_routine.sql +++ b/db/routines/bi/procedures/claim_ratio_routine.sql @@ -164,5 +164,7 @@ BEGIN ) sub SET cr.recobro = sub.recobro WHERE Id_Cliente IN ( 5189,8942); + + DROP TEMPORARY TABLE tmp.ticket_list; END$$ DELIMITER ; diff --git a/db/routines/cache/procedures/availableNoRaids_refresh.sql b/db/routines/cache/procedures/availableNoRaids_refresh.sql index 383e35436..37715d270 100644 --- a/db/routines/cache/procedures/availableNoRaids_refresh.sql +++ b/db/routines/cache/procedures/availableNoRaids_refresh.sql @@ -117,7 +117,7 @@ proc: BEGIN )sub GROUP BY sub.itemFk; - DROP TEMPORARY TABLE tmp.itemCalc, tItemRange; + DROP TEMPORARY TABLE tmp.itemCalc, tItemRange, tmp.itemList; CALL cache_calc_end (vCalc); END$$ DELIMITER ; diff --git a/db/routines/cache/procedures/available_refresh.sql b/db/routines/cache/procedures/available_refresh.sql index d0939e568..abf023a41 100644 --- a/db/routines/cache/procedures/available_refresh.sql +++ b/db/routines/cache/procedures/available_refresh.sql @@ -121,7 +121,7 @@ proc: BEGIN )sub GROUP BY sub.itemFk; - DROP TEMPORARY TABLE tmp.itemCalc, itemRange; + DROP TEMPORARY TABLE tmp.itemCalc, itemRange, tmp.itemList; CALL cache_calc_end (vCalc); END$$ DELIMITER ; diff --git a/db/routines/edi/procedures/floramondo_offerRefresh.sql b/db/routines/edi/procedures/floramondo_offerRefresh.sql index 26e09ebaf..6fdd1b3bb 100644 --- a/db/routines/edi/procedures/floramondo_offerRefresh.sql +++ b/db/routines/edi/procedures/floramondo_offerRefresh.sql @@ -1,5 +1,5 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`floramondo_offerRefresh`() +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`floramondo_offerRefresh`() proc: BEGIN DECLARE vLanded DATETIME; DECLARE vDone INT DEFAULT FALSE; @@ -484,7 +484,8 @@ proc: BEGIN DROP TEMPORARY TABLE edi.offer, - itemToInsert; + itemToInsert, + tmp.buyRecalc; SET @isTriggerDisabled = FALSE; @@ -518,5 +519,5 @@ proc: BEGIN fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); DO RELEASE_LOCK('edi.floramondo_offerRefresh'); -END$$ -DELIMITER ; +END$$ +DELIMITER ; diff --git a/db/routines/hedera/procedures/item_calcCatalog.sql b/db/routines/hedera/procedures/item_calcCatalog.sql index 81b3adf5a..6db11c034 100644 --- a/db/routines/hedera/procedures/item_calcCatalog.sql +++ b/db/routines/hedera/procedures/item_calcCatalog.sql @@ -30,6 +30,7 @@ BEGIN tmp.ticketComponentPrice, tmp.ticketComponent, tmp.ticketLot, - tmp.zoneGetShipped; + tmp.zoneGetShipped, + tmp.item; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/copyComponentsFromSaleList.sql b/db/routines/vn/procedures/copyComponentsFromSaleList.sql index 17cf487b1..13487af17 100644 --- a/db/routines/vn/procedures/copyComponentsFromSaleList.sql +++ b/db/routines/vn/procedures/copyComponentsFromSaleList.sql @@ -30,5 +30,6 @@ BEGIN JOIN tmp.saleList s ON s.saleFk = sc.saleFk JOIN tmp.newSaleList ns ON ns.orden = s.orden; + DROP TEMPORARY TABLE IF EXISTS tmp.newSaleList; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingRadar.sql b/db/routines/vn/procedures/itemShelvingRadar.sql index c89a190ae..db56c07a0 100644 --- a/db/routines/vn/procedures/itemShelvingRadar.sql +++ b/db/routines/vn/procedures/itemShelvingRadar.sql @@ -188,7 +188,7 @@ proc:BEGIN SELECT * FROM tmp.itemShelvingRadar; END IF; - DROP TEMPORARY TABLE tmp.itemShelvingRadar; + DROP TEMPORARY TABLE tmp.itemShelvingRadar, tmp.itemOutTime; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelving_inventory.sql b/db/routines/vn/procedures/itemShelving_inventory.sql index ce2934426..89adc0be4 100644 --- a/db/routines/vn/procedures/itemShelving_inventory.sql +++ b/db/routines/vn/procedures/itemShelving_inventory.sql @@ -58,5 +58,7 @@ BEGIN WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo AND p.sectorFk = vSectorFk ORDER BY p.pickingOrder; + + DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/item_getMinacum.sql b/db/routines/vn/procedures/item_getMinacum.sql index ed987637c..ddf2ae2c6 100644 --- a/db/routines/vn/procedures/item_getMinacum.sql +++ b/db/routines/vn/procedures/item_getMinacum.sql @@ -75,5 +75,7 @@ BEGIN i.quantity amount FROM tmp.itemAtp i HAVING amount != 0; + + DROP TEMPORARY TABLE tmp.itemAtp; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/productionSectorList.sql b/db/routines/vn/procedures/productionSectorList.sql index 5447f10d0..e1445ca52 100644 --- a/db/routines/vn/procedures/productionSectorList.sql +++ b/db/routines/vn/procedures/productionSectorList.sql @@ -104,5 +104,6 @@ BEGIN ) sub; DROP TEMPORARY TABLE tmp.whiteTicket; DROP TEMPORARY TABLE tmp.sectorTypeTicket; + DROP TEMPORARY TABLE tmp.productionBuffer; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_DelayTruck.sql b/db/routines/vn/procedures/ticket_DelayTruck.sql index 7a3170d68..20006fa65 100644 --- a/db/routines/vn/procedures/ticket_DelayTruck.sql +++ b/db/routines/vn/procedures/ticket_DelayTruck.sql @@ -30,5 +30,6 @@ BEGIN END LOOP; CLOSE cur1; + DROP TEMPORARY TABLE tmp.ticket, tmp.productionBuffer; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_add.sql b/db/routines/vn/procedures/ticket_add.sql index 5c3c28081..c85000218 100644 --- a/db/routines/vn/procedures/ticket_add.sql +++ b/db/routines/vn/procedures/ticket_add.sql @@ -65,6 +65,8 @@ BEGIN IF (vZoneFk IS NULL OR vZoneFk = 0) AND vIsRequiredZone THEN CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; END IF; INSERT INTO ticket ( diff --git a/db/routines/vn/procedures/ticket_cloneWeekly.sql b/db/routines/vn/procedures/ticket_cloneWeekly.sql index 6bceb2fdf..f9e8d2cb6 100644 --- a/db/routines/vn/procedures/ticket_cloneWeekly.sql +++ b/db/routines/vn/procedures/ticket_cloneWeekly.sql @@ -197,6 +197,6 @@ BEGIN END; END LOOP; CLOSE rsTicket; - DROP TEMPORARY TABLE IF EXISTS tmp.time; + DROP TEMPORARY TABLE IF EXISTS tmp.time, tmp.zoneGetLanded; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/zone_getCollisions.sql b/db/routines/vn/procedures/zone_getCollisions.sql index f6779e1b7..4f104eaad 100644 --- a/db/routines/vn/procedures/zone_getCollisions.sql +++ b/db/routines/vn/procedures/zone_getCollisions.sql @@ -120,6 +120,7 @@ BEGIN DROP TEMPORARY TABLE geoCollision, tmp.zone, - tmp.zoneNodes; + tmp.zoneNodes, + tmp.zoneOption; END$$ DELIMITER ; -- 2.40.1 From 93de845b6764da67a78386e2fc8496918884a740 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 16 Feb 2024 07:03:05 +0100 Subject: [PATCH 004/413] refs#5890 feat: delete trigger and modify getTickets --- back/methods/collection/getTickets.js | 2 +- .../vn/triggers/itemShelvingSale_afterInsert.sql | 12 ------------ 2 files changed, 1 insertion(+), 13 deletions(-) delete mode 100644 db/routines/vn/triggers/itemShelvingSale_afterInsert.sql diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 50117b954..fc77d4af3 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -68,7 +68,7 @@ module.exports = Self => { LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk LEFT JOIN parking p2 ON p2.id = sg.parkingFk JOIN item i ON i.id = s.itemFk - LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + JOIN itemShelvingSale iss ON iss.saleFk = s.id LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk LEFT JOIN shelving sh ON sh.code = ish.shelvingFk LEFT JOIN parking p ON p.id = sh.parkingFk diff --git a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql deleted file mode 100644 index 63ca893bd..000000000 --- a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql +++ /dev/null @@ -1,12 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelvingSale_afterInsert` - AFTER INSERT ON `itemShelvingSale` - FOR EACH ROW -BEGIN - - UPDATE vn.sale - SET isPicked = TRUE - WHERE id = NEW.saleFk; - -END$$ -DELIMITER ; -- 2.40.1 From c20747434e09fd7d5d8fedcf35a7f118fc25796f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 18 Mar 2024 17:51:35 +0100 Subject: [PATCH 005/413] feat: previas con sitema de reservas refs #6861 --- ...ShelvingSale_reserveBySectorCollection.sql | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql b/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql new file mode 100644 index 000000000..3ea351288 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql @@ -0,0 +1,26 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE + `vn`.`itemShelvingSale_reserveBySectorCollection`(vSectorCollectionFk INT(11)) +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una preparación previa + * de la cual ya tiene generada la asociación del saleGroup con sectorCollection + * + * @param vSectorCollectionFk Identificador de sectorCollection + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT s.id + FROM sectorCollectionSaleGroup sc + JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk + JOIN sale s ON sg.saleFk = s.id + JOIN saleTracking str ON str.saleFk = s.id + JOIN `state` st ON st.id = str.stateFk + AND st.code = 'PREVIOUS_PREPARATION' + WHERE sc.sectorCollectionFk = vSectorCollectionFk + AND str.workerFk = account.myUser_getId(); + + CALL itemShelvingSale_reserve(); +END$$ +DELIMITER ; -- 2.40.1 From bb86c27202878d487e86e7f07a7511cadf516fcc Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 20 Mar 2024 11:07:55 +0100 Subject: [PATCH 006/413] feat: refs #7116 create table agencyIncoming --- db/routines/bs/procedures/salesByItemTypeDay_add.sql | 2 +- db/versions/10960-silverRoebelini/00-firstScript.sql | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) create mode 100644 db/versions/10960-silverRoebelini/00-firstScript.sql diff --git a/db/routines/bs/procedures/salesByItemTypeDay_add.sql b/db/routines/bs/procedures/salesByItemTypeDay_add.sql index 5c12081a0..0f5c5c543 100644 --- a/db/routines/bs/procedures/salesByItemTypeDay_add.sql +++ b/db/routines/bs/procedures/salesByItemTypeDay_add.sql @@ -27,7 +27,7 @@ BEGIN JOIN vn.ticket t ON t.id = s.ticketFk WHERE ic.merchandise AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) - GROUP BY it.id, bs.dated; + GROUP BY i.id, bs.dated; INSERT INTO salesByItemTypeDay (itemTypeFk, dated, trash, faults) SELECT it.id itemTypeFk, diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql new file mode 100644 index 000000000..c72ce10a7 --- /dev/null +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -0,0 +1,11 @@ +-- Place your SQL code here +CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` varchar(50) DEFAULT NULL, + `description` varchar(50) DEFAULT NULL, + `isOrigin` tinyint(1) DEFAULT NULL, + PRIMARY KEY (`id`) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci; \ No newline at end of file -- 2.40.1 From 634bde1c9cf8efd49c2896d0f8c017482c20fcba Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 20 Mar 2024 11:10:06 +0100 Subject: [PATCH 007/413] refs #7116 --- db/routines/bs/procedures/salesByItemTypeDay_add.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/bs/procedures/salesByItemTypeDay_add.sql b/db/routines/bs/procedures/salesByItemTypeDay_add.sql index 0f5c5c543..5c12081a0 100644 --- a/db/routines/bs/procedures/salesByItemTypeDay_add.sql +++ b/db/routines/bs/procedures/salesByItemTypeDay_add.sql @@ -27,7 +27,7 @@ BEGIN JOIN vn.ticket t ON t.id = s.ticketFk WHERE ic.merchandise AND t.shipped BETWEEN vDateStart AND util.dayEnd(vDateEnd) - GROUP BY i.id, bs.dated; + GROUP BY it.id, bs.dated; INSERT INTO salesByItemTypeDay (itemTypeFk, dated, trash, faults) SELECT it.id itemTypeFk, -- 2.40.1 From f1e8f965b35475d3684b22d19b36abb45d449295 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 21 Mar 2024 11:59:45 +0100 Subject: [PATCH 008/413] refs #5890 itemShelving --- ...ShelvingSale_reserveBySectorCollection.sql | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql b/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql new file mode 100644 index 000000000..3510e774e --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql @@ -0,0 +1,26 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE + `vn`.`itemShelvingSale_reserveBySectorCollection`(vSectorCollectionFk INT(11)) +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una preparación previa + * de la cual ya tiene generada la asociación del saleGroup con sectorCollection + * + * @param vSectorCollectionFk Identificador de sectorCollection + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT s.id + FROM sectorCollectionSaleGroup sc + JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk + JOIN sale s ON sg.saleFk = s.id + JOIN saleTracking str ON str.saleFk = s.id + JOIN `state` st ON st.id = str.stateFk + AND st.code = 'PREVIOUS_PREPARATION' + WHERE sc.sectorCollectionFk = vSectorCollectionFk + AND str.workerFk = account.myUser_getId(); + + CALL itemShelvingSale_reserve(); +END$$ +DELIMITER ; \ No newline at end of file -- 2.40.1 From f18d61d17dab66359471710d6529c808fbff647b Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 21 Mar 2024 17:28:08 +0100 Subject: [PATCH 009/413] refs #5890 fix: dev --- back/methods/url/getUrl.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/url/getUrl.js b/back/methods/url/getUrl.js index ef741e5a0..8a86ba579 100644 --- a/back/methods/url/getUrl.js +++ b/back/methods/url/getUrl.js @@ -22,7 +22,7 @@ module.exports = Self => { const {url} = await Self.app.models.Url.findOne({ where: { appName, - environment: process.env.NODE_ENV || 'development' + environment: process.env.NODE_ENV || 'dev' } }); return url; -- 2.40.1 From a5d262671d5c23624d3fb2031daccb4e313dbad1 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 29 Mar 2024 22:19:23 +0100 Subject: [PATCH 010/413] refs #6436 feat: extend BeforeAll --- back/tests-helper.js | 14 ++++++++++++-- back/tests.js | 3 +-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/back/tests-helper.js b/back/tests-helper.js index b88fa1fd6..e4878c4a2 100644 --- a/back/tests-helper.js +++ b/back/tests-helper.js @@ -10,7 +10,7 @@ async function init() { host: process.env.DB_HOST, port: process.env.DB_PORT }); - + customBeforeAll(); const bootOptions = {dataSources}; await new Promise((resolve, reject) => { app.boot(bootOptions, @@ -24,7 +24,16 @@ async function deinit() { console.log('Stopping backend.'); await app.disconnect(); } - +function customBeforeAll() { + Object.assign(beforeAll, { + ctx: { + req: { + accessToken: {userId: 9}, + headers: {origin: 'http://localhost'}, + } + } + }); +} module.exports = { init, deinit @@ -32,3 +41,4 @@ module.exports = { if (require.main === module) init(); + diff --git a/back/tests.js b/back/tests.js index 50698eb92..f446b3483 100644 --- a/back/tests.js +++ b/back/tests.js @@ -84,13 +84,12 @@ async function test() { 'loopback/**/*[sS]pec.js', 'modules/*/back/**/*.[sS]pec.js' ], - helpers: [] + helpers: [`back/tests-helper.js`] }; if (PARALLEL) { const ParallelRunner = require('jasmine/parallel'); runner = new ParallelRunner({numWorkers: 1}); - config.helpers.push(`back/tests-helper.js`); } else { const Jasmine = require('jasmine'); runner = new Jasmine(); -- 2.40.1 From 48cc499f379e1b6645ae24292b4f44de9c643132 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 29 Mar 2024 22:19:36 +0100 Subject: [PATCH 011/413] refs #6436 perf: example to use --- back/methods/collection/spec/getSales.spec.js | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/back/methods/collection/spec/getSales.spec.js b/back/methods/collection/spec/getSales.spec.js index e6205cc79..f276d07d0 100644 --- a/back/methods/collection/spec/getSales.spec.js +++ b/back/methods/collection/spec/getSales.spec.js @@ -4,15 +4,7 @@ describe('collection getSales()', () => { const collectionOrTicketFk = 999999; const print = true; const source = 'CHECKER'; - - beforeAll(() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'}, - } - }; - }); + const {ctx} = beforeAll; it('should return a collection with tickets, placements and barcodes settled correctly', async() => { const tx = await models.Collection.beginTransaction({}); -- 2.40.1 From cb55740b68cdfc26948ff38de166fb8ad79fa9c6 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 1 Apr 2024 10:57:53 +0200 Subject: [PATCH 012/413] refs #6436 rollback --- back/tests-helper.js | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/back/tests-helper.js b/back/tests-helper.js index e4878c4a2..97554ae0d 100644 --- a/back/tests-helper.js +++ b/back/tests-helper.js @@ -10,7 +10,6 @@ async function init() { host: process.env.DB_HOST, port: process.env.DB_PORT }); - customBeforeAll(); const bootOptions = {dataSources}; await new Promise((resolve, reject) => { app.boot(bootOptions, @@ -24,16 +23,7 @@ async function deinit() { console.log('Stopping backend.'); await app.disconnect(); } -function customBeforeAll() { - Object.assign(beforeAll, { - ctx: { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'}, - } - } - }); -} + module.exports = { init, deinit -- 2.40.1 From d6ee5d571e6712f050533427946b91a7d92b6a7f Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 1 Apr 2024 10:58:04 +0200 Subject: [PATCH 013/413] refs #6436 feat: jasmine helper --- back/tests.js | 3 ++- back/vn-jasmine.js | 48 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) create mode 100644 back/vn-jasmine.js diff --git a/back/tests.js b/back/tests.js index f446b3483..2e89cfd05 100644 --- a/back/tests.js +++ b/back/tests.js @@ -84,12 +84,13 @@ async function test() { 'loopback/**/*[sS]pec.js', 'modules/*/back/**/*.[sS]pec.js' ], - helpers: [`back/tests-helper.js`] + helpers: [`back/vn-jasmine.js`] }; if (PARALLEL) { const ParallelRunner = require('jasmine/parallel'); runner = new ParallelRunner({numWorkers: 1}); + config.helpers.push(`back/tests-helper.js`); } else { const Jasmine = require('jasmine'); runner = new Jasmine(); diff --git a/back/vn-jasmine.js b/back/vn-jasmine.js new file mode 100644 index 000000000..88dc55dc0 --- /dev/null +++ b/back/vn-jasmine.js @@ -0,0 +1,48 @@ + +const LoopBackContext = require('loopback-context'); +const DEFAULT_ACCESS_TOKEN = {accessToken: {userId: 9}}; +const DEFAULT_HEADERS = {headers: {origin: 'http://localhost'}}; +const DEFAULT_BEFORE_ALL = { + ctx: { + req: { + ...DEFAULT_ACCESS_TOKEN, + ...DEFAULT_HEADERS + + }, + args: {} + } +}; +const DEFAULT_LOOPBACK_CTX = { + ...DEFAULT_ACCESS_TOKEN, + http: { + req: { + ...DEFAULT_HEADERS + } + }, + args: {} +}; + +function vnBeforeAll(value = DEFAULT_BEFORE_ALL) { + Object.assign(beforeAll, value); +} +function mockBeforeAll(value = DEFAULT_BEFORE_ALL) { + const origin = beforeAll.ctx; + Object.assign(origin, value); + return origin; +} + +const mockLoopBackContext = (value = DEFAULT_LOOPBACK_CTX) => { + const activeCtx = value; + + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + return activeCtx; +}; +module.exports = { + mockBeforeAll, mockLoopBackContext +}; + +(function init() { + vnBeforeAll(); +})(); -- 2.40.1 From 8ab9063b50b4003b0cb1cea62b81a33deae3454f Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 1 Apr 2024 11:00:55 +0200 Subject: [PATCH 014/413] refs #6436 feat: use mocks --- .../collection/spec/getTickets.spec.js | 10 +--------- .../client/specs/createWithUser.spec.js | 15 ++------------- .../invoice-in/specs/corrective.spec.js | 15 +-------------- .../item-shelving/specs/upsertItem.spec.js | 16 ++-------------- .../back/methods/sale/specs/clone.spec.js | 19 +++++-------------- .../ticket/specs/addSaleByCode.spec.js | 17 +++-------------- .../back/methods/ticket/specs/clone.spec.js | 15 +-------------- .../ticket/specs/transferClient.spec.js | 11 ++--------- 8 files changed, 17 insertions(+), 101 deletions(-) diff --git a/back/methods/collection/spec/getTickets.spec.js b/back/methods/collection/spec/getTickets.spec.js index e6b9e6a17..c066ead8c 100644 --- a/back/methods/collection/spec/getTickets.spec.js +++ b/back/methods/collection/spec/getTickets.spec.js @@ -1,15 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('collection getTickets()', () => { - let ctx; - beforeAll(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - } - }; - }); + const {ctx} = beforeAll; it('should get tickets, sales and barcodes from collection', async() => { const tx = await models.Collection.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 074cb289a..584c49d5c 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Client Create', () => { const newAccount = { @@ -17,18 +17,7 @@ describe('Client Create', () => { delete newAccountWithoutEmail.email; beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it(`should not find Deadpool as he's not created yet`, async() => { diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js index 1047cd028..ff547f1c8 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js @@ -1,24 +1,11 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('invoiceIn corrective()', () => { - let ctx; + const {ctx} = beforeAll; let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.Sale.beginTransaction({}); options.transaction = tx; diff --git a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js index 9042b743d..e7f2ab015 100644 --- a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js +++ b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js @@ -1,26 +1,14 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); // #6276 describe('ItemShelving upsertItem()', () => { const warehouseFk = 1; - let ctx; + + const {ctx} = beforeAll; let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.ItemShelving.beginTransaction({}); options.transaction = tx; diff --git a/modules/ticket/back/methods/sale/specs/clone.spec.js b/modules/ticket/back/methods/sale/specs/clone.spec.js index e2220c028..ef2c6a9a3 100644 --- a/modules/ticket/back/methods/sale/specs/clone.spec.js +++ b/modules/ticket/back/methods/sale/specs/clone.spec.js @@ -1,24 +1,15 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext, mockBeforeAll} = require('vn-loopback/../../back/vn-jasmine'); describe('Ticket cloning - clone function', () => { - let ctx; + let ctx = mockBeforeAll({ejemploe: true}); let options; let tx; + beforeAll(async() => { + mockLoopBackContext(); + }); beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.Sale.beginTransaction({}); options.transaction = tx; diff --git a/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js b/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js index b97139178..29af66752 100644 --- a/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js +++ b/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js @@ -1,22 +1,11 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('Ticket addSaleByCode()', () => { const quantity = 3; const ticketFk = 13; const warehouseFk = 1; - beforeAll(async() => { - activeCtx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'}, - __: value => value - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + + const {ctx} = beforeAll; it('should add a new sale', async() => { const tx = await models.Ticket.beginTransaction({}); @@ -26,7 +15,7 @@ describe('Ticket addSaleByCode()', () => { const code = '1111111111'; const salesBefore = await models.Sale.find(null, options); - await models.Ticket.addSaleByCode(activeCtx, code, quantity, ticketFk, warehouseFk, options); + await models.Ticket.addSaleByCode(ctx, code, quantity, ticketFk, warehouseFk, options); const salesAfter = await models.Sale.find(null, options); expect(salesAfter.length).toEqual(salesBefore.length + 1); diff --git a/modules/ticket/back/methods/ticket/specs/clone.spec.js b/modules/ticket/back/methods/ticket/specs/clone.spec.js index 26114bd58..cf222ab8d 100644 --- a/modules/ticket/back/methods/ticket/specs/clone.spec.js +++ b/modules/ticket/back/methods/ticket/specs/clone.spec.js @@ -1,26 +1,13 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('Ticket cloning - clone function', () => { - let ctx; + const {ctx} = beforeAll; let options; let tx; const ticketId = 1; const shipped = Date.vnNew(); beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.Ticket.beginTransaction({}); options.transaction = tx; diff --git a/modules/ticket/back/methods/ticket/specs/transferClient.spec.js b/modules/ticket/back/methods/ticket/specs/transferClient.spec.js index 5f1c09776..4aac0833a 100644 --- a/modules/ticket/back/methods/ticket/specs/transferClient.spec.js +++ b/modules/ticket/back/methods/ticket/specs/transferClient.spec.js @@ -4,18 +4,11 @@ describe('Ticket transferClient()', () => { const originalTicketId = 8; const refundTicketId = 24; const clientId = 1; - let ctx; + + const {ctx} = beforeAll; let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - options = {transaction: tx}; tx = await models.Ticket.beginTransaction({}); options.transaction = tx; -- 2.40.1 From 6db1696094f50f5fc47e07002cd933a131eb97b9 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 3 Apr 2024 07:04:12 +0200 Subject: [PATCH 015/413] refs #5890 feat:trigger --- .../itemShelvingSale_addByCollection.sql | 2 +- .../vn/triggers/itemShelving_AFTER_INSERT.sql | 27 ---------------- .../vn/triggers/itemShelving_AFTER_UPDATE.sql | 16 ---------- .../triggers/itemShelving_BEFORE_INSERT.sql | 10 ------ .../vn/triggers/itemShelving_afterInsert.sql | 31 +++++++++++-------- .../vn/triggers/itemShelving_afterUpdate.sql | 10 ++++-- .../vn/triggers/itemShelving_beforeInsert.sql | 1 + .../vn/triggers/itemShelving_beforeUpdate.sql | 6 ++++ 8 files changed, 33 insertions(+), 70 deletions(-) delete mode 100644 db/routines/vn/triggers/itemShelving_AFTER_INSERT.sql delete mode 100644 db/routines/vn/triggers/itemShelving_AFTER_UPDATE.sql delete mode 100644 db/routines/vn/triggers/itemShelving_BEFORE_INSERT.sql diff --git a/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql b/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql index 4e57fed0b..9bc549235 100644 --- a/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql +++ b/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql @@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_ad ) BEGIN /** - * Guarda la ubicación para el contenido de una colección + * Reserva cantidades con ubicaciones para el contenido de una colección * * @param vCollectionFk Identificador de collection */ diff --git a/db/routines/vn/triggers/itemShelving_AFTER_INSERT.sql b/db/routines/vn/triggers/itemShelving_AFTER_INSERT.sql deleted file mode 100644 index 784a736ec..000000000 --- a/db/routines/vn/triggers/itemShelving_AFTER_INSERT.sql +++ /dev/null @@ -1,27 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_AFTER_INSERT` - AFTER INSERT ON `itemShelving` - FOR EACH ROW -BEGIN - - INSERT INTO vn.itemShelvingLog( - itemShelvingFk, - workerFk, - accion, - itemFk, - shelvingFk, - visible, - `grouping`, - packing, - available) - VALUES( NEW.id, - NEW.userFk, - 'CREA REGISTRO', - NEW.itemFk, - NEW.shelvingFk, - NEW.visible, - NEW.`grouping`, - NEW.packing, - NEW.available); -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/itemShelving_AFTER_UPDATE.sql b/db/routines/vn/triggers/itemShelving_AFTER_UPDATE.sql deleted file mode 100644 index 23ea14e85..000000000 --- a/db/routines/vn/triggers/itemShelving_AFTER_UPDATE.sql +++ /dev/null @@ -1,16 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_AFTER_UPDATE` - AFTER UPDATE ON `itemShelving` - FOR EACH ROW -BEGIN - INSERT INTO itemShelvingLog - SET itemShelvingFk = NEW.id, - workerFk = account.myUser_getId(), - accion = 'CAMBIO', - itemFk = NEW.itemFk, - shelvingFk = NEW.shelvingFk, - visible = NEW.visible, - `grouping` = NEW.`grouping`, - packing = NEW.packing; -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/itemShelving_BEFORE_INSERT.sql b/db/routines/vn/triggers/itemShelving_BEFORE_INSERT.sql deleted file mode 100644 index 0bed738d2..000000000 --- a/db/routines/vn/triggers/itemShelving_BEFORE_INSERT.sql +++ /dev/null @@ -1,10 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_BEFORE_INSERT` - BEFORE INSERT ON `itemShelving` - FOR EACH ROW -BEGIN - SET NEW.editorFk = account.myUser_getId(); - SET NEW.userFk = account.myUser_getId(); - SET NEW.available = NEW.visible; -END$$ -DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelving_afterInsert.sql b/db/routines/vn/triggers/itemShelving_afterInsert.sql index 5c0cb3853..1408615c3 100644 --- a/db/routines/vn/triggers/itemShelving_afterInsert.sql +++ b/db/routines/vn/triggers/itemShelving_afterInsert.sql @@ -1,22 +1,27 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterInsert` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_AFTER_INSERT` AFTER INSERT ON `itemShelving` FOR EACH ROW -INSERT INTO vn.itemShelvingLog( itemShelvingFk, - workerFk, - accion, - itemFk, - shelvingFk, - visible, - `grouping`, - packing) - VALUES( NEW.id, +BEGIN + + INSERT INTO vn.itemShelvingLog( + itemShelvingFk, + workerFk, + accion, + itemFk, + shelvingFk, + visible, + `grouping`, + packing, + available) + VALUES( NEW.id, NEW.userFk, 'CREA REGISTRO', NEW.itemFk, NEW.shelvingFk, NEW.visible, NEW.`grouping`, - NEW.packing - )$$ -DELIMITER ; + NEW.packing, + NEW.available); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/itemShelving_afterUpdate.sql b/db/routines/vn/triggers/itemShelving_afterUpdate.sql index 107e8ecdc..1d7dc4ac6 100644 --- a/db/routines/vn/triggers/itemShelving_afterUpdate.sql +++ b/db/routines/vn/triggers/itemShelving_afterUpdate.sql @@ -1,8 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterUpdate` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_AFTER_UPDATE` AFTER UPDATE ON `itemShelving` FOR EACH ROW -INSERT INTO itemShelvingLog +BEGIN + INSERT INTO itemShelvingLog SET itemShelvingFk = NEW.id, workerFk = account.myUser_getId(), accion = 'CAMBIO', @@ -10,5 +11,8 @@ INSERT INTO itemShelvingLog shelvingFk = NEW.shelvingFk, visible = NEW.visible, `grouping` = NEW.`grouping`, - packing = NEW.packing$$ + packing = NEW.packing, + available = NEW.available; + +END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelving_beforeInsert.sql b/db/routines/vn/triggers/itemShelving_beforeInsert.sql index 011cf3701..e9fe17cf2 100644 --- a/db/routines/vn/triggers/itemShelving_beforeInsert.sql +++ b/db/routines/vn/triggers/itemShelving_beforeInsert.sql @@ -5,6 +5,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_beforeIn BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); + SET NEW.available = NEW.visible; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelving_beforeUpdate.sql b/db/routines/vn/triggers/itemShelving_beforeUpdate.sql index 6fd919d2e..214c64b45 100644 --- a/db/routines/vn/triggers/itemShelving_beforeUpdate.sql +++ b/db/routines/vn/triggers/itemShelving_beforeUpdate.sql @@ -3,9 +3,15 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_beforeUp BEFORE UPDATE ON `itemShelving` FOR EACH ROW BEGIN + SET NEW.editorFk = account.myUser_getId(); IF NEW.userFk IS NULL THEN SET NEW.userFk = account.myUser_getId(); END IF; + + IF (NEW.visible <> OLD.visible) THEN + SET NEW.available = GREATEST(NEW.available + NEW.visible - OLD.visible, 0); + END IF; + END$$ DELIMITER ; -- 2.40.1 From 78f55861365eeafaf3fe22e9278a619081b963fd Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 4 Apr 2024 09:37:34 +0200 Subject: [PATCH 016/413] refs #5890 feat:itemShelving_add --- db/routines/vn/procedures/itemShelving_add.sql | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/itemShelving_add.sql b/db/routines/vn/procedures/itemShelving_add.sql index dee96f43c..09a3e5bb6 100644 --- a/db/routines/vn/procedures/itemShelving_add.sql +++ b/db/routines/vn/procedures/itemShelving_add.sql @@ -55,8 +55,7 @@ BEGIN vQuantity, IFNULL(vGrouping, b.grouping), IFNULL(vPacking, b.packing), - IFNULL(vPackagingFk, b.packagingFk), - vQuantity + IFNULL(vPackagingFk, b.packagingFk) FROM item i LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk LEFT JOIN buy b ON b.id = lb.buy_id -- 2.40.1 From 09812c24ddcb717f7b09196bd644f0b66e6e6dc9 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 8 Apr 2024 09:54:23 +0200 Subject: [PATCH 017/413] refs #5890 feat: triggers --- db/routines/vn/triggers/itemShelving_afterInsert.sql | 2 +- db/routines/vn/triggers/itemShelving_afterUpdate.sql | 2 +- db/versions/10983-chocolateDracena/00-firstScript.sql | 5 +++++ 3 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 db/versions/10983-chocolateDracena/00-firstScript.sql diff --git a/db/routines/vn/triggers/itemShelving_afterInsert.sql b/db/routines/vn/triggers/itemShelving_afterInsert.sql index 1408615c3..86f149473 100644 --- a/db/routines/vn/triggers/itemShelving_afterInsert.sql +++ b/db/routines/vn/triggers/itemShelving_afterInsert.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_AFTER_INSERT` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterInsert` AFTER INSERT ON `itemShelving` FOR EACH ROW BEGIN diff --git a/db/routines/vn/triggers/itemShelving_afterUpdate.sql b/db/routines/vn/triggers/itemShelving_afterUpdate.sql index 1d7dc4ac6..1ad57961a 100644 --- a/db/routines/vn/triggers/itemShelving_afterUpdate.sql +++ b/db/routines/vn/triggers/itemShelving_afterUpdate.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_AFTER_UPDATE` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterUpdate` AFTER UPDATE ON `itemShelving` FOR EACH ROW BEGIN diff --git a/db/versions/10983-chocolateDracena/00-firstScript.sql b/db/versions/10983-chocolateDracena/00-firstScript.sql new file mode 100644 index 000000000..2baf1b21f --- /dev/null +++ b/db/versions/10983-chocolateDracena/00-firstScript.sql @@ -0,0 +1,5 @@ +-- Place your SQL code here +USE vn; + +DROP TRIGGER IF EXISTS itemShelving_AFTER_UPDATE; +DROP TRIGGER IF EXISTS itemShelving_AFTER_INSERT; -- 2.40.1 From 914d3b2c67ad4aaceb4968be15d1c40bd669c6da Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 10 Apr 2024 11:41:08 +0200 Subject: [PATCH 018/413] feat: refs #6449 add showId column --- .../10986-pinkChrysanthemum/00-addSummaryId.sql | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql diff --git a/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql b/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql new file mode 100644 index 000000000..3dd330c68 --- /dev/null +++ b/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql @@ -0,0 +1,17 @@ +ALTER TABLE vn.claimLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.clientLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.deviceProductionLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.entryLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.invoiceInLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.itemLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.packingSiteDeviceLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.parkingLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.rateLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.routeLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.shelvingLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.supplierLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.ticketLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.travelLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.userLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.workerLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; +ALTER TABLE vn.zoneLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; \ No newline at end of file -- 2.40.1 From 5967bd545c40df79625996295edafa515e9ebdbb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 11 Apr 2024 12:16:00 +0200 Subject: [PATCH 019/413] feat: previas con reserva refs #6861 --- back/methods/collection/getSales.js | 4 +- back/methods/collection/getTickets.js | 57 +++++++-- db/routines/vn/functions/ticket_get.sql | 88 ++++++-------- .../vn/procedures/collection_getTickets.sql | 115 +++++++++++------- 4 files changed, 155 insertions(+), 109 deletions(-) diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index 78945dc80..d4bf371b2 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -1,6 +1,6 @@ module.exports = Self => { Self.remoteMethodCtx('getSales', { - description: 'Get sales from ticket or collection', + description: 'Get sales from ticket, collection or sectorCollection', accessType: 'READ', accepts: [ { @@ -59,7 +59,7 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); for (let ticket of tickets) { - let observations = ticket.observaciones.split(' '); + let observations = ticket.observation.split(' '); for (let observation of observations) { const salesPerson = ticket.salesPersonFk; diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 50117b954..ab974e371 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -37,6 +37,7 @@ module.exports = Self => { const promises = []; const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions); + const sales = await Self.rawSql(` SELECT s.ticketFk, sgd.saleGroupFk, @@ -76,17 +77,55 @@ module.exports = Self => { LEFT JOIN origin o ON o.id = i.originFk WHERE tc.collectionFk = ? GROUP BY s.id, ish.id, p.code, p2.code - ORDER BY pickingOrder;`, [id], myOptions); - + UNION ALL + SELECT s.ticketFk, + sgd.saleGroupFk, + s.id saleFk, + s.itemFk, + i.longName, + i.size, + ic.color, + o.code origin, + ish.packing, + ish.grouping, + s.isAdded, + s.originalQuantity, + s.quantity, + iss.quantity, + SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id), + ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY p.pickingOrder), + COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) , + sh.code, + IFNULL(p2.code, p.code), + IFNULL(p2.pickingOrder, p.pickingOrder), + iss.id itemShelvingSaleFk, + iss.isPicked + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN saleGroup sg ON sg.id = ss.saleGroupFk + JOIN ticket t ON t.id = sg.ticketFk + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + LEFT JOIN parking p2 ON p2.id = sg.parkingFk + JOIN item i ON i.id = s.itemFk + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = sh.parkingFk + LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk + LEFT JOIN origin o ON o.id = i.originFk + WHERE sc.id = ? + GROUP BY s.id, ish.id, p.code, p2.code`, [id, id], myOptions); if (print) await Self.rawSql(`CALL vn.collection_printSticker(?, ?)`, [id, null], myOptions); const collection = {collectionFk: id, tickets: []}; + if (tickets && tickets.length) { for (const ticket of tickets) { const ticketId = ticket.ticketFk; - if (ticket.observaciones != '') { - for (observation of ticket.observaciones.split(' ')) { + if (ticket.observation) { + for (observation of ticket.observation?.split(' ')) { if (['#', '@'].includes(observation.charAt(0))) { promises.push(Self.app.models.Chat.send(ctx, observation, $t('The ticket is in preparation', { @@ -100,11 +139,11 @@ module.exports = Self => { if (sales && sales.length) { const barcodes = await Self.rawSql(` SELECT s.id saleFk, 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 + FROM sale s + LEFT JOIN itemBarcode b ON b.itemFk = s.itemFk + LEFT JOIN buy c ON c.itemFk = s.itemFk + LEFT JOIN entry e ON e.id = c.entryFk + LEFT JOIN travel tr ON tr.id = e.travelFk WHERE s.ticketFk = ? AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`, [ticketId], myOptions); diff --git a/db/routines/vn/functions/ticket_get.sql b/db/routines/vn/functions/ticket_get.sql index 1f0e9a25a..b55b1297e 100644 --- a/db/routines/vn/functions/ticket_get.sql +++ b/db/routines/vn/functions/ticket_get.sql @@ -1,64 +1,44 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_get`(vParamFk INT) - RETURNS int(11) + RETURNS INT(11) NOT DETERMINISTIC READS SQL DATA -proc:BEGIN - - /* Devuelve el número de ticket o collection consultando en varias tablas posibles - * - * @param vParamFk Número a validar - * @return vValidFk Identificador validado - */ - - DECLARE vValidFk INT; +BEGIN +/** + * Devuelve el número de ticket / collection / sectorCollection consultando + * en que tabla se encuantra en la última semana + * + * @param vParamFk Número a validar + * @return vReturn Identificador validado + */ + DECLARE vReturn INT DEFAULT NULL; + DECLARE vDated DATE; - -- Tabla vn.saleGroup - SELECT s.ticketFk INTO vValidFk - FROM vn.sale s - JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk - WHERE sg.id = vParamFk - AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()) - LIMIT 1; - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; + SET vDated = util.VN_CURDATE() - INTERVAL 1 WEEK; - -- Tabla vn.collection - SELECT c.id INTO vValidFk - FROM vn.collection c - WHERE c.id = vParamFk - AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; + SELECT COALESCE( + (SELECT s.ticketFk + FROM sale s + JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + WHERE sg.id = vParamFk + AND sg.created > vDated + LIMIT 1), + (SELECT c.id + FROM collection c + WHERE c.id = vParamFk + AND c.created > vDated), + (SELECT id + FROM ticket + WHERE id = vParamFk + AND shipped > vDated), + (SELECT id + FROM sectorCollection + WHERE id = vParamFk + AND created > vDated) + ) INTO vReturn; - -- Tabla vn.ticket - SELECT t.id INTO vValidFk - FROM vn.ticket t - WHERE t.id = vParamFk - AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; - - RETURN NULL; + RETURN vReturn; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql index 0a71ada78..09624acd2 100644 --- a/db/routines/vn/procedures/collection_getTickets.sql +++ b/db/routines/vn/procedures/collection_getTickets.sql @@ -2,61 +2,88 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_getTickets`(vParamFk INT) BEGIN /** - * Selecciona los tickets de una colección/ticket - * @param vParamFk ticketFk/collectionFk - * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones + * Selecciona los tickets de una colección/ticket/sectorCollection + * @param vParamFk ticketFk/collectionFk/sectorCollection + * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observation */ DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vDated DATE; -- Si los sacadores son los de pruebas, pinta los colores - SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + SELECT itemPackingTypeFk + INTO vItemPackingTypeFk + FROM collection WHERE id = vParamFk; + + SET vDated = util.yesterday(); - SELECT t.id ticketFk, - IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, - am.name agencyName, - t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description,'') observaciones, - cc.rgb - FROM vn.ticket t - LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.client c ON c.id = t.clientFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id - AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk - AND t.shipped >= util.yesterday() - UNION ALL + WITH observation AS ( + SELECT tob.ticketFk, tob.description + FROM ticketObservation tob + JOIN ticketCollection tc ON tc.ticketFk = tob.ticketFk + LEFT JOIN observationType ot ON ot.id = tob.observationTypeFk + WHERE ot.`code` = 'itemPicker' + AND tc.collectionFk = vParamFk + ) SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description, '') observaciones, - IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` - FROM vn.ticket t - JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc + w.id salesPersonFk, + IFNULL(ob.description,'') observation, + cc.rgb + FROM ticket t + LEFT JOIN ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN collection c2 ON c2.id = tc.collectionFk + LEFT JOIN collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` + AND cc.trainFk = c2.trainFk + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN worker w ON w.id = c.salesPersonFk + LEFT JOIN observation ob ON ob.ticketFk = t.id + WHERE t.id = vParamFk + AND t.shipped >= vDated + UNION ALL + SELECT t.id ticketFk, + IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, + am.name agencyName, + t.warehouseFk, + w.id salesPersonFk, + ob.description, + IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` + FROM ticket t + JOIN ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN collection c2 ON c2.id = tc.collectionFk + LEFT JOIN collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.client c ON c.id = t.clientFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id - AND tob.observationTypeFk = 1 - WHERE tc.collectionFk = vParamFk; - + AND cc.trainFk = c2.trainFk + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN worker w ON w.id = c.salesPersonFk + LEFT JOIN observation ob ON ob.ticketFk = t.id + WHERE tc.collectionFk = vParamFk + UNION ALL + SELECT sg.ticketFk, + NULL `level`, + am.name agencyName, + t.warehouseFk, + c.salesPersonFk, + ob.description, + NULL `rgb` + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN saleGroup sg ON sg.id = ss.saleGroupFk + JOIN ticket t ON t.id = sg.ticketFk + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN observation ob ON ob.ticketFk = t.id + LEFT JOIN client c ON c.id = t.clientFk + WHERE sc.id = vParamFk + AND t.shipped >= vDated; END$$ DELIMITER ; -- 2.40.1 From bc1397d916acea00fe70ef118c4f0d76b5d53dc8 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 11 Apr 2024 12:27:16 +0200 Subject: [PATCH 020/413] refs #6861 feat: reservePrevious --- db/routines/floranet/events/clean.sql | 22 ------- .../floranet/procedures/catalogue_get.sql | 64 ------------------- .../floranet/procedures/contact_request.sql | 20 ------ .../floranet/procedures/deliveryDate_get.sql | 29 --------- .../floranet/procedures/order_confirm.sql | 25 -------- db/routines/floranet/procedures/order_put.sql | 42 ------------ .../floranet/procedures/sliders_get.sql | 20 ------ .../vn/procedures/collection_getTickets.sql | 52 +++++++-------- 8 files changed, 26 insertions(+), 248 deletions(-) delete mode 100644 db/routines/floranet/events/clean.sql delete mode 100644 db/routines/floranet/procedures/catalogue_get.sql delete mode 100644 db/routines/floranet/procedures/contact_request.sql delete mode 100644 db/routines/floranet/procedures/deliveryDate_get.sql delete mode 100644 db/routines/floranet/procedures/order_confirm.sql delete mode 100644 db/routines/floranet/procedures/order_put.sql delete mode 100644 db/routines/floranet/procedures/sliders_get.sql diff --git a/db/routines/floranet/events/clean.sql b/db/routines/floranet/events/clean.sql deleted file mode 100644 index 4477112fd..000000000 --- a/db/routines/floranet/events/clean.sql +++ /dev/null @@ -1,22 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE - DEFINER=`root`@`localhost` - EVENT `floranet`.`clean` - ON SCHEDULE EVERY 1 DAY - STARTS '2024-01-01 23:00:00.000' - ON COMPLETION PRESERVE - ENABLE -DO -BEGIN - DELETE - FROM `order` - WHERE created < CURDATE() - AND isPaid = FALSE; - - DELETE c.* - FROM catalogue c - LEFT JOIN `order` o ON o.catalogueFk = c.id - WHERE c.created < CURDATE() - AND o.id IS NULL; -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/routines/floranet/procedures/catalogue_get.sql b/db/routines/floranet/procedures/catalogue_get.sql deleted file mode 100644 index e45fa7ddf..000000000 --- a/db/routines/floranet/procedures/catalogue_get.sql +++ /dev/null @@ -1,64 +0,0 @@ -DROP PROCEDURE IF EXISTS floranet.catalogue_get; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` PROCEDURE floranet.catalogue_get(vLanded DATE, vPostalCode VARCHAR(15)) -READS SQL DATA -proc:BEGIN -/** - * Returns list, price and all the stuff regarding the floranet items - * - * @param vLanded Delivery date - * @param vPostalCode Delivery address postal code - */ - DECLARE vLastCatalogueFk INT; - DECLARE vLockName VARCHAR(20); - DECLARE vLockTime INT; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK(vLockName); - - RESIGNAL; - END; - - SET vLockName = 'catalogue_get'; - SET vLockTime = 15; - - IF NOT GET_LOCK(vLockName, vLockTime) THEN - LEAVE proc; - END IF; - - SELECT MAX(id) INTO vLastCatalogueFk - FROM catalogue; - - INSERT INTO catalogue( - name, - price, - itemFk, - dated, - postalCode, - `type`, - image, - description - ) - SELECT i.name, - i.`size`, - i.id, - vLanded, - vPostalCode, - it.name, - CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image), - i.description - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - WHERE it.code IN ('FNR','FNP'); - - SELECT * - FROM catalogue - WHERE id > IFNULL(vLastCatalogueFk,0); - - DO RELEASE_LOCK(vLockName); - -END$$ -DELIMITER ; diff --git a/db/routines/floranet/procedures/contact_request.sql b/db/routines/floranet/procedures/contact_request.sql deleted file mode 100644 index 044c22c6f..000000000 --- a/db/routines/floranet/procedures/contact_request.sql +++ /dev/null @@ -1,20 +0,0 @@ -DROP PROCEDURE IF EXISTS floranet.contact_request; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` -PROCEDURE floranet.contact_request( - vName VARCHAR(100), - vPhone VARCHAR(15), - vEmail VARCHAR(100), - vMessage TEXT) -READS SQL DATA -BEGIN -/** - * Set actions for contact request. - * - * @param vPostalCode Delivery address postal code - */ - -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/routines/floranet/procedures/deliveryDate_get.sql b/db/routines/floranet/procedures/deliveryDate_get.sql deleted file mode 100644 index 29751ebe4..000000000 --- a/db/routines/floranet/procedures/deliveryDate_get.sql +++ /dev/null @@ -1,29 +0,0 @@ -DROP PROCEDURE IF EXISTS floranet.deliveryDate_get; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` PROCEDURE `floranet`.`deliveryDate_get`(vPostalCode VARCHAR(15)) - READS SQL DATA -BEGIN -/** - * Returns available dates for this postalCode, in the next seven days - * - * @param vPostalCode Delivery address postal code - */ - DECLARE vCurrentDayOfWeek INT; - - SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); - - SELECT DISTINCT nextDay - FROM ( - SELECT CURDATE() + INTERVAL IF( - apc.dayOfWeek >= vCurrentDayOfWeek, - apc.dayOfWeek - vCurrentDayOfWeek, - 7 - apc.dayOfWeek - ) DAY nextDay, - NOW() + INTERVAL apc.hoursInAdvance - 12 HOUR minDeliveryTime - FROM addressPostCode apc - WHERE apc.postCode = vPostalCode - HAVING nextDay > minDeliveryTime) sub; -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/routines/floranet/procedures/order_confirm.sql b/db/routines/floranet/procedures/order_confirm.sql deleted file mode 100644 index fed123663..000000000 --- a/db/routines/floranet/procedures/order_confirm.sql +++ /dev/null @@ -1,25 +0,0 @@ -DROP PROCEDURE IF EXISTS floranet.order_confirm; - -DELIMITER $$ -$$ - -CREATE DEFINER=`root`@`localhost`PROCEDURE floranet.order_confirm(vCatalogueFk INT) -READS SQL DATA - -BEGIN -/** Update order.isPaid field - * - * @param vCatalogueFk floranet.catalogue.id - * - * @returns floranet.order.isPaid - */ - UPDATE `order` - SET isPaid = TRUE, - payed = NOW() - WHERE catalogueFk = vCatalogueFk; - - SELECT isPaid - FROM `order` - WHERE catalogueFk = vCatalogueFk; -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/routines/floranet/procedures/order_put.sql b/db/routines/floranet/procedures/order_put.sql deleted file mode 100644 index c26cef19a..000000000 --- a/db/routines/floranet/procedures/order_put.sql +++ /dev/null @@ -1,42 +0,0 @@ -DROP PROCEDURE IF EXISTS floranet.order_put; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` PROCEDURE floranet.order_put(vOrder JSON) -READS SQL DATA -BEGIN -/** - * Get and process an order - * - * @param vOrder Data of the order - * - * Customer data: , , - * - * Item data: , - * - * Delivery data: ,
, - * - */ - INSERT IGNORE INTO `order`( - catalogueFk, - customerName, - email, - customerPhone, - message, - deliveryName, - address, - deliveryPhone - ) - VALUES (JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.catalogueFk')), - JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.customerName')), - JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.email')), - JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.customerPhone')), - JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.message')), - JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.deliveryName')), - JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.address')), - JSON_UNQUOTE(JSON_EXTRACT(vOrder,'$.deliveryPhone')) - ); - - SELECT LAST_INSERT_ID() orderFk; -END$$ -DELIMITER ; diff --git a/db/routines/floranet/procedures/sliders_get.sql b/db/routines/floranet/procedures/sliders_get.sql deleted file mode 100644 index bd791dec7..000000000 --- a/db/routines/floranet/procedures/sliders_get.sql +++ /dev/null @@ -1,20 +0,0 @@ -DROP PROCEDURE IF EXISTS floranet.sliders_get; - -DELIMITER $$ -$$ -CREATE DEFINER=`root`@`localhost` PROCEDURE floranet.sliders_get() -READS SQL DATA -BEGIN -/** - * Returns list of url for sliders - */ - SELECT - CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image) url, - i.longName - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - WHERE it.code IN ('FNR','FNP') - LIMIT 3; - -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql index 09624acd2..3f1239e9b 100644 --- a/db/routines/vn/procedures/collection_getTickets.sql +++ b/db/routines/vn/procedures/collection_getTickets.sql @@ -19,9 +19,9 @@ BEGIN WITH observation AS ( SELECT tob.ticketFk, tob.description - FROM ticketObservation tob - JOIN ticketCollection tc ON tc.ticketFk = tob.ticketFk - LEFT JOIN observationType ot ON ot.id = tob.observationTypeFk + FROM vn.ticketObservation tob + JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk + LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk WHERE ot.`code` = 'itemPicker' AND tc.collectionFk = vParamFk ) @@ -32,17 +32,17 @@ BEGIN w.id salesPersonFk, IFNULL(ob.description,'') observation, cc.rgb - FROM ticket t - LEFT JOIN ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN collection c2 ON c2.id = tc.collectionFk - LEFT JOIN collectionColors cc + FROM vn.ticket t + LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk + LEFT JOIN vn.collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk - LEFT JOIN zone z ON z.id = t.zoneFk - LEFT JOIN agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN client c ON c.id = t.clientFk - LEFT JOIN worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE t.id = vParamFk AND t.shipped >= vDated @@ -54,17 +54,17 @@ BEGIN w.id salesPersonFk, ob.description, IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` - FROM ticket t - JOIN ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN collection c2 ON c2.id = tc.collectionFk - LEFT JOIN collectionColors cc + FROM vn.ticket t + JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk + LEFT JOIN vn.collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk - LEFT JOIN zone z ON z.id = t.zoneFk - LEFT JOIN agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN client c ON c.id = t.clientFk - LEFT JOIN worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE tc.collectionFk = vParamFk UNION ALL @@ -75,14 +75,14 @@ BEGIN c.salesPersonFk, ob.description, NULL `rgb` - FROM sectorCollection sc - JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id - JOIN saleGroup sg ON sg.id = ss.saleGroupFk - JOIN ticket t ON t.id = sg.ticketFk - LEFT JOIN zone z ON z.id = t.zoneFk - LEFT JOIN agencyMode am ON am.id = z.agencyModeFk + FROM vn.sectorCollection sc + JOIN vn.sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN vn.saleGroup sg ON sg.id = ss.saleGroupFk + JOIN vn.ticket t ON t.id = sg.ticketFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN observation ob ON ob.ticketFk = t.id - LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN vn.client c ON c.id = t.clientFk WHERE sc.id = vParamFk AND t.shipped >= vDated; END$$ -- 2.40.1 From 3a8dcbfd292a1f1846e003a657143c366db1a3a5 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 11 Apr 2024 13:45:43 +0200 Subject: [PATCH 021/413] refs #6861 feat:reserve previos --- back/methods/collection/getTickets.js | 5 +++-- .../itemShelvingSale_reserveBySectorCollection.sql | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index a16757fd4..663b70e94 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -108,13 +108,14 @@ module.exports = Self => { LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id LEFT JOIN parking p2 ON p2.id = sg.parkingFk JOIN item i ON i.id = s.itemFk - LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + JOIN itemShelvingSale iss ON iss.saleFk = s.id LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk LEFT JOIN shelving sh ON sh.code = ish.shelvingFk LEFT JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk - WHERE sc.id = ? + WHERE sc.id = ? + AND sgd.saleGroupFk GROUP BY s.id, ish.id, p.code, p2.code`, [id, id], myOptions); if (print) await Self.rawSql(`CALL vn.collection_printSticker(?, ?)`, [id, null], myOptions); diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql b/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql index 3ea351288..52d83a75d 100644 --- a/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql +++ b/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql @@ -11,7 +11,7 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.sale (INDEX(saleFk)) ENGINE = MEMORY - SELECT s.id + SELECT s.id saleFk, str.workerFk userFK FROM sectorCollectionSaleGroup sc JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk JOIN sale s ON sg.saleFk = s.id -- 2.40.1 From 841a5fcd5b762b293fa1bcc2b28bfcb0afc52c44 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 11 Apr 2024 15:08:33 +0200 Subject: [PATCH 022/413] feat: refs #6449 add summaryId column --- .../00-addSummaryId.sql | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql b/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql index 3dd330c68..288785191 100644 --- a/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql +++ b/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql @@ -1,17 +1,22 @@ -ALTER TABLE vn.claimLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.clientLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.deviceProductionLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.entryLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.invoiceInLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.itemLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.packingSiteDeviceLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.parkingLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.rateLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.routeLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.shelvingLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.supplierLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.ticketLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.travelLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.userLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.workerLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; -ALTER TABLE vn.zoneLog ADD COLUMN IF NOT EXISTS showId BOOLEAN NOT NULL DEFAULT FALSE; \ No newline at end of file +ALTER TABLE vn.claimLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.clientLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.deviceProductionLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.entryLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.invoiceInLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.itemLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.packingSiteDeviceLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.parkingLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.rateLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.routeLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.shelvingLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.supplierLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.ticketLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.travelLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.userLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.workerLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.zoneLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); + +ALTER TABLE account.userLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE account.signInLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE account.roleLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE account.accountLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); \ No newline at end of file -- 2.40.1 From c161c122d01367fd22b6810a487a9ca3f7252a19 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 11 Apr 2024 15:56:17 +0200 Subject: [PATCH 023/413] feat: refs #6449 add column --- modules/ticket/back/models/ticket-log.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/ticket/back/models/ticket-log.json b/modules/ticket/back/models/ticket-log.json index 32b4afd13..97722be96 100644 --- a/modules/ticket/back/models/ticket-log.json +++ b/modules/ticket/back/models/ticket-log.json @@ -39,6 +39,9 @@ }, "changedModelValue": { "type": "string" + }, + "summaryId": { + "type":"string" } } } -- 2.40.1 From 0f1a086bca6c2493c9513378b1fdba8d34bea922 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 15 Apr 2024 13:03:27 +0200 Subject: [PATCH 024/413] refs #6861 feat:reserve previos --- db/routines/vn/procedures/itemShelvingSale_unpicked.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/itemShelvingSale_unpicked.sql b/db/routines/vn/procedures/itemShelvingSale_unpicked.sql index 6813a65b1..889cadfd0 100644 --- a/db/routines/vn/procedures/itemShelvingSale_unpicked.sql +++ b/db/routines/vn/procedures/itemShelvingSale_unpicked.sql @@ -27,9 +27,9 @@ BEGIN LEFT JOIN saleGroupDetail sg ON sg.saleFk = ish.saleFk WHERE ish.id = vSelf; - IF vIsSaleGroup THEN + /*IF vIsSaleGroup THEN CALL util.throw('Can not unpicked a sale group'); - END IF; + END IF;*/ START TRANSACTION; -- 2.40.1 From b1e8cdfd8641641874494b989d39fa1ed105fed1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 16 Apr 2024 09:12:51 +0200 Subject: [PATCH 025/413] feat: refs #7168 Added vRecords param in proc --- .../vn/procedures/itemShelvingLog_get.sql | 63 +++++++++++-------- 1 file changed, 37 insertions(+), 26 deletions(-) diff --git a/db/routines/vn/procedures/itemShelvingLog_get.sql b/db/routines/vn/procedures/itemShelvingLog_get.sql index ad67ea5cd..14d5101ee 100644 --- a/db/routines/vn/procedures/itemShelvingLog_get.sql +++ b/db/routines/vn/procedures/itemShelvingLog_get.sql @@ -1,35 +1,46 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`(vShelvingFk VARCHAR(10) ) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`( + vShelvingFk VARCHAR(10), + vRecords INT +) BEGIN - /** * Devuelve el log de los item en cada carro * - * @param vShelvingFk Matrícula del carro + * @param vShelvingFk Matrícula del carro + * @param vRecords Límite de registros retornados * */ - - SELECT isl.itemShelvingFk, - isl.created, - isl.accion, - isl.itemFk, - isl.shelvingFk, - isl.quantity, - isl.visible, - isl.available, - isl.grouping, - isl.packing, - isl.stars, - item.longName, - item.size, - item.subName, - worker.code, - isl.accion - FROM item - JOIN itemShelvingLog isl ON item.id = isl.itemFk - JOIN worker ON isl.workerFk = worker.id - WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk - ORDER BY isl.created DESC; - + DECLARE vQuery TEXT; + SET vQuery = ' + SELECT isl.itemShelvingFk, + isl.created, + isl.accion, + isl.itemFk, + isl.shelvingFk, + isl.quantity, + isl.visible, + isl.available, + isl.`grouping`, + isl.packing, + isl.stars, + item.longName, + item.size, + item.subName, + worker.code, + isl.accion + FROM item + JOIN itemShelvingLog isl ON item.id = isl.itemFk + JOIN worker ON isl.workerFk = worker.id + WHERE shelvingFk = ? + OR isl.itemFk = ? + ORDER BY isl.created DESC'; + + IF vRecords IS NOT NULL THEN + SET vQuery = CONCAT(vQuery, '\nLIMIT ', vRecords); + END IF; + + EXECUTE IMMEDIATE vQuery + USING vShelvingFk, vShelvingFk; END$$ DELIMITER ; -- 2.40.1 From 1140e6bbd39234cfe27a1cf00ac55c25288e87fd Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 16 Apr 2024 09:27:06 +0200 Subject: [PATCH 026/413] feat: refs #7168 Minor change --- .../vn/procedures/itemShelvingLog_get.sql | 25 ++++++------------- 1 file changed, 8 insertions(+), 17 deletions(-) diff --git a/db/routines/vn/procedures/itemShelvingLog_get.sql b/db/routines/vn/procedures/itemShelvingLog_get.sql index 14d5101ee..f72a31a9b 100644 --- a/db/routines/vn/procedures/itemShelvingLog_get.sql +++ b/db/routines/vn/procedures/itemShelvingLog_get.sql @@ -13,25 +13,16 @@ BEGIN */ DECLARE vQuery TEXT; SET vQuery = ' - SELECT isl.itemShelvingFk, - isl.created, - isl.accion, - isl.itemFk, + SELECT isl.itemFk, + i.longName, isl.shelvingFk, + w.code, + isl.accion, isl.quantity, - isl.visible, - isl.available, - isl.`grouping`, - isl.packing, - isl.stars, - item.longName, - item.size, - item.subName, - worker.code, - isl.accion - FROM item - JOIN itemShelvingLog isl ON item.id = isl.itemFk - JOIN worker ON isl.workerFk = worker.id + isl.created + FROM item i + JOIN itemShelvingLog isl ON i.id = isl.itemFk + JOIN worker w ON isl.workerFk = w.id WHERE shelvingFk = ? OR isl.itemFk = ? ORDER BY isl.created DESC'; -- 2.40.1 From 611f907ef0122b5c6137c0d6d61b38dc1d231ea7 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 25 Apr 2024 16:15:53 +0200 Subject: [PATCH 027/413] refs #6861 feat:reserveWithReservation --- .../vn/procedures/collection_addWithReservation.sql | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/collection_addWithReservation.sql b/db/routines/vn/procedures/collection_addWithReservation.sql index ea2632b05..ac0721146 100644 --- a/db/routines/vn/procedures/collection_addWithReservation.sql +++ b/db/routines/vn/procedures/collection_addWithReservation.sql @@ -2,7 +2,8 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_addWithReservation`( vItemFk INT, vQuantity INT, - vTicketFk INT + vTicketFk INT, + vSaleGroupFk INT ) BEGIN /** @@ -12,7 +13,9 @@ BEGIN * @param vItemFk id of item * @param vQuantity quantity to be added to the ticket * @param vTicketFk ticket to which the sales line is added + * @param vSaleGroupFk saleGroupFk id to add saleGroupDetail */ + DECLARE vWarehouseFk INT; DECLARE vCacheAvailableFk INT; DECLARE vAvailable INT; @@ -72,7 +75,7 @@ BEGIN CALL sale_calculateComponent(vSaleFk, NULL); CALL itemShelvingSale_addBySale(vSaleFk); - + IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN SET vHasThrow = TRUE; END IF; @@ -81,6 +84,10 @@ BEGIN IF vHasThrow THEN CALL util.throw("No hay disponibilidad para el artículo seleccionado"); ELSE + IF vSaleGroupFk THEN + INSERT INTO saleGroupDetail + SET saleFk = vSaleFk, + saleGroupFk = vSaleGroupFk, COMMIT; END IF; END$$ -- 2.40.1 From b9d3684db254a75a808f9af08db90f049f986f42 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 26 Apr 2024 15:48:30 +0200 Subject: [PATCH 028/413] feat: refs #6600 add column --- db/versions/11015-silverBamboo/00-addColumnPhotoMotivation.sql | 1 + modules/item/back/models/item.json | 3 +++ 2 files changed, 4 insertions(+) create mode 100644 db/versions/11015-silverBamboo/00-addColumnPhotoMotivation.sql diff --git a/db/versions/11015-silverBamboo/00-addColumnPhotoMotivation.sql b/db/versions/11015-silverBamboo/00-addColumnPhotoMotivation.sql new file mode 100644 index 000000000..9f77dc88e --- /dev/null +++ b/db/versions/11015-silverBamboo/00-addColumnPhotoMotivation.sql @@ -0,0 +1 @@ +ALTER TABLE vn.item ADD COLUMN photoMotivation VARCHAR(255); \ No newline at end of file diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 9d48dcbfb..7ec1daf7a 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -155,6 +155,9 @@ "minQuantity": { "type": "number", "description": "Min quantity" + }, + "photoMotivation":{ + "type": "string" } }, "relations": { -- 2.40.1 From 3146f4f5b611a57d371ad3456049f1300d7deb45 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 2 May 2024 14:59:30 +0200 Subject: [PATCH 029/413] refactor: refs #6701 Refactor claim_ratio_routine --- .../bi/procedures/claim_ratio_routine.sql | 166 ------------------ db/routines/vn/procedures/claimRatio_add.sql | 154 ++++++++++++++++ .../11028-silverCarnation/00-firstScript.sql | 4 + 3 files changed, 158 insertions(+), 166 deletions(-) delete mode 100644 db/routines/bi/procedures/claim_ratio_routine.sql create mode 100644 db/routines/vn/procedures/claimRatio_add.sql create mode 100644 db/versions/11028-silverCarnation/00-firstScript.sql diff --git a/db/routines/bi/procedures/claim_ratio_routine.sql b/db/routines/bi/procedures/claim_ratio_routine.sql deleted file mode 100644 index ae87e15a2..000000000 --- a/db/routines/bi/procedures/claim_ratio_routine.sql +++ /dev/null @@ -1,166 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bi`.`claim_ratio_routine`() -BEGIN - DECLARE vMonthToRefund INT DEFAULT 4; - - /* - * PAK 2015-11-20 - * Se trata de añadir a la tabla Greuges todos los - * cargos que luego vamos a utilizar para calcular el recobro - */ - - -- Reclamaciones demasiado sensibles - - INSERT INTO vn.greuge(shipped, clientFk, description, - amount, greugeTypeFk, ticketFk) - SELECT c.ticketCreated - , c.clientFk - , concat('Claim ', c.id,' : ', s.concept) - ,round( -1 * ((c.responsibility -1)/4) * s.quantity * - s.price * (100 - s.discount) / 100, 2) - , 4 - , s.ticketFk - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3; - - -- Reclamaciones que pasan a Maná - - INSERT INTO vn.greuge(shipped, clientFk, description, - amount, greugeTypeFk, ticketFk) - SELECT c.ticketCreated - , c.clientFk - , concat('Claim_mana ',c.id,' : ', s.concept) - ,round( ((c.responsibility -1)/4) * s.quantity * s.price * (100 - s.discount) / 100, 2) - ,3 - ,s.ticketFk - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3 - AND c.isChargedToMana; - - -- Marcamos para no repetir - UPDATE vn.claimEnd ce - JOIN vn.claim c ON c.id = ce.claimFk - SET c.isChargedToMana = TRUE - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3; - - -- Recobros - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT DISTINCT t.id Id_Ticket - FROM vn.saleComponent sc - JOIN vn.sale s ON sc.saleFk = s.id - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.ticketLastState ts ON ts.ticketFk = t.id - JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk - JOIN vn.state st ON st.id = tt.stateFk - WHERE sc.componentFk = 17 - AND sc.isGreuge = 0 - AND t.shipped >= '2016-10-01' - AND t.shipped < util.VN_CURDATE() - AND st.alertLevel >= 3; - - DELETE g.* - FROM vn.greuge g - JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket - WHERE g.greugeTypeFk = 2; - - INSERT INTO vn.greuge(clientFk, description, amount,shipped, - greugeTypeFk, ticketFk) - SELECT t.clientFk - ,concat('recobro ', s.ticketFk), - round(SUM(sc.value*s.quantity),2) - AS dif, - date(t.shipped) - , 2 - ,tt.Id_Ticket - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.id - JOIN vn.saleComponent sc - ON sc.saleFk = s.id AND sc.componentFk = 17 - GROUP BY t.id - HAVING ABS(dif) > 1; - - UPDATE vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = s.ticketFk - SET sc.isGreuge = 1 - WHERE sc.componentFk = 17; - - /* - * Recalculamos la ratio de las reclamaciones, que luego - * se va a utilizar en el recobro - */ - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT id, 0,0,0,0 - FROM vn.client; - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, - round(Reclamaciones / (12*fm.Consumo),4), 0 - FROM bi.facturacion_media_anual fm - LEFT JOIN( - SELECT c.clientFk, round(sum(-1 * ((c.responsibility -1)/4) * - s.quantity * s.price * (100 - s.discount) / 100)) - AS Reclamaciones - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND c.claimStateFk = 3 - AND c.ticketCreated >= TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) - GROUP BY c.clientFk - ) claims ON claims.clientFk = fm.Id_Cliente; - - - -- Calculamos el porcentaje del recobro para añadirlo al precio de venta - UPDATE bi.claims_ratio cr - JOIN ( - SELECT clientFk Id_Cliente, IFNULL(SUM(amount), 0) AS Greuge - FROM vn.greuge - WHERE shipped <= util.VN_CURDATE() - GROUP BY clientFk - ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(IFNULL(Greuge, 0) / - (IFNULL(Consumo, 0) * vMonthToRefund / 12 ) ,3)); - - -- Protección neonatos - UPDATE bi.claims_ratio cr - JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente - SET recobro = 0, Ratio = 0 - WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); - - -- CLIENTE 7983, JULIAN SUAU - UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; - - -- CLIENTE 4358 - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; - - -- CLIENTE 5523, VERDECORA - UPDATE bi.claims_ratio SET recobro = GREATEST(0.12, recobro) WHERE Id_Cliente = 5523; - - -- CLIENTE 15979, SERVEIS VETERINARIS - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979; - - -- CLIENTE 5189 i 8942, son de CSR i son el mateix client - UPDATE bi.claims_ratio cr - JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro - FROM bi.claims_ratio - WHERE Id_Cliente IN ( 5189,8942) - ) sub - SET cr.recobro = sub.recobro - WHERE Id_Cliente IN ( 5189,8942); -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/claimRatio_add.sql b/db/routines/vn/procedures/claimRatio_add.sql new file mode 100644 index 000000000..2f64f8c7e --- /dev/null +++ b/db/routines/vn/procedures/claimRatio_add.sql @@ -0,0 +1,154 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`claimRatio_add`() +BEGIN +/* +* PAK 2015-11-20 +* Se trata de añadir a la tabla Greuges todos los +* cargos que luego vamos a utilizar para calcular el recobro +*/ + DECLARE vMonthToRefund INT DEFAULT 4; + DECLARE vRecoveryGreugeType INT; + + SELECT id INTO vRecoveryGreugeType + FROM greugeType + WHERE code = 'recovery'; + + -- Reclamaciones demasiado sensibles + INSERT INTO greuge(shipped, clientFk, description, + amount, greugeTypeFk, ticketFk) + SELECT c.ticketCreated + , c.clientFk + , concat('Claim ', c.id,' : ', s.concept) + ,round( -1 * ((c.responsibility -1)/4) * s.quantity * + s.price * (100 - s.discount) / 100, 2) + , 4 + , s.ticketFk + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claim c ON c.id = ce.claimFk + WHERE ce.claimDestinationFk NOT IN (1,5) + AND NOT ce.isGreuge + AND c.claimStateFk = 3; + + -- Reclamaciones que pasan a Maná + INSERT INTO greuge(shipped, + clientFk, + `description`, + amount, + greugeTypeFk, + ticketFk) + SELECT c.ticketCreated, + c.clientFk, + concat('Claim_mana ',c.id,' : ', s.concept), + round( ((c.responsibility -1)/4) * s.quantity * s.price * (100 - s.discount) / 100, 2), + 3, + s.ticketFk + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claim c ON c.id = ce.claimFk + WHERE ce.claimDestinationFk NOT IN (1,5) + AND NOT ce.isGreuge + AND c.claimStateFk = 3 + AND c.isChargedToMana; + + -- Marcamos para no repetir + UPDATE claimEnd ce + JOIN claim c ON c.id = ce.claimFk + SET c.isChargedToMana = TRUE + WHERE ce.claimDestinationFk NOT IN (1,5) + AND NOT ce.isGreuge + AND c.claimStateFk = 3; + + -- Recobros + CREATE OR REPLACE TEMPORARY TABLE tTicketList + (PRIMARY KEY (ticketFk)) + SELECT DISTINCT s.ticketFk + FROM saleComponent sc + JOIN sale s ON sc.saleFk = s.id + JOIN ticket t ON t.id = s.ticketFk + JOIN ticketLastState ts ON ts.ticketFk = t.id + JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk + JOIN state st ON st.id = tt.stateFk + WHERE sc.componentFk = 17 + AND sc.isGreuge = 0 + AND t.shipped >= '2016-10-01' + AND t.shipped < util.VN_CURDATE() + AND st.alertLevel >= 3; + + DELETE g.* + FROM greuge g + JOIN tTicketList t ON t.ticketFk = g.ticketFk + WHERE g.greugeTypeFk = vRecoveryGreugeType; + + INSERT INTO greuge(clientFk, + `description`, + amount, + shipped, + greugeTypeFk, + ticketFk) + SELECT t.clientFk, + 'Recobro', + - ROUND(SUM(sc.value * s.quantity), 2) dif, + DATE(t.shipped), + vRecoveryGreugeType, + tl.ticketFk + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN tTicketList tl ON tl.ticketFk = t.id + JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = 17 + GROUP BY t.id + HAVING ABS(dif) > 1; + + UPDATE saleComponent sc + JOIN sale s ON s.id = sc.saleFk + JOIN tTicketList tl ON tl.ticketFk = s.ticketFk + SET sc.isGreuge = TRUE + WHERE sc.componentFk = 17; + + /* + * Recalculamos la ratio de las reclamaciones, que luego + * se va a utilizar en el recobro + */ + REPLACE claimRatio(clientFk, yearSale, claimAmount, claimingRate, priceIncreasing) + SELECT id, 0, 0, 0, 0 + FROM client; + + REPLACE claimRatio(clientFk, yearSale, claimAmount, claimingRate, priceIncreasing) + SELECT cac.clientFk, 12 * cac.invoiced, totalClaims, + ROUND(totalClaims / (12 * cac.invoiced), 4), 0 + FROM bs.clientAnnualConsumption cac + LEFT JOIN( + SELECT c.clientFk, round(sum(-1 * ((c.responsibility -1)/4) * + s.quantity * s.price * (100 - s.discount) / 100)) + totalClaims + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claim c ON c.id = ce.claimFk + WHERE ce.claimDestinationFk NOT IN (1,5) + AND c.claimStateFk = 3 + AND c.ticketCreated >= util.VN_CURDATE() - INTERVAL 1 YEAR + GROUP BY c.clientFk + ) claims ON claims.clientFk = fm.Id_Cliente; + + -- Calculamos el porcentaje del recobro para añadirlo al precio de venta + UPDATE claimRatio cr + JOIN ( + SELECT clientFk, IFNULL(SUM(amount), 0) AS Greuge + FROM greuge + WHERE shipped <= util.VN_CURDATE() + GROUP BY clientFk + ) g ON g.clientFk = cr.clientFk + SET cr.priceIncreasing = GREATEST(0, round(IFNULL(Greuge, 0) / + (IFNULL(Consumo, 0) * vMonthToRefund / 12 ), 3)); + + -- Protección neonatos + UPDATE claimRatio cr + JOIN firstTicketShipped fts ON fts.clientFk = cr.clientFk + SET cr.priceIncreasing = 0, + cr.claimingRate = 0 + WHERE fts.shipped > util.VN_CURDATE() - INTERVAL 1 MONTH; + + DROP TEMPORARY TABLE tTicketList; +END$$ +DELIMITER ; diff --git a/db/versions/11028-silverCarnation/00-firstScript.sql b/db/versions/11028-silverCarnation/00-firstScript.sql new file mode 100644 index 000000000..f865b0caf --- /dev/null +++ b/db/versions/11028-silverCarnation/00-firstScript.sql @@ -0,0 +1,4 @@ +UPDATE IGNORE bs.nightTask + SET `procedure` = 'claimRatio_add', + `schema` = 'vn' + WHERE `procedure` = 'claim_ratio_routine'; -- 2.40.1 From a21e3357743fbba4f3648db9c8b31667770c5a46 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 2 May 2024 17:23:04 +0200 Subject: [PATCH 030/413] feat: refs #6449 Add display of item ID in Ticket Logs --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a672e7986..c24cefa4f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - (Worker -> time-control) Corrección de errores - (InvoiceOut -> Crear factura) Cuando falla al crear una factura, se devuelve un error +- (Ticket -> Logs) Ahora se muestra el id del item de la línea de venta ## [24.18.01] - 2024-05-07 -- 2.40.1 From 411933a608718dc7e4e2af3c5dfaf0f7defaac21 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 3 May 2024 12:17:51 +0200 Subject: [PATCH 031/413] feat: refs #6598 acls back --- back/methods/vn-user/acls.js | 72 ++++++++++++++++++++++++++++++++++++ back/models/vn-user.js | 1 + back/models/vn-user.json | 7 ++++ 3 files changed, 80 insertions(+) create mode 100644 back/methods/vn-user/acls.js diff --git a/back/methods/vn-user/acls.js b/back/methods/vn-user/acls.js new file mode 100644 index 000000000..7da75ed2c --- /dev/null +++ b/back/methods/vn-user/acls.js @@ -0,0 +1,72 @@ +module.exports = Self => { + Self.remoteMethodCtx('acls', { + description: 'Get all of the current user acls', + returns: { + type: 'Object', + root: true + }, + http: { + path: '/acls', + verb: 'GET' + } + }); + + const staticAcls = new Map(); + const app = require('vn-loopback/server/server'); + app.on('started', function() { + for (const model of app.models()) { + for (const acl of model.settings.acls) { + if (acl.principalType == 'ROLE' && acl.permission == 'ALLOW') { + const staticAcl = { + model: model.name, + property: '*', + accessType: acl.accessType, + permission: acl.permission, + principalType: acl.principalType, + principalId: acl.principalId, + }; + if (staticAcls.has(acl.principalId)) + staticAcls.get(acl.principalId).push(staticAcl); + else + staticAcls.set(acl.principalId, [staticAcl]); + } + } + } + }); + + Self.acls = async function(ctx) { + const models = Self.app.models; + const acls = []; + const userId = ctx.req.accessToken.userId; + if (userId) { + const roleMapping = await models.RoleMapping.find({ + where: { + principalId: userId + }, + include: [ + { + relation: 'role', + scope: { + fields: [ + 'name' + ] + } + } + ] + }); + const dynamicAcls = await models.ACL.find({ + where: { + principalId: { + inq: roleMapping.map(rm => rm.role().name) + } + } + }); + dynamicAcls.forEach(acl => acls.push(acl)); + staticAcls.get('$authenticated').forEach(acl => acls.push(acl)); + } else + staticAcls.get('$unauthenticated').forEach(acl => acls.push(acl)); + + staticAcls.get('$everyone').forEach(acl => acls.push(acl)); + return acls; + }; +}; diff --git a/back/models/vn-user.js b/back/models/vn-user.js index b59f13ffa..08a4daf54 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -15,6 +15,7 @@ module.exports = function(Self) { require('../methods/vn-user/renew-token')(Self); require('../methods/vn-user/share-token')(Self); require('../methods/vn-user/update-user')(Self); + require('../methods/vn-user/acls')(Self); Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create'); diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 5f6ac3f47..ebd2ea2f3 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -133,6 +133,13 @@ "principalType": "ROLE", "principalId": "$authenticated", "permission": "ALLOW" + }, + { + "property": "acls", + "accessType": "*", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" } ], "scopes": { -- 2.40.1 From 883f6f18a3b48560e82446251453057f5ef4a894 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 3 May 2024 13:47:55 +0200 Subject: [PATCH 032/413] refactor: refs #6701 Refactor claim_ratio_routine --- db/routines/vn/procedures/claimRatio_add.sql | 171 ++++++++++++------- 1 file changed, 108 insertions(+), 63 deletions(-) diff --git a/db/routines/vn/procedures/claimRatio_add.sql b/db/routines/vn/procedures/claimRatio_add.sql index 2f64f8c7e..deb5cc068 100644 --- a/db/routines/vn/procedures/claimRatio_add.sql +++ b/db/routines/vn/procedures/claimRatio_add.sql @@ -7,57 +7,82 @@ BEGIN * cargos que luego vamos a utilizar para calcular el recobro */ DECLARE vMonthToRefund INT DEFAULT 4; - DECLARE vRecoveryGreugeType INT; + DECLARE vRecoveryGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'recovery'); + DECLARE vManaGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'mana'); + DECLARE vClaimGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'claim'); + DECLARE vDebtComponentType INT + DEFAULT (SELECT id FROM component WHERE code = 'debtCollection'); - SELECT id INTO vRecoveryGreugeType - FROM greugeType - WHERE code = 'recovery'; + IF vRecoveryGreugeType IS NULL + OR vManaGreugeType IS NULL + OR vClaimGreugeType IS NULL + OR vDebtComponentType IS NULL THEN + + CALL util.throw('Required variables not found'); + END IF; -- Reclamaciones demasiado sensibles - INSERT INTO greuge(shipped, clientFk, description, - amount, greugeTypeFk, ticketFk) - SELECT c.ticketCreated - , c.clientFk - , concat('Claim ', c.id,' : ', s.concept) - ,round( -1 * ((c.responsibility -1)/4) * s.quantity * - s.price * (100 - s.discount) / 100, 2) - , 4 - , s.ticketFk - FROM sale s - JOIN claimEnd ce ON ce.saleFk = s.id - JOIN claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3; - - -- Reclamaciones que pasan a Maná - INSERT INTO greuge(shipped, - clientFk, - `description`, - amount, - greugeTypeFk, - ticketFk) + INSERT INTO greuge( + shipped, + clientFk, + `description`, + amount, + greugeTypeFk, + ticketFk + ) SELECT c.ticketCreated, c.clientFk, - concat('Claim_mana ',c.id,' : ', s.concept), - round( ((c.responsibility -1)/4) * s.quantity * s.price * (100 - s.discount) / 100, 2), - 3, + CONCAT('Claim ', c.id,' : ', s.concept), + ROUND(-1 * ((c.responsibility - 1) / 4) * s.quantity * + s.price * (100 - s.discount) / 100, 2), + vClaimGreugeType, s.ticketFk FROM sale s JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk JOIN claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE ce.claimDestinationFk NOT IN ('Bueno', 'Corregido') AND NOT ce.isGreuge - AND c.claimStateFk = 3 + AND cs.code = 'resolved'; + + -- Reclamaciones que pasan a Maná + INSERT INTO greuge( + shipped, + clientFk, + `description`, + amount, + greugeTypeFk, + ticketFk + ) + SELECT c.ticketCreated, + c.clientFk, + CONCAT('Claim_mana ', c.id,' : ', s.concept), + ROUND( ((c.responsibility -1)/4) * s.quantity * s.price * (100 - s.discount) / 100, 2), + vManaGreugeType, + s.ticketFk + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved' AND c.isChargedToMana; -- Marcamos para no repetir UPDATE claimEnd ce + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk SET c.isChargedToMana = TRUE - WHERE ce.claimDestinationFk NOT IN (1,5) + WHERE cd.description NOT IN ('Bueno', 'Corregido') AND NOT ce.isGreuge - AND c.claimStateFk = 3; + AND cs.code = 'resolved'; -- Recobros CREATE OR REPLACE TEMPORARY TABLE tTicketList @@ -69,23 +94,26 @@ BEGIN JOIN ticketLastState ts ON ts.ticketFk = t.id JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk JOIN state st ON st.id = tt.stateFk - WHERE sc.componentFk = 17 - AND sc.isGreuge = 0 + JOIN alertLevel al ON al.id = st.alertLevel + WHERE sc.componentFk = vDebtComponentType + AND NOT sc.isGreuge AND t.shipped >= '2016-10-01' AND t.shipped < util.VN_CURDATE() - AND st.alertLevel >= 3; + AND al.code = 'DELIVERED'; DELETE g.* FROM greuge g JOIN tTicketList t ON t.ticketFk = g.ticketFk WHERE g.greugeTypeFk = vRecoveryGreugeType; - INSERT INTO greuge(clientFk, - `description`, - amount, - shipped, - greugeTypeFk, - ticketFk) + INSERT INTO greuge( + clientFk, + `description`, + amount, + shipped, + greugeTypeFk, + ticketFk + ) SELECT t.clientFk, 'Recobro', - ROUND(SUM(sc.value * s.quantity), 2) dif, @@ -96,51 +124,68 @@ BEGIN JOIN ticket t ON t.id = s.ticketFk JOIN tTicketList tl ON tl.ticketFk = t.id JOIN saleComponent sc ON sc.saleFk = s.id - AND sc.componentFk = 17 + AND sc.componentFk = vDebtComponentType GROUP BY t.id - HAVING ABS(dif) > 1; + HAVING ABS(dif) > 1; UPDATE saleComponent sc JOIN sale s ON s.id = sc.saleFk JOIN tTicketList tl ON tl.ticketFk = s.ticketFk SET sc.isGreuge = TRUE - WHERE sc.componentFk = 17; + WHERE sc.componentFk = vDebtComponentType; /* * Recalculamos la ratio de las reclamaciones, que luego * se va a utilizar en el recobro */ - REPLACE claimRatio(clientFk, yearSale, claimAmount, claimingRate, priceIncreasing) - SELECT id, 0, 0, 0, 0 - FROM client; + REPLACE claimRatio( + clientFk, + yearSale, + claimAmount, + claimingRate, + priceIncreasing + ) + SELECT id, 0, 0, 0, 0 FROM client; - REPLACE claimRatio(clientFk, yearSale, claimAmount, claimingRate, priceIncreasing) - SELECT cac.clientFk, 12 * cac.invoiced, totalClaims, - ROUND(totalClaims / (12 * cac.invoiced), 4), 0 + REPLACE claimRatio( + clientFk, + yearSale, + claimAmount, + claimingRate, + priceIncreasing + ) + SELECT cac.clientFk, + 12 * cac.invoiced, + totalClaims, + ROUND(totalClaims / (12 * cac.invoiced), 4), + 0 FROM bs.clientAnnualConsumption cac - LEFT JOIN( - SELECT c.clientFk, round(sum(-1 * ((c.responsibility -1)/4) * - s.quantity * s.price * (100 - s.discount) / 100)) - totalClaims + LEFT JOIN ( + SELECT c.clientFk, + ROUND(SUM(-1 * ((c.responsibility - 1) / 4) * + s.quantity * s.price * (100 - s.discount) + / 100)) totalClaims FROM sale s JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk JOIN claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND c.claimStateFk = 3 + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE ce.claimDestinationFk NOT IN ('Bueno', 'Corregido') + AND cs.code = 'resolved' AND c.ticketCreated >= util.VN_CURDATE() - INTERVAL 1 YEAR GROUP BY c.clientFk - ) claims ON claims.clientFk = fm.Id_Cliente; + ) sub ON sub.clientFk = cac.clientFk; -- Calculamos el porcentaje del recobro para añadirlo al precio de venta UPDATE claimRatio cr JOIN ( - SELECT clientFk, IFNULL(SUM(amount), 0) AS Greuge + SELECT clientFk, IFNULL(SUM(amount), 0) greuge FROM greuge WHERE shipped <= util.VN_CURDATE() GROUP BY clientFk - ) g ON g.clientFk = cr.clientFk - SET cr.priceIncreasing = GREATEST(0, round(IFNULL(Greuge, 0) / - (IFNULL(Consumo, 0) * vMonthToRefund / 12 ), 3)); + ) sub ON subg.clientFk = cr.clientFk + SET cr.priceIncreasing = GREATEST(0, ROUND(IFNULL(sub.greuge, 0) / + (IFNULL(cr.yearSale, 0) * vMonthToRefund / 12 ), 3)); -- Protección neonatos UPDATE claimRatio cr -- 2.40.1 From f0b814c79b895ee4ac6487a6a4494c35feaf8c64 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 3 May 2024 14:15:55 +0200 Subject: [PATCH 033/413] refactor: refs #6701 Refactor claim_ratio_routine --- db/dump/fixtures.before.sql | 6 +-- db/routines/vn/procedures/claimRatio_add.sql | 37 +++++++------------ .../11028-silverCarnation/00-firstScript.sql | 6 +++ 3 files changed, 22 insertions(+), 27 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 06e94c99e..6b8166caa 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -831,9 +831,9 @@ INSERT INTO `vn`.`config`(`id`, `mdbServer`, `fakeEmail`, `defaultersMaxAmount`, INSERT INTO `vn`.`greugeType`(`id`, `name`, `code`) VALUES (1, 'Diff', 'diff'), - (2, 'Recover', 'recover'), - (3, 'Mana', 'mana'), - (4, 'Reclaim', 'reclaim'), + (2, 'Recobro', 'recovery'), + (3, 'Maná', 'mana'), + (4, 'Reclamación', 'claim'), (5, 'Heritage', 'heritage'), (6, 'Miscellaneous', 'miscellaneous'), (7, 'Freight Pickup', 'freightPickUp'); diff --git a/db/routines/vn/procedures/claimRatio_add.sql b/db/routines/vn/procedures/claimRatio_add.sql index deb5cc068..36b9023da 100644 --- a/db/routines/vn/procedures/claimRatio_add.sql +++ b/db/routines/vn/procedures/claimRatio_add.sql @@ -2,9 +2,8 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`claimRatio_add`() BEGIN /* -* PAK 2015-11-20 -* Se trata de añadir a la tabla Greuges todos los -* cargos que luego vamos a utilizar para calcular el recobro +* Añade a la tabla greuges todos los cargos necesario y +* que luego lo utilizamos para calcular el recobro. */ DECLARE vMonthToRefund INT DEFAULT 4; DECLARE vRecoveryGreugeType INT @@ -61,7 +60,8 @@ BEGIN SELECT c.ticketCreated, c.clientFk, CONCAT('Claim_mana ', c.id,' : ', s.concept), - ROUND( ((c.responsibility -1)/4) * s.quantity * s.price * (100 - s.discount) / 100, 2), + ROUND(((c.responsibility - 1) / 4) * s.quantity * + s.price * (100 - s.discount) / 100, 2), vManaGreugeType, s.ticketFk FROM sale s @@ -134,20 +134,7 @@ BEGIN SET sc.isGreuge = TRUE WHERE sc.componentFk = vDebtComponentType; - /* - * Recalculamos la ratio de las reclamaciones, que luego - * se va a utilizar en el recobro - */ - REPLACE claimRatio( - clientFk, - yearSale, - claimAmount, - claimingRate, - priceIncreasing - ) - SELECT id, 0, 0, 0, 0 FROM client; - - REPLACE claimRatio( + INSERT INTO claimRatio( clientFk, yearSale, claimAmount, @@ -163,8 +150,8 @@ BEGIN LEFT JOIN ( SELECT c.clientFk, ROUND(SUM(-1 * ((c.responsibility - 1) / 4) * - s.quantity * s.price * (100 - s.discount) - / 100)) totalClaims + s.quantity * s.price * (100 - s.discount) + / 100)) totalClaims FROM sale s JOIN claimEnd ce ON ce.saleFk = s.id JOIN claimDestination cd ON cd.id = ce.claimDestinationFk @@ -183,17 +170,19 @@ BEGIN FROM greuge WHERE shipped <= util.VN_CURDATE() GROUP BY clientFk - ) sub ON subg.clientFk = cr.clientFk + ) sub ON sub.clientFk = cr.clientFk SET cr.priceIncreasing = GREATEST(0, ROUND(IFNULL(sub.greuge, 0) / - (IFNULL(cr.yearSale, 0) * vMonthToRefund / 12 ), 3)); + (IFNULL(cr.yearSale, 0) * vMonthToRefund / 12 ), 3)) + WHERE cr.dated = util.VN_CURDATE(); -- Protección neonatos UPDATE claimRatio cr JOIN firstTicketShipped fts ON fts.clientFk = cr.clientFk SET cr.priceIncreasing = 0, cr.claimingRate = 0 - WHERE fts.shipped > util.VN_CURDATE() - INTERVAL 1 MONTH; - + WHERE fts.shipped > util.VN_CURDATE() - INTERVAL 1 MONTH + AND cr.dated = util.VN_CURDATE(); + DROP TEMPORARY TABLE tTicketList; END$$ DELIMITER ; diff --git a/db/versions/11028-silverCarnation/00-firstScript.sql b/db/versions/11028-silverCarnation/00-firstScript.sql index f865b0caf..9d291f451 100644 --- a/db/versions/11028-silverCarnation/00-firstScript.sql +++ b/db/versions/11028-silverCarnation/00-firstScript.sql @@ -2,3 +2,9 @@ UPDATE IGNORE bs.nightTask SET `procedure` = 'claimRatio_add', `schema` = 'vn' WHERE `procedure` = 'claim_ratio_routine'; + +ALTER TABLE vn.claimRatio ADD dated DATE DEFAULT current_timestamp() NOT NULL; +ALTER TABLE vn.claimRatio CHANGE dated dated DATE DEFAULT current_timestamp() NOT NULL FIRST; +ALTER TABLE vn.claimRatio DROP FOREIGN KEY claimRatio_ibfk_1; +ALTER TABLE vn.claimRatio DROP PRIMARY KEY; +ALTER TABLE vn.claimRatio ADD CONSTRAINT claimRatio_pk PRIMARY KEY (dated,clientFk); -- 2.40.1 From 40b2c32a00a30e2eb5e4e38921c336b52cf6e8b0 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 3 May 2024 17:37:36 +0200 Subject: [PATCH 034/413] feat: refs #6243 show all cmr --- db/dump/.dump/data.sql | 2 +- .../route/{getExternalCmrs.js => cmrs.js} | 30 ++++--------------- modules/route/back/models/route.js | 2 +- print/templates/reports/cmr/sql/data.sql | 3 +- 4 files changed, 9 insertions(+), 28 deletions(-) rename modules/route/back/methods/route/{getExternalCmrs.js => cmrs.js} (87%) diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index 8c6794a5b..a5a95d565 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -1783,7 +1783,7 @@ INSERT INTO `ACL` VALUES (761,'Route','downloadZip','READ','ALLOW','ROLE','emplo INSERT INTO `ACL` VALUES (762,'Route','filter','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (763,'Route','getByWorker','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (764,'Route','getDeliveryPoint','READ','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (765,'Route','getExternalCmrs','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (765,'Route','cmrs','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (766,'Route','getSuggestedTickets','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (767,'Route','getTickets','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (768,'Route','guessPriority','WRITE','ALLOW','ROLE','employee'); diff --git a/modules/route/back/methods/route/getExternalCmrs.js b/modules/route/back/methods/route/cmrs.js similarity index 87% rename from modules/route/back/methods/route/getExternalCmrs.js rename to modules/route/back/methods/route/cmrs.js index b8cd1041a..814ff77c6 100644 --- a/modules/route/back/methods/route/getExternalCmrs.js +++ b/modules/route/back/methods/route/cmrs.js @@ -3,8 +3,8 @@ const buildFilter = require('vn-loopback/util/filter').buildFilter; const mergeFilters = require('vn-loopback/util/filter').mergeFilters; module.exports = Self => { - Self.remoteMethod('getExternalCmrs', { - description: 'Returns an array of external cmrs', + Self.remoteMethod('cmrs', { + description: 'Returns an array of cmrs', accessType: 'READ', accepts: [ { @@ -53,31 +53,14 @@ module.exports = Self => { root: true }, http: { - path: `/getExternalCmrs`, + path: `/cmrs`, verb: 'GET' } }); - Self.getExternalCmrs = async( - filter, - cmrFk, - ticketFk, - routeFk, - country, - clientFk, - hasCmrDms, - shipped, - options + Self.cmrs = async(filter, cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, shipped, options ) => { - const params = { - cmrFk, - ticketFk, - routeFk, - country, - clientFk, - hasCmrDms, - shipped, - }; + const params = {cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, shipped}; const conn = Self.dataSource.connector; let where = buildFilter(params, (param, value) => { @@ -124,8 +107,7 @@ module.exports = Self => { JOIN dmsType dt ON dt.id = d.dmsTypeFk WHERE dt.name = 'cmr' ) sub ON sub.ticketFk = t.id - WHERE co.code <> 'ES' - AND am.name <> 'ABONO' + WHERE am.name <> 'ABONO' AND w.code = 'ALG' AND t.cmrFk ) sub diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index bf1f26e74..ecc434108 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -15,7 +15,7 @@ module.exports = Self => { require('../methods/route/sendSms')(Self); require('../methods/route/downloadZip')(Self); require('../methods/route/cmr')(Self); - require('../methods/route/getExternalCmrs')(Self); + require('../methods/route/cmrs')(Self); require('../methods/route/downloadCmrsZip')(Self); require('../methods/route/cmrEmail')(Self); require('../methods/route/getExpeditionSummary')(Self); diff --git a/print/templates/reports/cmr/sql/data.sql b/print/templates/reports/cmr/sql/data.sql index e9500cc4b..09a42a718 100644 --- a/print/templates/reports/cmr/sql/data.sql +++ b/print/templates/reports/cmr/sql/data.sql @@ -39,8 +39,7 @@ SELECT c.id cmrFk, LEFT JOIN supplier s ON s.id = c.supplierFk LEFT JOIN country cou ON cou.id = s.countryFk LEFT JOIN company co ON co.id = c.companyFk - LEFT JOIN supplierAccount sa ON sa.id = co.supplierAccountFk - LEFT JOIN supplier s2 ON s2.id = sa.supplierFk + LEFT JOIN supplier s2 ON s2.id = c.companyFk LEFT JOIN country cou2 ON cou2.id = s2.countryFk LEFT JOIN `address` a ON a.id = c.addressToFk LEFT JOIN province p ON p.id = a.provinceFk -- 2.40.1 From 5a0882c2ac91c5ee7c9a1b087893822549d61a17 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 8 May 2024 10:59:19 +0200 Subject: [PATCH 035/413] refs #6861 feat:sectoCollection reserve --- .../collection_addWithReservation.sql | 11 ++++---- .../procedures/itemShelvingSale_reserve.sql | 2 ++ ...ShelvingSale_reserveBySectorCollection.sql | 15 ++++++++-- .../sectorCollection_getPartial.sql | 19 +++++++++++++ .../sectorCollection_hasSalesReserved.sql | 28 +++++++++++++++++++ db/versions/10852-pinkOak/00-firstScript.sql | 2 ++ 6 files changed, 70 insertions(+), 7 deletions(-) create mode 100644 db/routines/vn/procedures/sectorCollection_getPartial.sql create mode 100644 db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql diff --git a/db/routines/vn/procedures/collection_addWithReservation.sql b/db/routines/vn/procedures/collection_addWithReservation.sql index ac0721146..cc207b572 100644 --- a/db/routines/vn/procedures/collection_addWithReservation.sql +++ b/db/routines/vn/procedures/collection_addWithReservation.sql @@ -85,10 +85,11 @@ BEGIN CALL util.throw("No hay disponibilidad para el artículo seleccionado"); ELSE IF vSaleGroupFk THEN - INSERT INTO saleGroupDetail - SET saleFk = vSaleFk, - saleGroupFk = vSaleGroupFk, - COMMIT; - END IF; + INSERT INTO saleGroupDetail + SET saleFk = vSaleFk, + saleGroupFk = vSaleGroupFk; + COMMIT; + END IF; + END IF ; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingSale_reserve.sql b/db/routines/vn/procedures/itemShelvingSale_reserve.sql index afe65bd78..803059423 100644 --- a/db/routines/vn/procedures/itemShelvingSale_reserve.sql +++ b/db/routines/vn/procedures/itemShelvingSale_reserve.sql @@ -52,6 +52,7 @@ BEGIN FROM tmp.sale ts JOIN sale s ON s.id = ts.saleFk JOIN itemShelving ish ON ish.itemFk = s.itemFk + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id LEFT JOIN ( SELECT itemShelvingFk, SUM(quantity) reservedQuantity FROM itemShelvingSale @@ -64,6 +65,7 @@ BEGIN JOIN productionConfig pc WHERE w.id = vWarehouseFk AND NOT sc.isHideForPickers + AND iss.id IS NULL ORDER BY s.id, p.pickingOrder >= vLastPickingOrder, diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql b/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql index 52d83a75d..b8387d20c 100644 --- a/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql +++ b/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql @@ -8,6 +8,8 @@ BEGIN * * @param vSectorCollectionFk Identificador de sectorCollection */ + DECLARE vHasSales BOOL; + CREATE OR REPLACE TEMPORARY TABLE tmp.sale (INDEX(saleFk)) ENGINE = MEMORY @@ -18,9 +20,18 @@ BEGIN JOIN saleTracking str ON str.saleFk = s.id JOIN `state` st ON st.id = str.stateFk AND st.code = 'PREVIOUS_PREPARATION' + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id WHERE sc.sectorCollectionFk = vSectorCollectionFk - AND str.workerFk = account.myUser_getId(); + AND str.workerFk = account.myUser_getId() + AND iss.id IS NULL; - CALL itemShelvingSale_reserve(); + SELECT COUNT(*)INTO vHasSales + FROM tmp.sale; + + IF vHasSales THEN + CALL itemShelvingSale_reserve(); + ELSE + CALL util.throw ('There are not sales to reserve'); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/sectorCollection_getPartial.sql b/db/routines/vn/procedures/sectorCollection_getPartial.sql new file mode 100644 index 000000000..2f59f591a --- /dev/null +++ b/db/routines/vn/procedures/sectorCollection_getPartial.sql @@ -0,0 +1,19 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorCollection_getPartial`() +BEGIN +/** + * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas + * + */ + SELECT DISTINCT sc.id collectionFk, sc.created + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + LEFT JOIN vn.sale sl ON sl.id = sgd.saleFk + LEFT JOIN itemShelvingSale iss ON iss.saleFk = sl.id + WHERE sc.userFk = account.myUser_getId() + AND (ISNULL(scsg.sectorCollectionFk) + OR (NOT iss.isPicked)) + AND sc.created > util.VN_CURDATE() - INTERVAL 1 DAY; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql b/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql new file mode 100644 index 000000000..e0ef46a86 --- /dev/null +++ b/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql @@ -0,0 +1,28 @@ +CREATE DEFINER=`root`@`localhost` FUNCTION vn.sectorCollection_hasSalesReserved(vSelf INT) RETURNS tinyint(1) +DETERMINISTIC +BEGIN + +/** +* Devuelve si sectorCollection tiene reservas +* @param vSelf Id de sectorCollection +* +* returns BOOLEAN +*/ + + DECLARE vHasSalesReserved BOOLEAN; + + + SELECT DISTINCT COUNT(*)>0 INTO vHasSalesReserved + FROM vn.sectorCollection sc + JOIN vn.sectorCollectionSaleGroup scsg ON sc.id = scsg.sectorCollectionFk + JOIN vn.saleGroup sg ON sg.id = scsg.saleGroupFk + JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = sg.id + JOIN vn.sale s ON s.id = sgd.saleFk + JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + JOIN vn.saleTracking st ON st.saleFk = s.id + WHERE sc.id = vSelf; + + RETURN vHasSalesReserved; + +END$$ +DELIMITER ; diff --git a/db/versions/10852-pinkOak/00-firstScript.sql b/db/versions/10852-pinkOak/00-firstScript.sql index 7af48148c..369e32e92 100644 --- a/db/versions/10852-pinkOak/00-firstScript.sql +++ b/db/versions/10852-pinkOak/00-firstScript.sql @@ -3,6 +3,8 @@ ALTER TABLE vn.itemShelvingSale DROP COLUMN IF EXISTS isPicked; ALTER TABLE vn.itemShelvingSale ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; +UPDATE vn.itemShelvingSale SET isPicked = TRUE; + ALTER TABLE vn.productionConfig DROP COLUMN IF EXISTS orderMode; ALTER TABLE vn.productionConfig -- 2.40.1 From 679f9a1b9b6427ac55982d489ca20c80f14968ff Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 9 May 2024 07:07:10 +0200 Subject: [PATCH 036/413] refs #6861 feat:sectoCollection reserve --- .../vn/procedures/sectorCollection_hasSalesReserved.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql b/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql index e0ef46a86..0de49e90c 100644 --- a/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql +++ b/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql @@ -1,4 +1,5 @@ -CREATE DEFINER=`root`@`localhost` FUNCTION vn.sectorCollection_hasSalesReserved(vSelf INT) RETURNS tinyint(1) +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION vn.sectorCollection_hasSalesReserved(vSelf INT) RETURNS tinyint(1) DETERMINISTIC BEGIN -- 2.40.1 From 1ea357a5dd5ac3ec047b14a89992fe63ac02a8bd Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 May 2024 10:01:46 +0200 Subject: [PATCH 037/413] feat: refs #7126 Refactor and added columns in bs.waste table & proc --- db/dump/fixtures.before.sql | 32 ++++----- db/routines/bs/procedures/waste_addSales.sql | 67 ++++++++++++------- .../00-firstScript.sql | 22 ++++++ 3 files changed, 80 insertions(+), 41 deletions(-) create mode 100644 db/versions/11042-turquoiseAspidistra/00-firstScript.sql diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 06e94c99e..1f023f19c 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1473,23 +1473,23 @@ INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 0, 'observation seven'), (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, 1, ''); -INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleWaste`, `rate`) +INSERT INTO `bs`.`waste`(`buyerFk`, `year`, `week`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleQuantity`, `saleInternalWaste`, `saleExternalWaste`) VALUES - ('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Carnation', 1, 1, '1062', '51', '4.8'), - ('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Carnation Colombia', 2, 1, '35074', '687', '2.0'), - ('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Carnation Mini', 3, 1, '1777', '13', '0.7'), - ('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Carnation Short', 4, 1, '3182', '59', '0.6'), - ('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Crisantemo', 5, 1, '1747', '13', '0.7'), - ('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Lilium Oriental', 6, 1, '7182', '59', '0.6'), - ('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Alstroemeria', 7, 1, '1777', '13', '0.7'), - ('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Cymbidium', 1, 1, '4181', '59', '0.6'), - ('CharlesXavier', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Cymbidium', 2, 1, '7268', '59', '0.6'), - ('DavidCharlesHaller', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Containers', 2, 1, '-74', '0', '0.0'), - ('DavidCharlesHaller', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Packagings', 3, 1, '-7', '0', '0.0'), - ('DavidCharlesHaller', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Freight', 4, 1, '1100', '0', '0.0'), - ('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Funeral Accessories', 5, 1, '848', '-187', '-22.1'), - ('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Miscellaneous Accessories', 6, 1, '186', '0', '0.0'), - ('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Adhesives', 7, 1, '277', '0', '0.0'); + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 1, 1, '1062', '51', '56.20', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '35074', '687', '53.12', '89.69'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 3, 1, '1777', '13', '12.02', '53.12'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 4, 1, '3182', '59', '51', '56.20'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 5, 1, '1747', '13', '53.12', '53.12'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 6, 1, '7182', '59', '51', '53.12'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 7, 1, '1777', '13', '89.69', '89.69'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 8, 1, '4181', '59', '53.12', '53.12'), + ('35', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 9, 1, '7268', '59', '12.02', '56.20'), + ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 2, 1, '-74', '0', '51', '89.69'), + ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 3, 1, '-7', '0', '12.02', '53.12'), + ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 4, 1, '1100', '0', '51', '56.20'), + ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 5, 1, '848', '-187', '12.02', '89.69'), + ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 6, 1, '186', '0', '51', '53.12'), + ('103', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 7, 1, '277', '0', '53.12', '56.20'); INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packagingFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) VALUES diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index 0ab328b49..b705208c3 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -1,31 +1,48 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`() BEGIN - DECLARE vWeek INT; - DECLARE vYear INT; - - SELECT week, year - INTO vWeek, vYear - FROM vn.time - WHERE dated = util.VN_CURDATE(); - REPLACE bs.waste - SELECT *, 100 * mermas / total as porcentaje - FROM ( - SELECT buyer, - year, - week, - family, - itemFk, - itemTypeFk, - floor(sum(value)) as total, - floor(sum(IF(typeFk = 'loses', value, 0))) as mermas - FROM vn.saleValue - where year = vYear and week = vWeek - - GROUP BY family, itemFk - - ) sub - ORDER BY mermas DESC; + SELECT YEAR(t.shipped), + WEEK(t.shipped, 4), + it.workerFk, + it.id, + s.itemFk, + SUM(s.quantity), + SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) value, + SUM ( + IF( + a.nickname IN ( + 'MERMA: FALTAS', + 'MERMA: CONTENEDOR', + 'MERMA: TRANSPORTE/OTROS' + ), + (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, + 0 + ) + ) internalWaste, + SUM ( + IF( + a.nickname IN ( + 'MERMA: RECLAMACION BASURA', + 'MERMA: RECLAMACION TALLER', + 'MERMA: RECLAMACION FALTAS' + ), + (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, + 0 + ) + ) externalWaste + FROM vn.sale s + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.ticket t ON t.id = s.ticketFk + STRAIGHT_JOIN vn.address a ON a.id = t.addressFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN cache.last_buy lb ON lb.item_id = i.id + AND lb.warehouse_id = w.id + JOIN vn.buy b ON b.id = lb.buy_id + WHERE w.isManaged + AND YEAR(t.shipped) = YEAR(util.VN_CURDATE()) + AND WEEK(t.shipped, 4) = WEEK(util.VN_CURDATE(), 4) + GROUP BY it.id, s.itemFk END$$ DELIMITER ; diff --git a/db/versions/11042-turquoiseAspidistra/00-firstScript.sql b/db/versions/11042-turquoiseAspidistra/00-firstScript.sql new file mode 100644 index 000000000..5a0b23bc9 --- /dev/null +++ b/db/versions/11042-turquoiseAspidistra/00-firstScript.sql @@ -0,0 +1,22 @@ +ALTER TABLE bs.waste ADD buyerFk int(10) unsigned NOT NULL; + +UPDATE bs.waste w + JOIN account.`user` u ON u.name = w.buyer COLLATE utf8mb3_unicode_ci + SET w.buyerFk = u.id; + +ALTER TABLE bs.waste + DROP PRIMARY KEY, + DROP COLUMN family, + DROP COLUMN rate, + DROP COLUMN buyer; + +ALTER TABLE bs.waste CHANGE buyerFk buyerFk int(10) unsigned NOT NULL AFTER `week`; +ALTER TABLE bs.waste ADD CONSTRAINT waste_user_FK FOREIGN KEY (buyerFk) REFERENCES account.user(id) ON DELETE RESTRICT ON UPDATE RESTRICT; +ALTER TABLE bs.waste ADD saleQuantity int(11) DEFAULT NULL NULL; +ALTER TABLE bs.waste MODIFY COLUMN saleTotal decimal(10,2) DEFAULT NULL NULL; +ALTER TABLE bs.waste MODIFY COLUMN saleWaste decimal(10,2) DEFAULT NULL NULL; +ALTER TABLE bs.waste CHANGE saleWaste saleInternalWaste decimal(10,2) DEFAULT NULL NULL; +ALTER TABLE bs.waste ADD saleExternalWaste decimal(10,2) DEFAULT NULL NULL; +ALTER TABLE bs.waste CHANGE saleQuantity saleQuantity decimal(10,2) DEFAULT NULL NULL AFTER itemTypeFk; +ALTER TABLE bs.waste CHANGE itemFk itemFk int(11) DEFAULT 0 NOT NULL AFTER itemTypeFk; +ALTER TABLE bs.waste ADD CONSTRAINT waste_pk PRIMARY KEY (`year`, `week`, buyerFk, itemTypeFk, itemFk); \ No newline at end of file -- 2.40.1 From eea04520adac7fa085296bd9426fd6f4db9a8da9 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 May 2024 10:05:02 +0200 Subject: [PATCH 038/413] Fix: refs #7126 Fix proc --- db/routines/bs/procedures/waste_addSales.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index b705208c3..5b7f620c7 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -43,6 +43,6 @@ BEGIN WHERE w.isManaged AND YEAR(t.shipped) = YEAR(util.VN_CURDATE()) AND WEEK(t.shipped, 4) = WEEK(util.VN_CURDATE(), 4) - GROUP BY it.id, s.itemFk + GROUP BY it.id, s.itemFk; END$$ DELIMITER ; -- 2.40.1 From b1e136aa47cbbb585431de51eae40bfab757d673 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 May 2024 11:05:20 +0200 Subject: [PATCH 039/413] Fix: refs #7126 Tests back --- .../item/back/methods/item/getWasteByItem.js | 42 ++++++++++------ .../back/methods/item/getWasteByWorker.js | 48 +++++++++++-------- .../methods/item/specs/getWasteByItem.spec.js | 8 ++-- .../item/specs/getWasteByWorker.spec.js | 6 +-- .../buyer-week-waste/sql/wasteWeekly.sql | 18 +++---- 5 files changed, 72 insertions(+), 50 deletions(-) diff --git a/modules/item/back/methods/item/getWasteByItem.js b/modules/item/back/methods/item/getWasteByItem.js index 56b90b04a..548f28008 100644 --- a/modules/item/back/methods/item/getWasteByItem.js +++ b/modules/item/back/methods/item/getWasteByItem.js @@ -27,28 +27,42 @@ module.exports = Self => { }); Self.getWasteByItem = async(buyer, family, options) => { + const models = Self.app.models; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); + const user = await models.VnUser.findOne({ + fields: ['id'], + where: {name: buyer} + }); + + const itemType = await models.ItemType.findOne({ + fields: ['id'], + where: {name: family} + }, options); + const date = Date.vnNew(); date.setHours(0, 0, 0, 0); const wastes = await Self.rawSql(` - SELECT *, 100 * dwindle / total AS percentage - FROM ( - SELECT buyer, - ws.family, - ws.itemFk, - sum(ws.saleTotal) AS total, - sum(ws.saleWaste) AS dwindle - FROM bs.waste ws - WHERE buyer = ? AND family = ? - AND year = YEAR(TIMESTAMPADD(WEEK,-1, ?)) - AND week = WEEK(TIMESTAMPADD(WEEK,-1, ?), 1) - GROUP BY buyer, itemFk - ) sub - ORDER BY family, percentage DESC`, [buyer, family, date, date], myOptions); + SELECT *, 100 * dwindle / total percentage + FROM ( + SELECT u.name buyer, + it.name family, + w.itemFk, + SUM(w.saleTotal) total, + SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle + FROM bs.waste w + JOIN account.user u ON u.id = w.buyerFk + JOIN vn.itemType it ON it.id = w.itemTypeFk + WHERE w.buyerFk = ? AND w.itemTypeFk = ? + AND w.year = YEAR(TIMESTAMPADD(WEEK, -1, ?)) + AND w.week = WEEK(TIMESTAMPADD(WEEK, -1, ?), 1) + GROUP BY w.buyerFk, w.itemFk + ) sub + ORDER BY family, percentage DESC + `, [user.id, itemType.id, date, date], myOptions); const details = []; diff --git a/modules/item/back/methods/item/getWasteByWorker.js b/modules/item/back/methods/item/getWasteByWorker.js index 8fa351eed..9af49478f 100644 --- a/modules/item/back/methods/item/getWasteByWorker.js +++ b/modules/item/back/methods/item/getWasteByWorker.js @@ -22,31 +22,37 @@ module.exports = Self => { const date = Date.vnNew(); date.setHours(0, 0, 0, 0); const wastes = await Self.rawSql(` - SELECT *, 100 * dwindle / total AS percentage - FROM ( - SELECT buyer, - ws.family, - sum(ws.saleTotal) AS total, - sum(ws.saleWaste) AS dwindle - FROM bs.waste ws - WHERE year = YEAR(TIMESTAMPADD(WEEK,-1, ?)) - AND week = WEEK(TIMESTAMPADD(WEEK,-1, ?), 1) - GROUP BY buyer, family - ) sub - ORDER BY percentage DESC`, [date, date], myOptions); + SELECT *, 100 * dwindle / total percentage + FROM ( + SELECT u.name buyer, + it.name family, + w.itemFk, + SUM(w.saleTotal) total, + SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle + FROM bs.waste w + JOIN account.user u ON u.id = w.buyerFk + JOIN vn.itemType it ON it.id = w.itemTypeFk + WHERE year = YEAR(TIMESTAMPADD(WEEK, -1, ?)) + AND week = WEEK(TIMESTAMPADD(WEEK, -1, ?), 1) + GROUP BY buyerFk, itemTypeFk + ) sub + ORDER BY percentage DESC + `, [date, date], myOptions); const wastesTotal = await Self.rawSql(` - SELECT *, 100 * dwindle / total AS percentage + SELECT *, 100 * dwindle / total percentage FROM ( - SELECT buyer, - sum(ws.saleTotal) AS total, - sum(ws.saleWaste) AS dwindle - FROM bs.waste ws - WHERE year = YEAR(TIMESTAMPADD(WEEK,-1, ?)) - AND week = WEEK(TIMESTAMPADD(WEEK,-1, ?), 1) - GROUP BY buyer + SELECT u.name buyer, + SUM(w.saleTotal) total, + SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle + FROM bs.waste w + JOIN account.user u ON u.id = w.buyerFk + WHERE w.year = YEAR(TIMESTAMPADD(WEEK, -1, ?)) + AND w.week = WEEK(TIMESTAMPADD(WEEK, -1, ?), 1) + GROUP BY w.buyerFk ) sub - ORDER BY percentage DESC`, [date, date], myOptions); + ORDER BY percentage DESC + `, [date, date], myOptions); const details = []; diff --git a/modules/item/back/methods/item/specs/getWasteByItem.spec.js b/modules/item/back/methods/item/specs/getWasteByItem.spec.js index 68ba02887..ac3d6c8af 100644 --- a/modules/item/back/methods/item/specs/getWasteByItem.spec.js +++ b/modules/item/back/methods/item/specs/getWasteByItem.spec.js @@ -1,18 +1,18 @@ const models = require('vn-loopback/server/server').models; -describe('Item getWasteByItem()', () => { +fdescribe('Item getWasteByItem()', () => { it('should check for the waste breakdown by worker and item', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const result = await models.Item.getWasteByItem('CharlesXavier', 'Cymbidium', options); + const result = await models.Item.getWasteByItem('buyer', 'Crisantemo', options); const length = result.length; const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; - expect(anyResult.buyer).toEqual('CharlesXavier'); - expect(anyResult.family).toEqual('Cymbidium'); + expect(anyResult.buyer).toEqual('buyer'); + expect(anyResult.family).toEqual('Crisantemo'); expect(anyResult.lines.length).toBeGreaterThanOrEqual(2); await tx.rollback(); diff --git a/modules/item/back/methods/item/specs/getWasteByWorker.spec.js b/modules/item/back/methods/item/specs/getWasteByWorker.spec.js index 52f806bd3..4dbd5b14b 100644 --- a/modules/item/back/methods/item/specs/getWasteByWorker.spec.js +++ b/modules/item/back/methods/item/specs/getWasteByWorker.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -describe('Item getWasteByWorker()', () => { +fdescribe('Item getWasteByWorker()', () => { it('should check for the waste breakdown for every worker', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; @@ -11,9 +11,9 @@ describe('Item getWasteByWorker()', () => { const length = result.length; const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; - expect(anyResult.buyer).toMatch(/(CharlesXavier|HankPym|DavidCharlesHaller)/); + expect(anyResult.buyer).toMatch(/(buyer|it)/); expect(anyResult.total).toBeGreaterThanOrEqual(1000); - expect(anyResult.lines.length).toBeGreaterThanOrEqual(3); + expect(anyResult.lines.length).toBeGreaterThanOrEqual(1); await tx.rollback(); } catch (e) { diff --git a/print/templates/email/buyer-week-waste/sql/wasteWeekly.sql b/print/templates/email/buyer-week-waste/sql/wasteWeekly.sql index 943c085d0..1b486a004 100644 --- a/print/templates/email/buyer-week-waste/sql/wasteWeekly.sql +++ b/print/templates/email/buyer-week-waste/sql/wasteWeekly.sql @@ -1,11 +1,13 @@ -SELECT *, 100 * dwindle / total AS percentage +SELECT *, 100 * dwindle / total `percentage` FROM ( - SELECT buyer, - sum(saleTotal) as total, - sum(saleWaste) as dwindle + SELECT u.name buyer, + SUM(saleTotal) total, + SUM(w.saleInternalWaste + w.saleExternalWaste) dwindle FROM bs.waste w - JOIN vn.time t ON w.year = t.year AND w.week = t.week - WHERE t.dated = DATE_ADD(CURDATE(), INTERVAL -1 WEEK) - GROUP BY buyer + JOIN account.user u ON u.id = w.buyerFk + JOIN vn.itemType it ON it.id = w.itemTypeFk + WHERE w.year = YEAR(util.VN_CURDATE() - INTERVAL 1 WEEK) + AND w.week = WEEK(util.VN_CURDATE() - INTERVAL 1 WEEK, 4) + GROUP BY buyerFk ) sub - ORDER BY percentage DESC; \ No newline at end of file + ORDER BY `percentage` DESC; -- 2.40.1 From 13ed86d26d235538ed43d5e14182b2e849b15d07 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 May 2024 11:06:49 +0200 Subject: [PATCH 040/413] Fix: refs #7126 Tests back --- modules/item/back/methods/item/specs/getWasteByItem.spec.js | 2 +- modules/item/back/methods/item/specs/getWasteByWorker.spec.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/item/back/methods/item/specs/getWasteByItem.spec.js b/modules/item/back/methods/item/specs/getWasteByItem.spec.js index ac3d6c8af..51ee28a33 100644 --- a/modules/item/back/methods/item/specs/getWasteByItem.spec.js +++ b/modules/item/back/methods/item/specs/getWasteByItem.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -fdescribe('Item getWasteByItem()', () => { +describe('Item getWasteByItem()', () => { it('should check for the waste breakdown by worker and item', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; diff --git a/modules/item/back/methods/item/specs/getWasteByWorker.spec.js b/modules/item/back/methods/item/specs/getWasteByWorker.spec.js index 4dbd5b14b..fba35d716 100644 --- a/modules/item/back/methods/item/specs/getWasteByWorker.spec.js +++ b/modules/item/back/methods/item/specs/getWasteByWorker.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -fdescribe('Item getWasteByWorker()', () => { +describe('Item getWasteByWorker()', () => { it('should check for the waste breakdown for every worker', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; -- 2.40.1 From 4d1031e0313cce0eb1bd06362878fdb28e8bf206 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 10 May 2024 13:20:15 +0200 Subject: [PATCH 041/413] feat: refs #7126 Added manaClaim calc --- db/routines/bs/procedures/waste_addSales.sql | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index 5b7f620c7..07ae088e5 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -28,7 +28,10 @@ BEGIN 'MERMA: RECLAMACION FALTAS' ), (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, - 0 + IF(c.code = 'manaClaim', + sc.value * s.quantity, + 0 + ) ) ) externalWaste FROM vn.sale s @@ -40,9 +43,11 @@ BEGIN JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = w.id JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN component c ON c.id = sc.componentFk WHERE w.isManaged AND YEAR(t.shipped) = YEAR(util.VN_CURDATE()) AND WEEK(t.shipped, 4) = WEEK(util.VN_CURDATE(), 4) - GROUP BY it.id, s.itemFk; + GROUP BY it.id, i.id; END$$ DELIMITER ; -- 2.40.1 From 5abc95af5122b53b4e03d412ba284bd288060034 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 17 May 2024 11:29:16 +0200 Subject: [PATCH 042/413] feat: refs #6598 back test --- back/methods/vn-user/specs/acls.spec.js | 36 +++++++++++++++++++++++++ back/tests-helper.js | 1 + 2 files changed, 37 insertions(+) create mode 100644 back/methods/vn-user/specs/acls.spec.js diff --git a/back/methods/vn-user/specs/acls.spec.js b/back/methods/vn-user/specs/acls.spec.js new file mode 100644 index 000000000..486d23bca --- /dev/null +++ b/back/methods/vn-user/specs/acls.spec.js @@ -0,0 +1,36 @@ +const {models} = require('vn-loopback/server/server'); +const id = {administrative: 5, employee: 1, productionBoss: 50}; + +describe('VnUser acls()', () => { + it('should get its owns acls', async() => { + const hasAdministrativeAcls = await hasAcl('administrative', id.administrative); + const hasProductionBossAcls = await hasAcl('productionBoss', id.productionBoss); + + expect(hasAdministrativeAcls).toBeTruthy(); + expect(hasProductionBossAcls).toBeTruthy(); + }); + + it('should not get administrative acls', async() => { + const hasAdministrativeAcls = await hasAcl('administrative', id.employee); + + expect(hasAdministrativeAcls).toBeFalsy(); + }); + + it('should get the $authenticated acls', async() => { + const hasAuthAcls = await hasAcl('$authenticated', id.employee); + + expect(hasAuthAcls).toBeTruthy(); + }); + + it('should get the $everyone acls', async() => { + const hasEveryoneAcls = await hasAcl('$everyone', id.employee); + + expect(hasEveryoneAcls).toBeTruthy(); + }); +}); + +const hasAcl = async(role, userId) => { + const ctx = {req: {accessToken: {userId}, headers: {origin: 'http://localhost'}}}; + const acls = await models.VnUser.acls(ctx); + return Object.values(acls).some(acl => acl.principalId === role); +}; diff --git a/back/tests-helper.js b/back/tests-helper.js index b88fa1fd6..6d465bc2a 100644 --- a/back/tests-helper.js +++ b/back/tests-helper.js @@ -17,6 +17,7 @@ async function init() { err => err ? reject(err) : resolve()); }); // FIXME: Workaround to wait for loopback to be ready + app.emit('started'); await app.models.Application.status(); } -- 2.40.1 From 0e51fa861cb4ce8707ad2106ad5204f0a5c41706 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 17 May 2024 11:35:29 +0200 Subject: [PATCH 043/413] fix: refs #6598 drop variables --- back/methods/vn-user/specs/acls.spec.js | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/back/methods/vn-user/specs/acls.spec.js b/back/methods/vn-user/specs/acls.spec.js index 486d23bca..0349b39fb 100644 --- a/back/methods/vn-user/specs/acls.spec.js +++ b/back/methods/vn-user/specs/acls.spec.js @@ -3,29 +3,20 @@ const id = {administrative: 5, employee: 1, productionBoss: 50}; describe('VnUser acls()', () => { it('should get its owns acls', async() => { - const hasAdministrativeAcls = await hasAcl('administrative', id.administrative); - const hasProductionBossAcls = await hasAcl('productionBoss', id.productionBoss); - - expect(hasAdministrativeAcls).toBeTruthy(); - expect(hasProductionBossAcls).toBeTruthy(); + expect(await hasAcl('administrative', id.administrative)).toBeTruthy(); + expect(await hasAcl('productionBoss', id.productionBoss)).toBeTruthy(); }); it('should not get administrative acls', async() => { - const hasAdministrativeAcls = await hasAcl('administrative', id.employee); - - expect(hasAdministrativeAcls).toBeFalsy(); + expect(await hasAcl('administrative', id.employee)).toBeFalsy(); }); it('should get the $authenticated acls', async() => { - const hasAuthAcls = await hasAcl('$authenticated', id.employee); - - expect(hasAuthAcls).toBeTruthy(); + expect(await hasAcl('$authenticated', id.employee)).toBeTruthy(); }); it('should get the $everyone acls', async() => { - const hasEveryoneAcls = await hasAcl('$everyone', id.employee); - - expect(hasEveryoneAcls).toBeTruthy(); + expect(await hasAcl('$everyone', id.employee)).toBeTruthy(); }); }); -- 2.40.1 From 1f1a49d0a56cb67ca15c207e43347587cfc0c01e Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 17 May 2024 14:20:33 +0200 Subject: [PATCH 044/413] refactor: refs #6889 use addSale --- modules/ticket/back/methods/ticket/addSale.js | 8 ++- .../back/methods/ticket/addSaleByCode.js | 56 ------------------- .../ticket/specs/addSaleByCode.spec.js | 39 ------------- modules/ticket/back/models/ticket-methods.js | 1 - modules/ticket/front/sale/index.js | 2 +- modules/ticket/front/sale/index.spec.js | 2 +- 6 files changed, 7 insertions(+), 101 deletions(-) delete mode 100644 modules/ticket/back/methods/ticket/addSaleByCode.js delete mode 100644 modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 826de6e12..8dc7a633c 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -10,8 +10,8 @@ module.exports = Self => { http: {source: 'path'} }, { - arg: 'itemId', - type: 'number', + arg: 'barcode', + type: 'any', required: true }, { @@ -29,7 +29,7 @@ module.exports = Self => { } }); - Self.addSale = async(ctx, id, itemId, quantity, options) => { + Self.addSale = async(ctx, id, barcode, quantity, options) => { const $t = ctx.req.__; // $translate const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; @@ -46,7 +46,9 @@ module.exports = Self => { try { await models.Ticket.isEditableOrThrow(ctx, id, myOptions); + const itemId = await models.ItemBarcode.toItem(barcode, myOptions); const item = await models.Item.findById(itemId, null, myOptions); + const ticket = await models.Ticket.findById(id, { include: { relation: 'client', diff --git a/modules/ticket/back/methods/ticket/addSaleByCode.js b/modules/ticket/back/methods/ticket/addSaleByCode.js deleted file mode 100644 index ca3d2cb07..000000000 --- a/modules/ticket/back/methods/ticket/addSaleByCode.js +++ /dev/null @@ -1,56 +0,0 @@ -const UserError = require('vn-loopback/util/user-error'); -module.exports = Self => { - Self.remoteMethodCtx('addSaleByCode', { - description: 'Add a collection', - accessType: 'WRITE', - accepts: [ - { - arg: 'barcode', - type: 'string', - required: true - }, { - arg: 'quantity', - type: 'number', - required: true - }, { - arg: 'ticketFk', - type: 'number', - required: true - }, { - arg: 'warehouseFk', - type: 'number', - required: true - }, - - ], - http: { - path: `/addSaleByCode`, - verb: 'POST' - }, - }); - - Self.addSaleByCode = async(ctx, barcode, quantity, ticketFk, warehouseFk, options) => { - const myOptions = {userId: ctx.req.accessToken.userId}; - 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(?,?)', [barcode, 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) { - if (tx) await tx.rollback(); - throw e; - } - }; -}; diff --git a/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js b/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js deleted file mode 100644 index b97139178..000000000 --- a/modules/ticket/back/methods/ticket/specs/addSaleByCode.spec.js +++ /dev/null @@ -1,39 +0,0 @@ -const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); - -describe('Ticket addSaleByCode()', () => { - const quantity = 3; - const ticketFk = 13; - 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.Ticket.beginTransaction({}); - - try { - const options = {transaction: tx}; - const code = '1111111111'; - - const salesBefore = await models.Sale.find(null, 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); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -}); diff --git a/modules/ticket/back/models/ticket-methods.js b/modules/ticket/back/models/ticket-methods.js index 0ae2ce3b4..5582dde5c 100644 --- a/modules/ticket/back/models/ticket-methods.js +++ b/modules/ticket/back/models/ticket-methods.js @@ -46,6 +46,5 @@ module.exports = function(Self) { require('../methods/ticket/invoiceTicketsAndPdf')(Self); require('../methods/ticket/docuwareDownload')(Self); require('../methods/ticket/myLastModified')(Self); - require('../methods/ticket/addSaleByCode')(Self); require('../methods/ticket/clone')(Self); }; diff --git a/modules/ticket/front/sale/index.js b/modules/ticket/front/sale/index.js index 1cd5560a4..7ff8d89e3 100644 --- a/modules/ticket/front/sale/index.js +++ b/modules/ticket/front/sale/index.js @@ -476,7 +476,7 @@ class Controller extends Section { */ addSale(sale) { const data = { - itemId: sale.itemFk, + barcode: sale.itemFk, quantity: sale.quantity }; const query = `tickets/${this.ticket.id}/addSale`; diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js index fb1c925d4..8200d6b89 100644 --- a/modules/ticket/front/sale/index.spec.js +++ b/modules/ticket/front/sale/index.spec.js @@ -659,7 +659,7 @@ describe('Ticket', () => { jest.spyOn(controller, 'resetChanges').mockReturnThis(); const newSale = {itemFk: 4, quantity: 10}; - const expectedParams = {itemId: 4, quantity: 10}; + const expectedParams = {barcode: 4, quantity: 10}; const expectedResult = { id: 30, quantity: 10, -- 2.40.1 From 49fed4e51e45f1d203ca43f13ed3c4cb02cd5cb2 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 22 May 2024 12:23:33 +0200 Subject: [PATCH 045/413] refs #6964 feat: hasItemOlder --- db/versions/11064-grayMedeola/00-firstScript.sql | 6 ++++++ .../back/methods/item-shelving/hasItemOlder.js | 15 ++++++++++----- 2 files changed, 16 insertions(+), 5 deletions(-) create mode 100644 db/versions/11064-grayMedeola/00-firstScript.sql diff --git a/db/versions/11064-grayMedeola/00-firstScript.sql b/db/versions/11064-grayMedeola/00-firstScript.sql new file mode 100644 index 000000000..301c0fef1 --- /dev/null +++ b/db/versions/11064-grayMedeola/00-firstScript.sql @@ -0,0 +1,6 @@ +-- Place your SQL code here + +USE vn; + +ALTER TABLE vn.sector ADD hasItemOlderReview BIGINT DEFAULT false NULL COMMENT 'Indica si el sector se revisa para comprobar si tiene ítems más viejos'; +ALTER TABLE vn.productionConfig ADD itemOlderReviewHours int(11) NULL COMMENT 'Horas que se tienen en cuenta para comprobar si un ítem es más viejo.'; diff --git a/modules/item/back/methods/item-shelving/hasItemOlder.js b/modules/item/back/methods/item-shelving/hasItemOlder.js index ee4cdc829..02cd14bb8 100644 --- a/modules/item/back/methods/item-shelving/hasItemOlder.js +++ b/modules/item/back/methods/item-shelving/hasItemOlder.js @@ -46,17 +46,22 @@ module.exports = Self => { SELECT COUNT(ish.id) countItemOlder FROM vn.itemShelving ish JOIN ( - SELECT ish.itemFk, created,shelvingFk + SELECT ish.itemFk, created, shelvingFk FROM vn.itemShelving ish JOIN vn.shelving s ON ish.shelvingFk = s.code + LEFT JOIN vn.parking p2 ON p2.id = s.parkingFk WHERE ish.shelvingFk = ? )sub ON sub.itemFK = ish.itemFk JOIN vn.shelving s ON s.code = ish.shelvingFk JOIN vn.parking p ON p.id = s.parkingFk - WHERE sub.created > ish.created - AND (p.code <> ? OR ? IS NULL) - AND (ish.shelvingFk <> ? OR ? IS NULL) - AND (ish.itemFk <> ? OR ? IS NULL)`, + JOIN vn.sector s2 ON s2.id = p.sectorFk + JOIN vn.productionConfig pc ON pc.itemOlderReviewHours + WHERE ish.created + INTERVAL pc.itemOlderReviewHours HOUR < sub.created + AND (p.code <> ? OR ? IS NULL) + AND (ish.shelvingFk <> ? OR ? IS NULL) + AND (ish.itemFk = ? OR ? IS NULL) + AND (p.pickingOrder < sub.pickingOrder OR sub.pickingOrder IS NULL) + AND (s2.hasItemOlderReview)`, [shelvingFkIn, parking, parking, shelvingFkOut, shelvingFkOut, itemFk, itemFk], myOptions); return result[0]['countItemOlder'] > 0; }; -- 2.40.1 From 22a6c3695c25958fc8c91ecbd19af3d4bfdedac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 22 May 2024 18:05:16 +0200 Subject: [PATCH 046/413] feat:concurrency issue refs #6861 --- .../vn/procedures/itemShelvingSale_addBySale.sql | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql index 3ad581b15..7e836859a 100644 --- a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql +++ b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql @@ -37,12 +37,12 @@ proc: BEGIN IF(pc.orderMode = 'Location', p.pickingOrder, ish.created); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; -/* DECLARE EXIT HANDLER FOR SQLEXCEPTION + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; -*/ + SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)) INTO vLastPickingOrder, vOutStanding FROM sale s @@ -67,6 +67,8 @@ proc: BEGIN LEAVE l; END IF; + START TRANSACTION; + SELECT id INTO vItemShelvingFk FROM itemShelving WHERE id = vItemShelvingFk @@ -76,7 +78,6 @@ proc: BEGIN SET vOutStanding = vOutStanding - vReservedQuantity; IF vReservedQuantity > 0 THEN - -- START TRANSACTION; INSERT INTO itemShelvingSale( itemShelvingFk, @@ -92,8 +93,9 @@ proc: BEGIN SET available = available - vReservedQuantity WHERE id = vItemShelvingFk; - -- COMMIT; END IF; + + COMMIT; END LOOP; CLOSE vItemShelvingAvailable; END$$ -- 2.40.1 From e902a84d10b66cb3a4cc032aa2baf445408ef4aa Mon Sep 17 00:00:00 2001 From: Jon Date: Thu, 23 May 2024 09:22:19 +0200 Subject: [PATCH 047/413] refactor: refs #5447 changed models --- back/models/country.json | 8 ++++++++ back/models/warehouse.json | 10 ++++++++++ loopback/locale/en.json | 9 +++++---- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/back/models/country.json b/back/models/country.json index a4c74d330..5b9d842a8 100644 --- a/back/models/country.json +++ b/back/models/country.json @@ -25,6 +25,9 @@ }, "isSocialNameUnique": { "type": "boolean" + }, + "continentFk": { + "type": "number" } }, "relations": { @@ -32,6 +35,11 @@ "type": "belongsTo", "model": "Currency", "foreignKey": "currencyFk" + }, + "continent": { + "type": "belongsTo", + "model": "Continent", + "foreignKey": "continentFk" } }, "acls": [ diff --git a/back/models/warehouse.json b/back/models/warehouse.json index dcbf7f2d2..f12b5e86e 100644 --- a/back/models/warehouse.json +++ b/back/models/warehouse.json @@ -24,6 +24,16 @@ }, "isManaged":{ "type": "boolean" + }, + "countryFk": { + "type": "number" + } + }, + "relations": { + "country": { + "type": "belongsTo", + "model": "Country", + "foreignKey": "countryFk" } }, "acls": [ diff --git a/loopback/locale/en.json b/loopback/locale/en.json index ca76eae42..601a26f5b 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -223,7 +223,8 @@ "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)", - "This password can only be changed by the user themselves": "This password can only be changed by the user themselves", - "They're not your subordinate": "They're not your subordinate", - "InvoiceIn is already booked": "InvoiceIn is already booked" -} + "This password can only be changed by the user themselves": "This password can only be changed by the user themselves", + "They're not your subordinate": "They're not your subordinate", + "InvoiceIn is already booked": "InvoiceIn is already booked", + "This workCenter is already assigned to this agency": "This workCenter is already assigned to this agency" +} \ No newline at end of file -- 2.40.1 From 0914925a860d6978f848c9315a38456307e1cc3f Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 23 May 2024 13:43:00 +0200 Subject: [PATCH 048/413] refs #6964 feat: hasItemOlder --- modules/item/back/methods/item-shelving/hasItemOlder.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/back/methods/item-shelving/hasItemOlder.js b/modules/item/back/methods/item-shelving/hasItemOlder.js index 02cd14bb8..9bea6fbe9 100644 --- a/modules/item/back/methods/item-shelving/hasItemOlder.js +++ b/modules/item/back/methods/item-shelving/hasItemOlder.js @@ -46,7 +46,7 @@ module.exports = Self => { SELECT COUNT(ish.id) countItemOlder FROM vn.itemShelving ish JOIN ( - SELECT ish.itemFk, created, shelvingFk + SELECT ish.itemFk, created, shelvingFk, pickingOrder FROM vn.itemShelving ish JOIN vn.shelving s ON ish.shelvingFk = s.code LEFT JOIN vn.parking p2 ON p2.id = s.parkingFk -- 2.40.1 From ea4f70f460b4186c4e7d97171a023f116fc5511d Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 23 May 2024 16:35:36 +0200 Subject: [PATCH 049/413] refs #6861 feat: previas a reservas --- .../vn/procedures/collection_getTickets.sql | 52 +++++----- ...temShelvingSale_addBySectorCollection.sql} | 34 ++++--- .../procedures/itemShelvingSale_reserve.sql | 94 ------------------- .../itemShelvingSale_reserveByCollection.sql | 29 ------ .../itemShelvingSale_reserveBySale.sql | 21 ----- 5 files changed, 45 insertions(+), 185 deletions(-) rename db/routines/vn/procedures/{itemShelvingSale_reserveBySectorCollection.sql => itemShelvingSale_addBySectorCollection.sql} (64%) delete mode 100644 db/routines/vn/procedures/itemShelvingSale_reserve.sql delete mode 100644 db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql delete mode 100644 db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql index 3f1239e9b..09624acd2 100644 --- a/db/routines/vn/procedures/collection_getTickets.sql +++ b/db/routines/vn/procedures/collection_getTickets.sql @@ -19,9 +19,9 @@ BEGIN WITH observation AS ( SELECT tob.ticketFk, tob.description - FROM vn.ticketObservation tob - JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk - LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk + FROM ticketObservation tob + JOIN ticketCollection tc ON tc.ticketFk = tob.ticketFk + LEFT JOIN observationType ot ON ot.id = tob.observationTypeFk WHERE ot.`code` = 'itemPicker' AND tc.collectionFk = vParamFk ) @@ -32,17 +32,17 @@ BEGIN w.id salesPersonFk, IFNULL(ob.description,'') observation, cc.rgb - FROM vn.ticket t - LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk - LEFT JOIN vn.collectionColors cc + FROM ticket t + LEFT JOIN ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN collection c2 ON c2.id = tc.collectionFk + LEFT JOIN collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.client c ON c.id = t.clientFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN worker w ON w.id = c.salesPersonFk LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE t.id = vParamFk AND t.shipped >= vDated @@ -54,17 +54,17 @@ BEGIN w.id salesPersonFk, ob.description, IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` - FROM vn.ticket t - JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk - LEFT JOIN vn.collectionColors cc + FROM ticket t + JOIN ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN collection c2 ON c2.id = tc.collectionFk + LEFT JOIN collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.client c ON c.id = t.clientFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN worker w ON w.id = c.salesPersonFk LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE tc.collectionFk = vParamFk UNION ALL @@ -75,14 +75,14 @@ BEGIN c.salesPersonFk, ob.description, NULL `rgb` - FROM vn.sectorCollection sc - JOIN vn.sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id - JOIN vn.saleGroup sg ON sg.id = ss.saleGroupFk - JOIN vn.ticket t ON t.id = sg.ticketFk - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN saleGroup sg ON sg.id = ss.saleGroupFk + JOIN ticket t ON t.id = sg.ticketFk + LEFT JOIN zone z ON z.id = t.zoneFk + LEFT JOIN agencyMode am ON am.id = z.agencyModeFk LEFT JOIN observation ob ON ob.ticketFk = t.id - LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN client c ON c.id = t.clientFk WHERE sc.id = vParamFk AND t.shipped >= vDated; END$$ diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql b/db/routines/vn/procedures/itemShelvingSale_addBySectorCollection.sql similarity index 64% rename from db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql rename to db/routines/vn/procedures/itemShelvingSale_addBySectorCollection.sql index b8387d20c..442abcf5d 100644 --- a/db/routines/vn/procedures/itemShelvingSale_reserveBySectorCollection.sql +++ b/db/routines/vn/procedures/itemShelvingSale_addBySectorCollection.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE - `vn`.`itemShelvingSale_reserveBySectorCollection`(vSectorCollectionFk INT(11)) + `vn`.`itemShelvingSale_addBySectorCollection`(vSectorCollectionFk INT(11)) BEGIN /** * Reserva cantidades con ubicaciones para el contenido de una preparación previa @@ -8,12 +8,10 @@ BEGIN * * @param vSectorCollectionFk Identificador de sectorCollection */ - DECLARE vHasSales BOOL; - - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) - ENGINE = MEMORY - SELECT s.id saleFk, str.workerFk userFK + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + SELECT s.id FROM sectorCollectionSaleGroup sc JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk JOIN sale s ON sg.saleFk = s.id @@ -25,13 +23,19 @@ BEGIN AND str.workerFk = account.myUser_getId() AND iss.id IS NULL; - SELECT COUNT(*)INTO vHasSales - FROM tmp.sale; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - IF vHasSales THEN - CALL itemShelvingSale_reserve(); - ELSE - CALL util.throw ('There are not sales to reserve'); - END IF; + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; END$$ -DELIMITER ; +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_reserve.sql b/db/routines/vn/procedures/itemShelvingSale_reserve.sql deleted file mode 100644 index 803059423..000000000 --- a/db/routines/vn/procedures/itemShelvingSale_reserve.sql +++ /dev/null @@ -1,94 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserve`() -BEGIN -/** - * Reserva cantidades con ubicaciones para un conjunto de sales del mismo - * almacen. - * - * @table tmp.sale(saleFk, userFk) - */ - DECLARE vCalcFk INT; - DECLARE vWarehouseFk INT; - DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW()); - DECLARE vLastPickingOrder INT; - - SELECT t.warehouseFk, MAX(p.pickingOrder) - INTO vWarehouseFk, vLastPickingOrder - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN tmp.sale ts ON ts.saleFk = s.id - LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk - LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk - LEFT JOIN shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN parking p ON p.id = sh.parkingFk - WHERE t.warehouseFk IS NOT NULL; - - IF vWarehouseFk IS NULL THEN - CALL util.throw('Warehouse not set'); - END IF; - - CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); - - SET @outstanding = 0; - SET @oldsaleFk = 0; - - CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity - (INDEX(saleFk)) - ENGINE = MEMORY - SELECT saleFk, userFk, quantityToReserve, itemShelvingFk - FROM( SELECT saleFk, - sub.userFk, - itemShelvingFk , - IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding), - @qtr := LEAST(@outstanding, available) quantityToReserve, - @outStanding := @outStanding - @qtr, - @oldsaleFk := saleFk - FROM( - SELECT ts.saleFk, - ts.userFk, - s.quantity, - ish.id itemShelvingFk, - ish.visible - IFNULL(ishr.reservedQuantity, 0) available - FROM tmp.sale ts - JOIN sale s ON s.id = ts.saleFk - JOIN itemShelving ish ON ish.itemFk = s.itemFk - LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id - LEFT JOIN ( - SELECT itemShelvingFk, SUM(quantity) reservedQuantity - FROM itemShelvingSale - WHERE NOT isPicked - GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector sc ON sc.id = p.sectorFk - JOIN warehouse w ON w.id = sc.warehouseFk - JOIN productionConfig pc - WHERE w.id = vWarehouseFk - AND NOT sc.isHideForPickers - AND iss.id IS NULL - ORDER BY - s.id, - p.pickingOrder >= vLastPickingOrder, - sh.priority DESC, - ish.visible >= s.quantity DESC, - s.quantity MOD ish.grouping = 0 DESC, - ish.grouping DESC, - IF(pc.orderMode = 'Location', p.pickingOrder, ish.created) - )sub - )sub2 - WHERE quantityToReserve > 0; - - INSERT INTO itemShelvingSale( - itemShelvingFk, - saleFk, - quantity, - userFk) - SELECT itemShelvingFk, - saleFk, - quantityToReserve, - IFNULL(userFk, getUser()) - FROM tSalePlacementQuantity spl; - - DROP TEMPORARY TABLE tmp.sale; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql b/db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql deleted file mode 100644 index 9a97130dd..000000000 --- a/db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql +++ /dev/null @@ -1,29 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveByCollection`( - vCollectionFk INT(11) -) -BEGIN -/** - * Reserva cantidades con ubicaciones para el contenido de una colección - * - * @param vCollectionFk Identificador de collection - */ - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) - ENGINE = MEMORY - SELECT s.id saleFk, NULL userFk - FROM ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - LEFT JOIN ( - SELECT DISTINCT saleFk - FROM saleTracking st - JOIN state s ON s.id = st.stateFk - WHERE st.isChecked - AND s.semaphore = 1)st ON st.saleFk = s.id - WHERE tc.collectionFk = vCollectionFk - AND st.saleFk IS NULL - AND NOT s.isPicked; - - CALL itemShelvingSale_reserve(); -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql b/db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql deleted file mode 100644 index fb245062e..000000000 --- a/db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql +++ /dev/null @@ -1,21 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveBySale`( - vSelf INT , - vQuantity INT, - vUserFk INT -) -BEGIN -/** - * Reserva cantida y ubicación para una saleFk - * - * @param vSelf Identificador de la venta - * @param vQuantity Cantidad a reservar - * @param vUserFk Id de usuario que realiza la reserva - */ - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - ENGINE = MEMORY - SELECT vSelf saleFk, vUserFk userFk; - - CALL itemShelvingSale_reserve(); -END$$ -DELIMITER ; -- 2.40.1 From cee8fdd784739d01d463ef0b51c84ec1b4c7386b Mon Sep 17 00:00:00 2001 From: Sergio De la torre Date: Thu, 23 May 2024 16:56:35 +0200 Subject: [PATCH 050/413] refs #6832 fix: ToItem --- modules/item/back/methods/item-barcode/toItem.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/item/back/methods/item-barcode/toItem.js b/modules/item/back/methods/item-barcode/toItem.js index 96e9d5981..d189b77c3 100644 --- a/modules/item/back/methods/item-barcode/toItem.js +++ b/modules/item/back/methods/item-barcode/toItem.js @@ -4,7 +4,7 @@ module.exports = Self => { accessType: 'READ', accepts: [{ arg: 'barcode', - type: 'number', + type: 'string', required: true, description: 'barcode' }], @@ -18,7 +18,7 @@ module.exports = Self => { } }); - Self.toItem = async(barcode, options) => { + Self.toItem = async (barcode, options) => { const myOptions = {}; if (typeof options == 'object') -- 2.40.1 From 0e5a15dd4e1b9fc5ac5738280090663a6cf1f4b1 Mon Sep 17 00:00:00 2001 From: jgallego Date: Fri, 24 May 2024 15:14:20 +0200 Subject: [PATCH 051/413] con addressFk --- db/dump/.dump/data.sql | 4 +-- db/dump/fixtures.before.sql | 19 +++++++++----- .../vn/procedures/expeditionTruck_Add.sql | 9 ------- .../vn/procedures/expeditionTruck_List.sql | 12 --------- .../vn/views/expeditionTruck_Control.sql | 19 -------------- .../views/expeditionTruck_Control_Detail.sql | 18 ------------- .../expeditionTruck_Control_Detail_Pallet.sql | 22 ---------------- .../00-roadmapAddress.sql | 8 ++++++ .../11063-purpleAnthurium/01-roadmapStop.sql | 7 +++++ .../02-roadmapStopGrants.sql | 11 ++++++++ .../route/back/locale/routesMonitor/en.yml | 4 +-- .../route/back/locale/routesMonitor/es.yml | 4 +-- modules/route/back/methods/roadmap/clone.js | 11 +++----- modules/route/back/model-config.json | 3 +++ modules/route/back/models/roadmapAddress.json | 26 +++++++++++++++++++ modules/route/back/models/roadmapStop.json | 8 +++--- 16 files changed, 81 insertions(+), 104 deletions(-) delete mode 100644 db/routines/vn/procedures/expeditionTruck_Add.sql delete mode 100644 db/routines/vn/procedures/expeditionTruck_List.sql delete mode 100644 db/routines/vn/views/expeditionTruck_Control.sql delete mode 100644 db/routines/vn/views/expeditionTruck_Control_Detail.sql delete mode 100644 db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql create mode 100644 db/versions/11063-purpleAnthurium/00-roadmapAddress.sql create mode 100644 db/versions/11063-purpleAnthurium/01-roadmapStop.sql create mode 100644 db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql create mode 100644 modules/route/back/models/roadmapAddress.json diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index f49e3f0f9..b1a69dee9 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -1747,8 +1747,8 @@ INSERT INTO `ACL` VALUES (688,'ClientSms','create','WRITE','ALLOW','ROLE','emplo INSERT INTO `ACL` VALUES (689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'); INSERT INTO `ACL` VALUES (691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'); -INSERT INTO `ACL` VALUES (692,'ExpeditionTruck','*','*','ALLOW','ROLE','production'); -INSERT INTO `ACL` VALUES (693,'ExpeditionTruck','*','*','ALLOW','ROLE','productionBoss'); +INSERT INTO `ACL` VALUES (692,'roadmapStop','*','*','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (693,'roadmapStop','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'); diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 3e6edf07d..ccd6ef1d5 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -2670,13 +2670,20 @@ INSERT INTO `vn`.`zoneAgencyMode`(`id`, `agencyModeFk`, `zoneFk`) (3, 6, 5), (4, 7, 1); +INSERT INTO `vn`.`roadmapAddress` (`addressFk`) + VALUES + (1), + (2), + (3), + (4); + INSERT INTO `vn`.`roadmap` (`id`, `name`, `tractorPlate`, `trailerPlate`, `phone`, `supplierFk`, `etd`, `observations`, `userFk`, `price`, `driverName`) VALUES - (1, 'val-algemesi', 'RE-001', 'PO-001', '111111111', 1, util.VN_NOW(), 'this is test observation', 1, 15, 'Batman'), - (2, 'alg-valencia', 'RE-002', 'PO-002', '111111111', 1, util.VN_NOW(), 'test observation', 1, 20, 'Robin'), - (3, 'alz-algemesi', 'RE-003', 'PO-003', '222222222', 2, DATE_ADD(util.VN_NOW(), INTERVAL 2 DAY), 'observations...', 2, 25, 'Driverman'); + (1, 'val-algemesi', '1234-BCD', '9876-BCD', '111111111', 1, util.VN_NOW(), 'this is test observation', 1, 15, 'Batman'), + (2, 'alg-valencia', '2345-CDF', '8765-BCD', '111111111', 1, util.VN_NOW(), 'test observation', 1, 20, 'Robin'), + (3, 'alz-algemesi', '3456-DFG', '7654-BCD', '222222222', 2, DATE_ADD(util.VN_NOW(), INTERVAL 2 DAY), 'observations...', 2, 25, 'Driverman'); -INSERT INTO `vn`.`expeditionTruck` (`id`, `roadmapFk`, `warehouseFk`, `eta`, `description`, `userFk`) +INSERT INTO `vn`.`roadmapStop` (`id`, `roadmapFk`, `addressFk`, `eta`, `description`, `userFk`) VALUES (1, 1, 1, DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY), 'Best truck in fleet', 1), (2, 1, 2, DATE_ADD(util.VN_NOW(), INTERVAL '1 2' DAY_HOUR), 'Second truck in fleet', 1), @@ -3788,7 +3795,7 @@ INSERT INTO vn.workerTeam(id, team, workerFk) VALUES (8, 1, 19); -INSERT INTO vn.workCenter (id, name, payrollCenterFk, counter, warehouseFk, street, geoFk, deliveryManAdjustment) +INSERT INTO vn.workCenter (id, name, payrollCenterFk, counter, warehouseFk, street, geoFk, deliveryManAdjustment) VALUES(100, 'workCenterOne', 1, NULL, 1, 'gotham', NULL, NULL); -UPDATE vn.locker SET workerFk = 1110 WHERE id = 147; \ No newline at end of file +UPDATE vn.locker SET workerFk = 1110 WHERE id = 147; diff --git a/db/routines/vn/procedures/expeditionTruck_Add.sql b/db/routines/vn/procedures/expeditionTruck_Add.sql deleted file mode 100644 index eabfa452c..000000000 --- a/db/routines/vn/procedures/expeditionTruck_Add.sql +++ /dev/null @@ -1,9 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionTruck_Add`(vHour VARCHAR(5), vDescription VARCHAR(45)) -BEGIN - - INSERT INTO vn.roadmapStop(eta,description) - VALUES(CONCAT(util.VN_CURDATE(), ' ', vHour), vDescription); - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/expeditionTruck_List.sql b/db/routines/vn/procedures/expeditionTruck_List.sql deleted file mode 100644 index c358df5e3..000000000 --- a/db/routines/vn/procedures/expeditionTruck_List.sql +++ /dev/null @@ -1,12 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`expeditionTruck_List`() -BEGIN - - SELECT id truckFk, - eta, - description Destino - FROM roadmapStop - WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) - ORDER BY eta; -END$$ -DELIMITER ; diff --git a/db/routines/vn/views/expeditionTruck_Control.sql b/db/routines/vn/views/expeditionTruck_Control.sql deleted file mode 100644 index 838e1f89e..000000000 --- a/db/routines/vn/views/expeditionTruck_Control.sql +++ /dev/null @@ -1,19 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`expeditionTruck_Control` -AS SELECT `e`.`truckFk` AS `id`, - `e`.`eta` AS `ETD`, - `e`.`description` AS `description`, - COUNT( - DISTINCT IF(`e`.`expeditionFk` IS NULL, `e`.`ticketFk`, NULL) - ) AS `ticketsSinBultos`, - COUNT(DISTINCT `e`.`palletFk`) AS `pallets`, - COUNT(DISTINCT `e`.`routeFk`) AS `routes`, - COUNT(DISTINCT `e`.`scanFk`) AS `scans`, - COUNT(DISTINCT `e`.`expeditionFk`) AS `expeditions`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, - max(`e`.`lastPacked`) AS `lastPacked` -FROM `vn`.`expeditionCommon` `e` -GROUP BY `e`.`truckFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, - `e`.`eta` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail.sql b/db/routines/vn/views/expeditionTruck_Control_Detail.sql deleted file mode 100644 index 96a5b78e6..000000000 --- a/db/routines/vn/views/expeditionTruck_Control_Detail.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`expeditionTruck_Control_Detail` -AS SELECT `e`.`truckFk` AS `id`, - `e`.`eta` AS `eta`, - `e`.`description` AS `destino`, - `e`.`palletFk` AS `pallet`, - COUNT(DISTINCT `e`.`routeFk`) AS `routes`, - COUNT(DISTINCT `e`.`scanFk`) AS `scans`, - COUNT(DISTINCT `e`.`expeditionTruckFk`) AS `destinos`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, - max(`e`.`lastPacked`) AS `lastPacked` -FROM `vn`.`expeditionCommon` `e` -GROUP BY `e`.`truckFk`, - `e`.`palletFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, - `e`.`eta`, - `e`.`truckFk` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql b/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql deleted file mode 100644 index 3f239432d..000000000 --- a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql +++ /dev/null @@ -1,22 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn`.`expeditionTruck_Control_Detail_Pallet` -AS SELECT `e`.`truckFk` AS `id`, - `e`.`eta` AS `eta`, - `e`.`description` AS `destino`, - `e`.`palletFk` AS `pallet`, - `e`.`routeFk` AS `route`, - COUNT(DISTINCT `e`.`scanFk`) AS `scans`, - `rs`.`description` AS `destinos`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, - `e`.`expeditionTruckFk` AS `expeditionTruckFk`, - max(`e`.`lastPacked`) AS `lastPacked` -FROM ( - `vn`.`expeditionCommon` `e` - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`expeditionTruckFk`) - ) -GROUP BY `e`.`truckFk`, - `e`.`palletFk`, - `e`.`routeFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, - `e`.`palletFk` diff --git a/db/versions/11063-purpleAnthurium/00-roadmapAddress.sql b/db/versions/11063-purpleAnthurium/00-roadmapAddress.sql new file mode 100644 index 000000000..6435da1c9 --- /dev/null +++ b/db/versions/11063-purpleAnthurium/00-roadmapAddress.sql @@ -0,0 +1,8 @@ +CREATE TABLE `vn`.`roadmapAddress` ( + addressFk int(11) NULL, + isActive TINYINT DEFAULT 1 NULL, + PRIMARY KEY (addressFk) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Direcciones de los troncales'; + +ALTER TABLE vn.roadmapAddress + ADD CONSTRAINT roadmapAddress_address_FK FOREIGN KEY (addressFk) REFERENCES vn.address(id) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/db/versions/11063-purpleAnthurium/01-roadmapStop.sql b/db/versions/11063-purpleAnthurium/01-roadmapStop.sql new file mode 100644 index 000000000..844abf45f --- /dev/null +++ b/db/versions/11063-purpleAnthurium/01-roadmapStop.sql @@ -0,0 +1,7 @@ +ALTER TABLE vn.roadmapStop DROP FOREIGN KEY expeditionTruck_FK_1; +ALTER TABLE vn.roadmapStop DROP COLUMN warehouseFk; +ALTER TABLE vn.roadmapStop ADD addressFk int(11) NULL; +ALTER TABLE vn.roadmapStop CHANGE addressFk addressFk int(11) DEFAULT NULL NULL AFTER roadmapFk; + +ALTER TABLE vn.roadmapStop + ADD CONSTRAINT roadmapStop_roadmapAddress_FK FOREIGN KEY (addressFk) REFERENCES vn.roadmapAddress(addressFk) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql b/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql new file mode 100644 index 000000000..d2c8354c0 --- /dev/null +++ b/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql @@ -0,0 +1,11 @@ +DELETE FROM salix.ACL + WHERE model in ('expeditionTruck', 'Roadmap', 'roadmapStop', 'roadmapAddress'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) + VALUES + ('roadmapAddress', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), + ('roadmapAddress', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('Roadmap', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), + ('Roadmap', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('RoadmapStop', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), + ('RoadmapStop', '*', 'READ', 'ALLOW', 'ROLE', 'production'); diff --git a/modules/route/back/locale/routesMonitor/en.yml b/modules/route/back/locale/routesMonitor/en.yml index 8908ee636..0542ced54 100644 --- a/modules/route/back/locale/routesMonitor/en.yml +++ b/modules/route/back/locale/routesMonitor/en.yml @@ -13,7 +13,7 @@ columns: m3: m3 priority: priority etd: etd - expeditionTruckFk: truck + roadmapStopFk: truck m3boxes: m3 boxes bufferFk: buffer - isPickingAllowed: is picking allowed \ No newline at end of file + isPickingAllowed: is picking allowed diff --git a/modules/route/back/locale/routesMonitor/es.yml b/modules/route/back/locale/routesMonitor/es.yml index 9ded8983d..1ea0532c6 100644 --- a/modules/route/back/locale/routesMonitor/es.yml +++ b/modules/route/back/locale/routesMonitor/es.yml @@ -13,7 +13,7 @@ columns: m3: m3 priority: prioridad etd: etd - expeditionTruckFk: camión + roadmapStopFk: camión m3boxes: m3 cajas bufferFk: buffer - isPickingAllowed: está permitido recoger \ No newline at end of file + isPickingAllowed: está permitido recoger diff --git a/modules/route/back/methods/roadmap/clone.js b/modules/route/back/methods/roadmap/clone.js index b74cf803c..5f1ab9229 100644 --- a/modules/route/back/methods/roadmap/clone.js +++ b/modules/route/back/methods/roadmap/clone.js @@ -37,17 +37,12 @@ module.exports = Self => { fields: [ 'id', 'name', - 'tractorPlate', - 'trailerPlate', - 'phone', 'supplierFk', - 'etd', - 'observations', - 'price'], + 'etd'], include: [{ - relation: 'expeditionTruck', + relation: 'roadmapStop', scope: { - fields: ['roadmapFk', 'warehouseFk', 'eta', 'description'] + fields: ['roadmapFk', 'addressFk', 'eta', 'description'] } }] diff --git a/modules/route/back/model-config.json b/modules/route/back/model-config.json index 09cda6b2d..ccae87bd9 100644 --- a/modules/route/back/model-config.json +++ b/modules/route/back/model-config.json @@ -8,6 +8,9 @@ "DeliveryPoint": { "dataSource": "vn" }, + "RoadmapAddress": { + "dataSource": "vn" + }, "RoadmapStop": { "dataSource": "vn" }, diff --git a/modules/route/back/models/roadmapAddress.json b/modules/route/back/models/roadmapAddress.json new file mode 100644 index 000000000..0241ce0d8 --- /dev/null +++ b/modules/route/back/models/roadmapAddress.json @@ -0,0 +1,26 @@ +{ + "name": "RoadmapAddress", + "base": "VnModel", + "options": { + "mysql": { + "table": "roadmapAddress" + } + }, + "properties": { + "addressFk": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "isActive": { + "type": "number" + } + }, + "relations": { + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" + } + } +} diff --git a/modules/route/back/models/roadmapStop.json b/modules/route/back/models/roadmapStop.json index 51aa3a6db..527bbae98 100644 --- a/modules/route/back/models/roadmapStop.json +++ b/modules/route/back/models/roadmapStop.json @@ -15,7 +15,7 @@ "roadmapFk": { "type": "number" }, - "warehouseFk": { + "addressFk": { "type": "number" }, "eta": { @@ -34,10 +34,10 @@ "model": "Roadmap", "foreignKey": "roadmapFk" }, - "warehouse": { + "address": { "type": "belongsTo", - "model": "Warehouse", - "foreignKey": "warehouseFk" + "model": "RoadmapAddress", + "foreignKey": "addressFk" } } } -- 2.40.1 From 723327918b4c479c095e0702b95fb072c3887636 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 24 May 2024 15:55:23 +0200 Subject: [PATCH 052/413] refs #7406 worker formation --- db/dump/fixtures.before.sql | 15 ++++- .../worker/back/models/trainingCenter.json | 21 ++++++ .../worker/back/models/trainingCourse.json | 67 +++++++++++++++++++ .../back/models/trainingCourseType.json | 39 +++++++++++ 4 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 modules/worker/back/models/trainingCenter.json create mode 100644 modules/worker/back/models/trainingCourse.json create mode 100644 modules/worker/back/models/trainingCourseType.json diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index b8094471a..7765edc9f 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3788,14 +3788,23 @@ INSERT INTO vn.workerTeam(id, team, workerFk) VALUES (8, 1, 19); -INSERT INTO vn.workCenter (id, name, payrollCenterFk, counter, warehouseFk, street, geoFk, deliveryManAdjustment) +INSERT INTO vn.workCenter (id, name, payrollCenterFk, counter, warehouseFk, street, geoFk, deliveryManAdjustment) VALUES(100, 'workCenterOne', 1, NULL, 1, 'gotham', NULL, NULL); -UPDATE vn.locker SET workerFk = 1110 WHERE id = 147; +UPDATE vn.locker SET workerFk = 1110 WHERE id = 147; INSERT INTO `vn`.`ledgerCompany` SET fiscalYear = YEAR(util.VN_CURDATE()), bookEntry = 2; -INSERT INTO `vn`.`ledgerConfig` SET +INSERT INTO `vn`.`ledgerConfig` SET maxTolerance = 0.01; + + +INSERT INTO vn.trainingCourse (workerFk,trainingCourseTypeFk,centerFk,started,ended,hasDiscount,hasDiploma) + VALUES (9,2,1,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',0,1); +INSERT INTO vn.trainingCourse (workerFk,trainingCourseTypeFk,centerFk,started,ended,hasDiscount,hasDiploma) + VALUES (9,1,2,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',1,0); +INSERT INTO vn.trainingCourse (workerFk,trainingCourseTypeFk,centerFk,started,ended,hasDiscount,hasDiploma) + VALUES (9,2,2,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',1,1); + diff --git a/modules/worker/back/models/trainingCenter.json b/modules/worker/back/models/trainingCenter.json new file mode 100644 index 000000000..8c5e47873 --- /dev/null +++ b/modules/worker/back/models/trainingCenter.json @@ -0,0 +1,21 @@ +{ + "name": "TrainingCenter", + "base": "VnModel", + "options": { + "mysql": { + "table": "trainingCenter" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "string", + "required": true + } + + } +} diff --git a/modules/worker/back/models/trainingCourse.json b/modules/worker/back/models/trainingCourse.json new file mode 100644 index 000000000..7a44ad419 --- /dev/null +++ b/modules/worker/back/models/trainingCourse.json @@ -0,0 +1,67 @@ +{ + "name": "TrainingCourse", + "description": "List of workers who have completed training", + "base": "VnModel", + "options": { + "mysql": { + "table": "trainingCourse" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "workerFk": { + "type": "number", + "required": true + }, + "trainingCourseTypeFk": { + "type": "number", + "required": true + }, + "centerFk": { + "type" : "number" + }, + "started": { + "type" : "date" + }, + "ended": { + "type" : "date" + }, + "invoice": { + "type" : "string" + }, + "amount": { + "type" : "number" + }, + "remark": { + "type" : "boolean" + }, + "hasDiscount": { + "type" : "boolean" + }, + "hasDiploma": { + "type" : "boolean" + } + + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "trainingCourseType": { + "type": "belongsTo", + "model": "trainingCourseType", + "foreignKey": "trainingCourseTypeFk" + }, + "centerFk": { + "type": "belongsTo", + "model": "Center", + "foreignKey": "centerFk" + } + } +} diff --git a/modules/worker/back/models/trainingCourseType.json b/modules/worker/back/models/trainingCourseType.json new file mode 100644 index 000000000..1dc708f2f --- /dev/null +++ b/modules/worker/back/models/trainingCourseType.json @@ -0,0 +1,39 @@ +{ + "name": "trainingCourseType", + "description": "List of trainings", + "base": "VnModel", + "options": { + "mysql": { + "table": "trainingCourseType" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "string", + "required": true + } + + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "trainingCourseType": { + "type": "belongsTo", + "model": "trainingCourseType", + "foreignKey": "trainingCourseTypeFk" + }, + "centerFk": { + "type": "belongsTo", + "model": "Center", + "foreignKey": "centerFk" + } + } +} -- 2.40.1 From d770cd8d48a8785a20b70bab93bca0a98d2d841c Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 27 May 2024 07:33:33 +0200 Subject: [PATCH 053/413] refs #6861 feat: getLock --- .../vn/procedures/collection_getAssigned.sql | 37 ++++++++++++++++--- 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/collection_getAssigned.sql b/db/routines/vn/procedures/collection_getAssigned.sql index dead563ac..63805e701 100644 --- a/db/routines/vn/procedures/collection_getAssigned.sql +++ b/db/routines/vn/procedures/collection_getAssigned.sql @@ -10,13 +10,27 @@ proc:BEGIN * @param vCollectionFk Id de colección */ DECLARE vHasTooMuchCollections BOOL; - DECLARE vLockTime INT DEFAULT 15; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + END IF; + + RESIGNAL; + END; -- Si hay colecciones sin terminar, sale del proceso CALL collection_get(vUserFk); - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName FROM tCollection JOIN productionConfig pc ; @@ -27,8 +41,19 @@ proc:BEGIN LEAVE proc; END IF; - IF NOT GET_LOCK('collection_getAssigned', vLockTime) THEN - LEAVE proc; + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); END IF; -- Se eliminan las colecciones sin asignar que estan obsoletas @@ -72,6 +97,6 @@ proc:BEGIN CALL itemShelvingSale_addByCollection(vCollectionFk); - DO RELEASE_LOCK('collection_getAssigned'); + DO RELEASE_LOCK(vLockName); END$$ DELIMITER ; \ No newline at end of file -- 2.40.1 From 2cd7133a8cd25098228dfeda73a7b6e1e8281e08 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 27 May 2024 08:15:57 +0200 Subject: [PATCH 054/413] refs #6861 feat: skipTest --- back/methods/collection/spec/assignCollection.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/collection/spec/assignCollection.spec.js b/back/methods/collection/spec/assignCollection.spec.js index 340bd6a93..e8f3882a3 100644 --- a/back/methods/collection/spec/assignCollection.spec.js +++ b/back/methods/collection/spec/assignCollection.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -fdescribe('ticket assignCollection()', () => { +describe('ticket assignCollection()', () => { let ctx; let options; let tx; -- 2.40.1 From eb503238d737858f100dc53f06af1d28a497fddb Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 27 May 2024 09:07:23 +0200 Subject: [PATCH 055/413] feat refs #7296 routesMonitor.expeditionTruckFk to routesMonitor.roadmapStopFk --- db/dump/fixtures.after.sql | 2 +- db/routines/dipole/procedures/expedition_add.sql | 2 +- db/routines/srt/functions/expedition_getDayMinute.sql | 2 +- db/routines/srt/views/bufferDayMinute.sql | 2 +- db/routines/srt/views/bufferStock.sql | 2 +- db/routines/srt/views/upperStickers.sql | 2 +- db/routines/vn/procedures/conveyorExpedition_Add.sql | 2 +- db/routines/vn/procedures/expedition_StateGet.sql | 2 +- db/routines/vn/procedures/expedition_getState.sql | 2 +- db/routines/vn/procedures/reportLabelCollection_get.sql | 2 +- db/routines/vn/procedures/routeMonitor_calculate.sql | 2 +- db/routines/vn/views/expeditionCommon.sql | 4 ++-- db/routines/vn/views/expeditionPallet_Print.sql | 4 ++-- db/routines/vn/views/expeditionRoute_Monitor.sql | 2 +- db/routines/vn/views/expeditionSticker.sql | 2 +- db/routines/vn/views/expeditionTicket_NoBoxes.sql | 2 +- db/routines/vn/views/expeditionTruck_Control.sql | 4 ++-- db/routines/vn/views/expeditionTruck_Control_Detail.sql | 6 +++--- .../vn/views/expeditionTruck_Control_Detail_Pallet.sql | 6 +++--- print/templates/reports/collection-label/sql/labelsData.sql | 2 +- .../reports/expedition-pallet-label/sql/labelData.sql | 4 ++-- 21 files changed, 29 insertions(+), 29 deletions(-) diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index fd940d8a6..562ea02d8 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -129,7 +129,7 @@ INSERT INTO vn.itemShelving (id,itemFk,visible,shelvingFk,`grouping`,packing,pac INSERT INTO vn.beach (code,warehouseFk) VALUES ('TEST',1); -INSERT INTO vn.routesMonitor (routeFk,name,beachFk,m3,expeditionTruckFk) VALUES +INSERT INTO vn.routesMonitor (routeFk,name,beachFk,m3,roadmapStopFk) VALUES (1,'TEST','TEST',1.0,1); /* #5483 INSERT INTO vn.ticket (clientFk, warehouseFk, shipped, nickname, refFk, addressFk, workerFk, observations, isSigned, isLabeled, isPrinted, packages, location, `hour`, created, isBlocked, solution, routeFk, priority, hasPriority, companyFk, agencyModeFk, landed, isBoxed, isDeleted, zoneFk, zonePrice, zoneBonus, totalWithVat, totalWithoutVat, weight) diff --git a/db/routines/dipole/procedures/expedition_add.sql b/db/routines/dipole/procedures/expedition_add.sql index e224cd2d2..70bc7930e 100644 --- a/db/routines/dipole/procedures/expedition_add.sql +++ b/db/routines/dipole/procedures/expedition_add.sql @@ -46,7 +46,7 @@ BEGIN JOIN vn.address a ON a.id = t.addressFk JOIN vn.province p ON p.id = a.provinceFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk LEFT JOIN vn.beach b ON b.code = rm.beachFk LEFT JOIN vn.`zone`z ON z.id = t.zoneFk JOIN vn.agencyMode am ON t.agencyModeFk = am.id diff --git a/db/routines/srt/functions/expedition_getDayMinute.sql b/db/routines/srt/functions/expedition_getDayMinute.sql index 9331f77e5..01ff534f5 100644 --- a/db/routines/srt/functions/expedition_getDayMinute.sql +++ b/db/routines/srt/functions/expedition_getDayMinute.sql @@ -22,7 +22,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON t.routeFk = rm.routeFk - LEFT JOIN vn.roadmapStop rs ON rm.expeditionTruckFk = rs.id + LEFT JOIN vn.roadmapStop rs ON rm.roadmapStopFk = rs.id WHERE e.id = vExpeditionFk; RETURN vDayMinute; diff --git a/db/routines/srt/views/bufferDayMinute.sql b/db/routines/srt/views/bufferDayMinute.sql index 41db2bcf7..d2108e513 100644 --- a/db/routines/srt/views/bufferDayMinute.sql +++ b/db/routines/srt/views/bufferDayMinute.sql @@ -34,7 +34,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`expeditionTruckFk` = `rs`.`id`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`roadmapStopFk` = `rs`.`id`) ) LEFT JOIN `vn`.`zone` `z` ON(`z`.`id` = `t`.`zoneFk`) ) diff --git a/db/routines/srt/views/bufferStock.sql b/db/routines/srt/views/bufferStock.sql index 7494cf0a9..ca04d3c01 100644 --- a/db/routines/srt/views/bufferStock.sql +++ b/db/routines/srt/views/bufferStock.sql @@ -45,7 +45,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`expeditionTruckFk` = `rs`.`id`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`roadmapStopFk` = `rs`.`id`) ) JOIN `srt`.`config` `c` ) diff --git a/db/routines/srt/views/upperStickers.sql b/db/routines/srt/views/upperStickers.sql index a230408d9..1cd72c12b 100644 --- a/db/routines/srt/views/upperStickers.sql +++ b/db/routines/srt/views/upperStickers.sql @@ -32,7 +32,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`t`.`routeFk` = `rm`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`expeditionTruckFk` = `rs`.`id`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rm`.`roadmapStopFk` = `rs`.`id`) ) JOIN `dipole`.`expedition_PrintOut` `epo` ON(`epo`.`expeditionFk` = `e`.`id`) ) diff --git a/db/routines/vn/procedures/conveyorExpedition_Add.sql b/db/routines/vn/procedures/conveyorExpedition_Add.sql index daaf33f2f..94cbc88e2 100644 --- a/db/routines/vn/procedures/conveyorExpedition_Add.sql +++ b/db/routines/vn/procedures/conveyorExpedition_Add.sql @@ -34,7 +34,7 @@ BEGIN LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.agency a ON a.id = am.agencyFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded diff --git a/db/routines/vn/procedures/expedition_StateGet.sql b/db/routines/vn/procedures/expedition_StateGet.sql index e58ec3afd..c709841eb 100644 --- a/db/routines/vn/procedures/expedition_StateGet.sql +++ b/db/routines/vn/procedures/expedition_StateGet.sql @@ -67,7 +67,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE e.id = vExpeditionFk; END$$ diff --git a/db/routines/vn/procedures/expedition_getState.sql b/db/routines/vn/procedures/expedition_getState.sql index f3f94a889..61d65f571 100644 --- a/db/routines/vn/procedures/expedition_getState.sql +++ b/db/routines/vn/procedures/expedition_getState.sql @@ -50,7 +50,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE e.id = vExpeditionFk; END$$ diff --git a/db/routines/vn/procedures/reportLabelCollection_get.sql b/db/routines/vn/procedures/reportLabelCollection_get.sql index e7f8f2bc3..f3bcbfa28 100644 --- a/db/routines/vn/procedures/reportLabelCollection_get.sql +++ b/db/routines/vn/procedures/reportLabelCollection_get.sql @@ -47,7 +47,7 @@ BEGIN LEFT JOIN ticketTrolley tt ON tt.ticket = t.id LEFT JOIN zone zo ON t.zoneFk = zo.id LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam) GROUP BY t.id ORDER BY cc.code; diff --git a/db/routines/vn/procedures/routeMonitor_calculate.sql b/db/routines/vn/procedures/routeMonitor_calculate.sql index 04a31a161..463c176ff 100644 --- a/db/routines/vn/procedures/routeMonitor_calculate.sql +++ b/db/routines/vn/procedures/routeMonitor_calculate.sql @@ -106,7 +106,7 @@ BEGIN SET rm.m3boxes = sub.m3boxes; UPDATE routesMonitor rm - JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk SET rm.etd = rs.eta; DROP TEMPORARY TABLE tmp.routesMonitor; diff --git a/db/routines/vn/views/expeditionCommon.sql b/db/routines/vn/views/expeditionCommon.sql index d1ce80880..46765e57c 100644 --- a/db/routines/vn/views/expeditionCommon.sql +++ b/db/routines/vn/views/expeditionCommon.sql @@ -8,7 +8,7 @@ AS SELECT `rs`.`id` AS `truckFk`, `t`.`routeFk` AS `routeFk`, `es`.`id` AS `scanFk`, `e`.`id` AS `expeditionFk`, - `r`.`expeditionTruckFk` AS `expeditionTruckFk`, + `r`.`roadmapStopFk` AS `expeditionTruckFk`, `t`.`warehouseFk` AS `warehouseFk`, `e`.`created` AS `lastPacked`, `t`.`id` AS `ticketFk` @@ -18,7 +18,7 @@ FROM ( ( ( `vn`.`roadmapStop` `rs` - LEFT JOIN `vn`.`routesMonitor` `r` ON(`rs`.`id` = `r`.`expeditionTruckFk`) + LEFT JOIN `vn`.`routesMonitor` `r` ON(`rs`.`id` = `r`.`roadmapStopFk`) ) LEFT JOIN `vn`.`ticket` `t` ON(`r`.`routeFk` = `t`.`routeFk`) ) diff --git a/db/routines/vn/views/expeditionPallet_Print.sql b/db/routines/vn/views/expeditionPallet_Print.sql index c0b8208c3..aab725ebe 100644 --- a/db/routines/vn/views/expeditionPallet_Print.sql +++ b/db/routines/vn/views/expeditionPallet_Print.sql @@ -6,7 +6,7 @@ AS SELECT `rs2`.`description` AS `truck`, `r`.`description` AS `zone`, COUNT(`es`.`id`) AS `eti`, `ep`.`id` AS `palletFk`, - `rs`.`id` <=> `rm`.`expeditionTruckFk` AS `isMatch`, + `rs`.`id` <=> `rm`.`roadmapStopFk` AS `isMatch`, `t`.`warehouseFk` AS `warehouseFk`, IF( `r`.`created` > `util`.`VN_CURDATE`() + INTERVAL 1 DAY, @@ -33,7 +33,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `r`.`id`) ) - LEFT JOIN `vn`.`roadmapStop` `rs2` ON(`rs2`.`id` = `rm`.`expeditionTruckFk`) + LEFT JOIN `vn`.`roadmapStop` `rs2` ON(`rs2`.`id` = `rm`.`roadmapStopFk`) ) GROUP BY `ep`.`id`, `t`.`routeFk` diff --git a/db/routines/vn/views/expeditionRoute_Monitor.sql b/db/routines/vn/views/expeditionRoute_Monitor.sql index cc1f16894..7eef40425 100644 --- a/db/routines/vn/views/expeditionRoute_Monitor.sql +++ b/db/routines/vn/views/expeditionRoute_Monitor.sql @@ -15,7 +15,7 @@ FROM ( `vn`.`route` `r` LEFT JOIN `vn`.`routesMonitor` `rm` ON(`r`.`id` = `rm`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`expeditionTruckFk`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`roadmapStopFk`) ) JOIN `vn`.`ticket` `t` ON(`t`.`routeFk` = `r`.`id`) ) diff --git a/db/routines/vn/views/expeditionSticker.sql b/db/routines/vn/views/expeditionSticker.sql index 05fbc42a1..ef0743527 100644 --- a/db/routines/vn/views/expeditionSticker.sql +++ b/db/routines/vn/views/expeditionSticker.sql @@ -45,7 +45,7 @@ FROM ( ) LEFT JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `t`.`routeFk`) ) - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`expeditionTruckFk`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`roadmapStopFk`) ) LEFT JOIN `vn`.`beach` `b` ON(`b`.`code` = `rm`.`beachFk`) ) diff --git a/db/routines/vn/views/expeditionTicket_NoBoxes.sql b/db/routines/vn/views/expeditionTicket_NoBoxes.sql index 8acbe17fe..75218c7a9 100644 --- a/db/routines/vn/views/expeditionTicket_NoBoxes.sql +++ b/db/routines/vn/views/expeditionTicket_NoBoxes.sql @@ -13,7 +13,7 @@ FROM ( ) JOIN `vn`.`routesMonitor` `rm` ON(`rm`.`routeFk` = `t`.`routeFk`) ) - JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`expeditionTruckFk`) + JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `rm`.`roadmapStopFk`) ) WHERE `e`.`id` IS NULL AND `rs`.`eta` > `util`.`VN_CURDATE`() diff --git a/db/routines/vn/views/expeditionTruck_Control.sql b/db/routines/vn/views/expeditionTruck_Control.sql index 838e1f89e..818ae3ae6 100644 --- a/db/routines/vn/views/expeditionTruck_Control.sql +++ b/db/routines/vn/views/expeditionTruck_Control.sql @@ -11,9 +11,9 @@ AS SELECT `e`.`truckFk` AS `id`, COUNT(DISTINCT `e`.`routeFk`) AS `routes`, COUNT(DISTINCT `e`.`scanFk`) AS `scans`, COUNT(DISTINCT `e`.`expeditionFk`) AS `expeditions`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, + sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`, max(`e`.`lastPacked`) AS `lastPacked` FROM `vn`.`expeditionCommon` `e` GROUP BY `e`.`truckFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, +ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC, `e`.`eta` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail.sql b/db/routines/vn/views/expeditionTruck_Control_Detail.sql index 96a5b78e6..51970544b 100644 --- a/db/routines/vn/views/expeditionTruck_Control_Detail.sql +++ b/db/routines/vn/views/expeditionTruck_Control_Detail.sql @@ -7,12 +7,12 @@ AS SELECT `e`.`truckFk` AS `id`, `e`.`palletFk` AS `pallet`, COUNT(DISTINCT `e`.`routeFk`) AS `routes`, COUNT(DISTINCT `e`.`scanFk`) AS `scans`, - COUNT(DISTINCT `e`.`expeditionTruckFk`) AS `destinos`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, + COUNT(DISTINCT `e`.`roadmapStopFk`) AS `destinos`, + sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`, max(`e`.`lastPacked`) AS `lastPacked` FROM `vn`.`expeditionCommon` `e` GROUP BY `e`.`truckFk`, `e`.`palletFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, +ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC, `e`.`eta`, `e`.`truckFk` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql b/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql index 3f239432d..7e24d6b01 100644 --- a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql +++ b/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql @@ -8,15 +8,15 @@ AS SELECT `e`.`truckFk` AS `id`, `e`.`routeFk` AS `route`, COUNT(DISTINCT `e`.`scanFk`) AS `scans`, `rs`.`description` AS `destinos`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, + sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`, `e`.`expeditionTruckFk` AS `expeditionTruckFk`, max(`e`.`lastPacked`) AS `lastPacked` FROM ( `vn`.`expeditionCommon` `e` - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`expeditionTruckFk`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`roadmapStopFk`) ) GROUP BY `e`.`truckFk`, `e`.`palletFk`, `e`.`routeFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, +ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC, `e`.`palletFk` diff --git a/print/templates/reports/collection-label/sql/labelsData.sql b/print/templates/reports/collection-label/sql/labelsData.sql index 2ffa6d8db..c96817b9c 100644 --- a/print/templates/reports/collection-label/sql/labelsData.sql +++ b/print/templates/reports/collection-label/sql/labelsData.sql @@ -35,7 +35,7 @@ SELECT c.itemPackingTypeFk code, LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id LEFT JOIN vn.`zone` zo ON t.zoneFk = zo.id LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id JOIN vn.productionConfig pc WHERE t.id IN (?) diff --git a/print/templates/reports/expedition-pallet-label/sql/labelData.sql b/print/templates/reports/expedition-pallet-label/sql/labelData.sql index 385614305..49a4031ae 100644 --- a/print/templates/reports/expedition-pallet-label/sql/labelData.sql +++ b/print/templates/reports/expedition-pallet-label/sql/labelData.sql @@ -5,7 +5,7 @@ SELECT ep.id palletFk, COUNT(es.id) labels, t.warehouseFk warehouseFk, dayname(r.created) `dayName`, - rs.id <=> rm.expeditionTruckFk isMatch + rs.id <=> rm.roadmapStopFk isMatch FROM vn.roadmapStop rs JOIN vn.expeditionPallet ep ON ep.truckFk = rs.id JOIN vn.expeditionScan es ON es.palletFk = ep.id @@ -13,7 +13,7 @@ SELECT ep.id palletFk, JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.roadmapStop rs2 ON rs2.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs2 ON rs2.id = rm.roadmapStopFk WHERE ep.id = ? GROUP BY ep.id, t.routeFk ORDER BY t.routeFk -- 2.40.1 From aaea0c95f7c71734a070c1028fbc8b099a3fd96c Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 27 May 2024 09:41:28 +0200 Subject: [PATCH 056/413] feat: refs #7296 roadmapStopFk --- db/routines/vn/views/expeditionTruck_Control.sql | 4 ++-- db/routines/vn/views/expeditionTruck_Control_Detail.sql | 6 +++--- .../vn/views/expeditionTruck_Control_Detail_Pallet.sql | 6 +++--- db/versions/11070-turquoiseCordyline/00-firstScript.sql | 1 + 4 files changed, 9 insertions(+), 8 deletions(-) create mode 100644 db/versions/11070-turquoiseCordyline/00-firstScript.sql diff --git a/db/routines/vn/views/expeditionTruck_Control.sql b/db/routines/vn/views/expeditionTruck_Control.sql index 818ae3ae6..838e1f89e 100644 --- a/db/routines/vn/views/expeditionTruck_Control.sql +++ b/db/routines/vn/views/expeditionTruck_Control.sql @@ -11,9 +11,9 @@ AS SELECT `e`.`truckFk` AS `id`, COUNT(DISTINCT `e`.`routeFk`) AS `routes`, COUNT(DISTINCT `e`.`scanFk`) AS `scans`, COUNT(DISTINCT `e`.`expeditionFk`) AS `expeditions`, - sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`, + sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, max(`e`.`lastPacked`) AS `lastPacked` FROM `vn`.`expeditionCommon` `e` GROUP BY `e`.`truckFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC, +ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, `e`.`eta` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail.sql b/db/routines/vn/views/expeditionTruck_Control_Detail.sql index 51970544b..96a5b78e6 100644 --- a/db/routines/vn/views/expeditionTruck_Control_Detail.sql +++ b/db/routines/vn/views/expeditionTruck_Control_Detail.sql @@ -7,12 +7,12 @@ AS SELECT `e`.`truckFk` AS `id`, `e`.`palletFk` AS `pallet`, COUNT(DISTINCT `e`.`routeFk`) AS `routes`, COUNT(DISTINCT `e`.`scanFk`) AS `scans`, - COUNT(DISTINCT `e`.`roadmapStopFk`) AS `destinos`, - sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`, + COUNT(DISTINCT `e`.`expeditionTruckFk`) AS `destinos`, + sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, max(`e`.`lastPacked`) AS `lastPacked` FROM `vn`.`expeditionCommon` `e` GROUP BY `e`.`truckFk`, `e`.`palletFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC, +ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, `e`.`eta`, `e`.`truckFk` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql b/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql index 7e24d6b01..3f239432d 100644 --- a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql +++ b/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql @@ -8,15 +8,15 @@ AS SELECT `e`.`truckFk` AS `id`, `e`.`routeFk` AS `route`, COUNT(DISTINCT `e`.`scanFk`) AS `scans`, `rs`.`description` AS `destinos`, - sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`, + sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, `e`.`expeditionTruckFk` AS `expeditionTruckFk`, max(`e`.`lastPacked`) AS `lastPacked` FROM ( `vn`.`expeditionCommon` `e` - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`roadmapStopFk`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`expeditionTruckFk`) ) GROUP BY `e`.`truckFk`, `e`.`palletFk`, `e`.`routeFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC, +ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, `e`.`palletFk` diff --git a/db/versions/11070-turquoiseCordyline/00-firstScript.sql b/db/versions/11070-turquoiseCordyline/00-firstScript.sql new file mode 100644 index 000000000..494080033 --- /dev/null +++ b/db/versions/11070-turquoiseCordyline/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.routesMonitor CHANGE expeditionTruckFk roadmapStopFk int(11) DEFAULT NULL NULL; -- 2.40.1 From 74b71079f26f0ceda927500e5ae5fa84e3cd86ba Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 27 May 2024 11:33:04 +0200 Subject: [PATCH 057/413] refs #6861 feat: obsrevation --- back/methods/collection/getSales.js | 2 +- .../collection/spec/getTickets.spec.js | 4 +- .../vn/procedures/collection_getTickets.sql | 54 +++++++++---------- .../triggers/itemShelvingSale_afterInsert.sql | 12 +++++ db/versions/10852-pinkOak/00-firstScript.sql | 4 +- 5 files changed, 45 insertions(+), 31 deletions(-) create mode 100644 db/routines/vn/triggers/itemShelvingSale_afterInsert.sql diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index 1ea5dcc3c..8f5bfaeef 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -60,7 +60,7 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); for (let ticket of tickets) { - let observations = ticket.observation.split(' '); + let observations = ticket.observaciones.split(' '); for (let observation of observations) { const salesPerson = ticket.salesPersonFk; diff --git a/back/methods/collection/spec/getTickets.spec.js b/back/methods/collection/spec/getTickets.spec.js index e6b9e6a17..969800839 100644 --- a/back/methods/collection/spec/getTickets.spec.js +++ b/back/methods/collection/spec/getTickets.spec.js @@ -26,8 +26,8 @@ describe('collection getTickets()', () => { expect(collectionTickets.tickets[1].ticketFk).toEqual(2); expect(collectionTickets.tickets[2].ticketFk).toEqual(23); expect(collectionTickets.tickets[0].sales[0].ticketFk).toEqual(1); - expect(collectionTickets.tickets[0].sales[1].ticketFk).toEqual(1); - expect(collectionTickets.tickets[0].sales[2].ticketFk).toEqual(1); + expect(collectionTickets.tickets[1].sales.length).toEqual(0); + expect(collectionTickets.tickets[2].sales.length).toEqual(0); expect(collectionTickets.tickets[0].sales[0].Barcodes.length).toBeTruthy(); await tx.rollback(); diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql index 09624acd2..8be8c8654 100644 --- a/db/routines/vn/procedures/collection_getTickets.sql +++ b/db/routines/vn/procedures/collection_getTickets.sql @@ -19,9 +19,9 @@ BEGIN WITH observation AS ( SELECT tob.ticketFk, tob.description - FROM ticketObservation tob - JOIN ticketCollection tc ON tc.ticketFk = tob.ticketFk - LEFT JOIN observationType ot ON ot.id = tob.observationTypeFk + FROM vn.ticketObservation tob + JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk + LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk WHERE ot.`code` = 'itemPicker' AND tc.collectionFk = vParamFk ) @@ -30,19 +30,19 @@ BEGIN am.name agencyName, t.warehouseFk, w.id salesPersonFk, - IFNULL(ob.description,'') observation, + IFNULL(ob.description,'') observaciones, cc.rgb - FROM ticket t - LEFT JOIN ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN collection c2 ON c2.id = tc.collectionFk - LEFT JOIN collectionColors cc + FROM vn.ticket t + LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk + LEFT JOIN vn.collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk - LEFT JOIN zone z ON z.id = t.zoneFk - LEFT JOIN agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN client c ON c.id = t.clientFk - LEFT JOIN worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE t.id = vParamFk AND t.shipped >= vDated @@ -54,17 +54,17 @@ BEGIN w.id salesPersonFk, ob.description, IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` - FROM ticket t - JOIN ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN collection c2 ON c2.id = tc.collectionFk - LEFT JOIN collectionColors cc + FROM vn.ticket t + JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk + LEFT JOIN vn.collectionColors cc ON cc.wagon = tc.wagon AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk - LEFT JOIN zone z ON z.id = t.zoneFk - LEFT JOIN agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN client c ON c.id = t.clientFk - LEFT JOIN worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE tc.collectionFk = vParamFk UNION ALL @@ -75,14 +75,14 @@ BEGIN c.salesPersonFk, ob.description, NULL `rgb` - FROM sectorCollection sc - JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id - JOIN saleGroup sg ON sg.id = ss.saleGroupFk - JOIN ticket t ON t.id = sg.ticketFk - LEFT JOIN zone z ON z.id = t.zoneFk - LEFT JOIN agencyMode am ON am.id = z.agencyModeFk + FROM vn.sectorCollection sc + JOIN vn.sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN vn.saleGroup sg ON sg.id = ss.saleGroupFk + JOIN vn.ticket t ON t.id = sg.ticketFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN observation ob ON ob.ticketFk = t.id - LEFT JOIN client c ON c.id = t.clientFk + LEFT JOIN vn.client c ON c.id = t.clientFk WHERE sc.id = vParamFk AND t.shipped >= vDated; END$$ diff --git a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql new file mode 100644 index 000000000..71ede88f7 --- /dev/null +++ b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterInsert` + AFTER INSERT ON `itemShelving` + FOR EACH ROW +BEGIN + + UPDATE sale s + JOIN operator o ON o.workerFk = account.myUser_getId() + SET isPicked = IF(o.isOnReservationMode, isPicked, TRUE) + WHERE id = NEW.saleFk; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/versions/10852-pinkOak/00-firstScript.sql b/db/versions/10852-pinkOak/00-firstScript.sql index 369e32e92..7739976e6 100644 --- a/db/versions/10852-pinkOak/00-firstScript.sql +++ b/db/versions/10852-pinkOak/00-firstScript.sql @@ -27,4 +27,6 @@ CREATE TABLE vn.itemShelvingSaleReserv ( INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) VALUES - ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file + ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'); + +ALTER TABLE vn.operator ADD IF NOT EXISTS isOnReservationMode TINYINT(1) NOT NULL DEFAULT FALSE; \ No newline at end of file -- 2.40.1 From 0b648d09af48ca8595f72187d531a01a087ea5aa Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 27 May 2024 11:45:22 +0200 Subject: [PATCH 058/413] feat: refs #7296 roadmapStopFk --- db/routines/vn/procedures/expeditionPallet_build.sql | 6 +++--- db/routines/vn/views/expeditionCommon.sql | 2 +- db/routines/vn/views/expeditionTruck_Control.sql | 4 ++-- .../vn/views/expeditionTruck_Control_Detail.sql | 6 +++--- .../vn/views/expeditionTruck_Control_Detail_Pallet.sql | 10 +++++----- 5 files changed, 14 insertions(+), 14 deletions(-) diff --git a/db/routines/vn/procedures/expeditionPallet_build.sql b/db/routines/vn/procedures/expeditionPallet_build.sql index 9fbb60100..bea56eae6 100644 --- a/db/routines/vn/procedures/expeditionPallet_build.sql +++ b/db/routines/vn/procedures/expeditionPallet_build.sql @@ -56,13 +56,13 @@ BEGIN LIMIT 1; IF vPalletFk IS NULL THEN - SELECT expeditionTruckFk + SELECT roadmapStopFk INTO vTruckFk FROM ( - SELECT rm.expeditionTruckFk, count(*) n + SELECT rm.roadmapStopFk, count(*) n FROM vn.routesMonitor rm JOIN tExpedition e ON e.routeFk = rm.routeFk - GROUP BY expeditionTruckFk + GROUP BY roadmapStopFk ORDER BY n DESC LIMIT 1) sub; diff --git a/db/routines/vn/views/expeditionCommon.sql b/db/routines/vn/views/expeditionCommon.sql index 46765e57c..fcf36a7d8 100644 --- a/db/routines/vn/views/expeditionCommon.sql +++ b/db/routines/vn/views/expeditionCommon.sql @@ -8,7 +8,7 @@ AS SELECT `rs`.`id` AS `truckFk`, `t`.`routeFk` AS `routeFk`, `es`.`id` AS `scanFk`, `e`.`id` AS `expeditionFk`, - `r`.`roadmapStopFk` AS `expeditionTruckFk`, + `r`.`roadmapStopFk` AS `roadmapStopFk`, `t`.`warehouseFk` AS `warehouseFk`, `e`.`created` AS `lastPacked`, `t`.`id` AS `ticketFk` diff --git a/db/routines/vn/views/expeditionTruck_Control.sql b/db/routines/vn/views/expeditionTruck_Control.sql index 838e1f89e..818ae3ae6 100644 --- a/db/routines/vn/views/expeditionTruck_Control.sql +++ b/db/routines/vn/views/expeditionTruck_Control.sql @@ -11,9 +11,9 @@ AS SELECT `e`.`truckFk` AS `id`, COUNT(DISTINCT `e`.`routeFk`) AS `routes`, COUNT(DISTINCT `e`.`scanFk`) AS `scans`, COUNT(DISTINCT `e`.`expeditionFk`) AS `expeditions`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, + sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`, max(`e`.`lastPacked`) AS `lastPacked` FROM `vn`.`expeditionCommon` `e` GROUP BY `e`.`truckFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, +ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC, `e`.`eta` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail.sql b/db/routines/vn/views/expeditionTruck_Control_Detail.sql index 96a5b78e6..51970544b 100644 --- a/db/routines/vn/views/expeditionTruck_Control_Detail.sql +++ b/db/routines/vn/views/expeditionTruck_Control_Detail.sql @@ -7,12 +7,12 @@ AS SELECT `e`.`truckFk` AS `id`, `e`.`palletFk` AS `pallet`, COUNT(DISTINCT `e`.`routeFk`) AS `routes`, COUNT(DISTINCT `e`.`scanFk`) AS `scans`, - COUNT(DISTINCT `e`.`expeditionTruckFk`) AS `destinos`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, + COUNT(DISTINCT `e`.`roadmapStopFk`) AS `destinos`, + sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`, max(`e`.`lastPacked`) AS `lastPacked` FROM `vn`.`expeditionCommon` `e` GROUP BY `e`.`truckFk`, `e`.`palletFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, +ORDER BY sum(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC, `e`.`eta`, `e`.`truckFk` diff --git a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql b/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql index 3f239432d..b7244ecf8 100644 --- a/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql +++ b/db/routines/vn/views/expeditionTruck_Control_Detail_Pallet.sql @@ -8,15 +8,15 @@ AS SELECT `e`.`truckFk` AS `id`, `e`.`routeFk` AS `route`, COUNT(DISTINCT `e`.`scanFk`) AS `scans`, `rs`.`description` AS `destinos`, - sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`, - `e`.`expeditionTruckFk` AS `expeditionTruckFk`, - max(`e`.`lastPacked`) AS `lastPacked` + SUM(`e`.`truckFk` <> `e`.`roadmapStopFk`) AS `fallos`, + `e`.`roadmapStopFk` AS `roadmapStopFk`, + MAX(`e`.`lastPacked`) AS `lastPacked` FROM ( `vn`.`expeditionCommon` `e` - LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`expeditionTruckFk`) + LEFT JOIN `vn`.`roadmapStop` `rs` ON(`rs`.`id` = `e`.`roadmapStopFk`) ) GROUP BY `e`.`truckFk`, `e`.`palletFk`, `e`.`routeFk` -ORDER BY sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) DESC, +ORDER BY SUM(`e`.`truckFk` <> `e`.`roadmapStopFk`) DESC, `e`.`palletFk` -- 2.40.1 From 208409acb2118e69e0485d7b2d6914bac0b45ddf Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 27 May 2024 11:50:15 +0200 Subject: [PATCH 059/413] refs #7406 add relation --- modules/worker/back/models/worker.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 4e7617aab..3eab43650 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -115,6 +115,11 @@ "type": "hasMany", "model": "Locker", "foreignKey": "workerFk" + }, + "trainingCourse": { + "type": "hasMany", + "model": "TrainingCourse", + "foreignKey": "workerFk" } }, "acls":[ -- 2.40.1 From e133dec514fef4a8e34757f0ba9419147d055af7 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 27 May 2024 11:55:42 +0200 Subject: [PATCH 060/413] refs #6861 feat: trigger --- db/routines/vn/triggers/itemShelvingSale_afterInsert.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql index 71ede88f7..f5bd88b1b 100644 --- a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql +++ b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql @@ -1,6 +1,6 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterInsert` - AFTER INSERT ON `itemShelving` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelvingSale_afterInsert` + AFTER INSERT ON `itemShelvingSale` FOR EACH ROW BEGIN -- 2.40.1 From 7559875aff5c3a10cd971998dce6dfd549859dc0 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 27 May 2024 12:08:14 +0200 Subject: [PATCH 061/413] feat: refs #7296 roadmapStopFk --- db/versions/11070-turquoiseCordyline/00-firstScript.sql | 2 ++ 1 file changed, 2 insertions(+) diff --git a/db/versions/11070-turquoiseCordyline/00-firstScript.sql b/db/versions/11070-turquoiseCordyline/00-firstScript.sql index 494080033..db123eb55 100644 --- a/db/versions/11070-turquoiseCordyline/00-firstScript.sql +++ b/db/versions/11070-turquoiseCordyline/00-firstScript.sql @@ -1 +1,3 @@ ALTER TABLE vn.routesMonitor CHANGE expeditionTruckFk roadmapStopFk int(11) DEFAULT NULL NULL; + +ALTER TABLE vn.routesMonitor ADD COLUMN expeditionTruckFk int(11) AS (roadmapStopFk) VIRTUAL; \ No newline at end of file -- 2.40.1 From 32aafc35453d4acdc44241814c3367c97f7b936b Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 27 May 2024 12:21:22 +0200 Subject: [PATCH 062/413] feat: refs #6861 trigger --- db/routines/vn/triggers/itemShelving_afterInsert.sql | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/triggers/itemShelving_afterInsert.sql b/db/routines/vn/triggers/itemShelving_afterInsert.sql index 86f149473..819e3e790 100644 --- a/db/routines/vn/triggers/itemShelving_afterInsert.sql +++ b/db/routines/vn/triggers/itemShelving_afterInsert.sql @@ -3,8 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterIns AFTER INSERT ON `itemShelving` FOR EACH ROW BEGIN - - INSERT INTO vn.itemShelvingLog( + INSERT INTO vn.itemShelvingLog( itemShelvingFk, workerFk, accion, @@ -13,8 +12,10 @@ BEGIN visible, `grouping`, packing, - available) - VALUES( NEW.id, + available + ) + VALUES ( + NEW.id, NEW.userFk, 'CREA REGISTRO', NEW.itemFk, @@ -22,6 +23,7 @@ BEGIN NEW.visible, NEW.`grouping`, NEW.packing, - NEW.available); + NEW.available + ); END$$ DELIMITER ; \ No newline at end of file -- 2.40.1 From 578b8a2c71348188a4da17cc568ecc2d9fa511e9 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 27 May 2024 14:28:13 +0200 Subject: [PATCH 063/413] refs #7406 changes sql, modelconfig model --- db/versions/11073-crimsonBirch/00-firstScript.sql | 9 +++++++++ modules/worker/back/model-config.json | 9 +++++++++ modules/worker/back/models/trainingCourseType.json | 4 ++-- 3 files changed, 20 insertions(+), 2 deletions(-) create mode 100644 db/versions/11073-crimsonBirch/00-firstScript.sql diff --git a/db/versions/11073-crimsonBirch/00-firstScript.sql b/db/versions/11073-crimsonBirch/00-firstScript.sql new file mode 100644 index 000000000..2ad04468f --- /dev/null +++ b/db/versions/11073-crimsonBirch/00-firstScript.sql @@ -0,0 +1,9 @@ +-- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('TrainingCourse','*','*','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('TrainingCourseType','*','*','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('TrainingCenter','*','*','ALLOW','ROLE','employee'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Worker','__get_trainingCourse','*','ALLOW','ROLE','employee'); diff --git a/modules/worker/back/model-config.json b/modules/worker/back/model-config.json index b7c355511..9bf2f014f 100644 --- a/modules/worker/back/model-config.json +++ b/modules/worker/back/model-config.json @@ -124,6 +124,15 @@ }, "Locker": { "dataSource": "vn" + }, + "TrainingCourse": { + "dataSource": "vn" + }, + "TrainingCourseType": { + "dataSource": "vn" + }, + "TrainingCenter": { + "dataSource": "vn" } } diff --git a/modules/worker/back/models/trainingCourseType.json b/modules/worker/back/models/trainingCourseType.json index 1dc708f2f..1a2a45bc7 100644 --- a/modules/worker/back/models/trainingCourseType.json +++ b/modules/worker/back/models/trainingCourseType.json @@ -1,5 +1,5 @@ { - "name": "trainingCourseType", + "name": "TrainingCourseType", "description": "List of trainings", "base": "VnModel", "options": { @@ -27,7 +27,7 @@ }, "trainingCourseType": { "type": "belongsTo", - "model": "trainingCourseType", + "model": "TrainingCourseType", "foreignKey": "trainingCourseTypeFk" }, "centerFk": { -- 2.40.1 From eb2dd5ba5bbd3a21777137e1da4fc1fcaf2a2a98 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 27 May 2024 16:17:44 +0200 Subject: [PATCH 064/413] refs #7406 acls --- db/versions/11073-crimsonBirch/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/11073-crimsonBirch/00-firstScript.sql b/db/versions/11073-crimsonBirch/00-firstScript.sql index 2ad04468f..7d76a75cd 100644 --- a/db/versions/11073-crimsonBirch/00-firstScript.sql +++ b/db/versions/11073-crimsonBirch/00-firstScript.sql @@ -6,4 +6,4 @@ INSERT INTO salix.ACL (model,property,accessType,permission,principalType,princi INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) VALUES ('TrainingCenter','*','*','ALLOW','ROLE','employee'); INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Worker','__get_trainingCourse','*','ALLOW','ROLE','employee'); + VALUES ('Worker','__get__trainingCourse','*','ALLOW','ROLE','employee'); -- 2.40.1 From b95009899ca6c2a68d106c426282d57dedd70b5b Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 28 May 2024 12:22:11 +0200 Subject: [PATCH 065/413] refs #7406 fix back --- modules/worker/back/models/trainingCourse.json | 7 +++---- .../worker/back/models/trainingCourseType.json | 18 ------------------ 2 files changed, 3 insertions(+), 22 deletions(-) diff --git a/modules/worker/back/models/trainingCourse.json b/modules/worker/back/models/trainingCourse.json index 7a44ad419..af466e13e 100644 --- a/modules/worker/back/models/trainingCourse.json +++ b/modules/worker/back/models/trainingCourse.json @@ -45,7 +45,6 @@ "hasDiploma": { "type" : "boolean" } - }, "relations": { "worker": { @@ -55,12 +54,12 @@ }, "trainingCourseType": { "type": "belongsTo", - "model": "trainingCourseType", + "model": "TrainingCourseType", "foreignKey": "trainingCourseTypeFk" }, - "centerFk": { + "trainingCenter": { "type": "belongsTo", - "model": "Center", + "model": "TrainingCenter", "foreignKey": "centerFk" } } diff --git a/modules/worker/back/models/trainingCourseType.json b/modules/worker/back/models/trainingCourseType.json index 1a2a45bc7..9bf8fc671 100644 --- a/modules/worker/back/models/trainingCourseType.json +++ b/modules/worker/back/models/trainingCourseType.json @@ -17,23 +17,5 @@ "type": "string", "required": true } - - }, - "relations": { - "worker": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "workerFk" - }, - "trainingCourseType": { - "type": "belongsTo", - "model": "TrainingCourseType", - "foreignKey": "trainingCourseTypeFk" - }, - "centerFk": { - "type": "belongsTo", - "model": "Center", - "foreignKey": "centerFk" - } } } -- 2.40.1 From 885aa5208aaa9c5c38c5296bc8ed8f03cd1de5ba Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 28 May 2024 17:23:58 +0200 Subject: [PATCH 066/413] feat : refs #6889 wip: check if is productionReviewer or owner --- back/models/collection.json | 10 ++++++++++ .../00-createRoleProductionReviewer.sql | 11 +++++++++++ modules/ticket/back/models/sale.js | 12 +++++++++++- 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql diff --git a/back/models/collection.json b/back/models/collection.json index cb8dc3d7c..8a8afeb89 100644 --- a/back/models/collection.json +++ b/back/models/collection.json @@ -1,6 +1,16 @@ { "name": "Collection", "base": "VnModel", + "properties": { + "id": { + "id": true, + "type": "number", + "required": true + }, + "workerFk": { + "type": "number" + } + }, "options": { "mysql": { "table": "collection" diff --git a/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql b/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql new file mode 100644 index 000000000..6c4b8e0d1 --- /dev/null +++ b/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql @@ -0,0 +1,11 @@ +INSERT INTO account.role + SET name = 'productionReviewer', + description = 'Revisor de producción', + hasLogin = TRUE, + created = util.VN_CURDATE(), + modified = util.VN_CURDATE(), + editorFk = NULL; + +UPDATE salix.ACL + SET principalId = 'productionReviewer' + WHERE property = 'isInPreparing'; \ No newline at end of file diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index 1b4d8e31c..f7af4fc21 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -68,6 +68,7 @@ module.exports = Self => { fields: ['family', 'minQuantity'], where: {id: itemId}, }, ctx.options); + if (item.family == 'EMB') return; if (await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*')) return; @@ -88,7 +89,16 @@ module.exports = Self => { if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; - if (newQuantity < item.minQuantity && newQuantity != available) + // WIP: Check if is owner + const ticketCollection = await models.TicketCollection.findOne({ + include: {relation: 'collection', fields: ['workerFk']}, + where: {ticketFk: ticketId} + }, ctx.options); + + // if(!res) look in SaleGroup.(ask for Sergio to make fixtures for this case) + const isOwner = res.collection.workerFk === ctx.req.accessToken.userId; + + if (newQuantity < item.minQuantity && newQuantity != available && !isOwner) throw new UserError('The amount cannot be less than the minimum'); if (ctx.isNewInstance || isReduction) return; -- 2.40.1 From fc606f7e367b966099de28490cb16b1db69bd6eb Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 29 May 2024 10:22:22 +0200 Subject: [PATCH 067/413] fix: refs #6889 rollback --- modules/ticket/back/models/sale.js | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index f7af4fc21..1b4d8e31c 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -68,7 +68,6 @@ module.exports = Self => { fields: ['family', 'minQuantity'], where: {id: itemId}, }, ctx.options); - if (item.family == 'EMB') return; if (await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*')) return; @@ -89,16 +88,7 @@ module.exports = Self => { if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; - // WIP: Check if is owner - const ticketCollection = await models.TicketCollection.findOne({ - include: {relation: 'collection', fields: ['workerFk']}, - where: {ticketFk: ticketId} - }, ctx.options); - - // if(!res) look in SaleGroup.(ask for Sergio to make fixtures for this case) - const isOwner = res.collection.workerFk === ctx.req.accessToken.userId; - - if (newQuantity < item.minQuantity && newQuantity != available && !isOwner) + if (newQuantity < item.minQuantity && newQuantity != available) throw new UserError('The amount cannot be less than the minimum'); if (ctx.isNewInstance || isReduction) return; -- 2.40.1 From a32db7840e0467f2d5c2b9a9ce60fef2213822e6 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 29 May 2024 16:54:24 +0200 Subject: [PATCH 068/413] feat: refs #6889 fixtures & models --- db/dump/fixtures.before.sql | 37 ++++++++++++++++--- modules/shelving/back/model-config.json | 6 +++ .../back/models/sectorCollection.json | 24 ++++++++++++ .../models/sectorCollectionSaleGroup.json | 30 +++++++++++++++ modules/ticket/back/models/saleGroup.json | 3 ++ 5 files changed, 94 insertions(+), 6 deletions(-) create mode 100644 modules/shelving/back/models/sectorCollection.json create mode 100644 modules/shelving/back/models/sectorCollectionSaleGroup.json diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 55f79220e..c1ac37798 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -762,7 +762,11 @@ INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeF (30, 1, 8, 1, 1, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), - (33, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL); + (33, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), + (34, 1, 1, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1103, 'BEJAR', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (35, 1, 1, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Somewhere in Philippines', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (36, 1, 1, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Ant-Man Adventure', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL); + INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) VALUES (1, 11, 1, 'ready'), @@ -808,7 +812,10 @@ INSERT INTO `vn`.`ticketTracking`(`ticketFk`, `stateFk`, `userFk`, `created`) (21, 1, 19, DATE_ADD(util.VN_NOW(), INTERVAL +1 MONTH)), (22, 1, 19, DATE_ADD(util.VN_NOW(), INTERVAL +1 MONTH)), (23, 16, 21, util.VN_NOW()), - (24, 16, 21, util.VN_NOW()); + (24, 16, 21, util.VN_NOW()), + (34, 14, 49, util.VN_NOW()), + (35, 14, 18, util.VN_NOW()), + (36, 14, 18, util.VN_NOW()); INSERT INTO `vn`.`deliveryPoint` (`id`, `name`, `ubication`) VALUES @@ -1068,7 +1075,10 @@ INSERT INTO `vn`.`sale`(`id`, `itemFk`, `ticketFk`, `concept`, `quantity`, `pric (37, 4, 31, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (36, 4, 30, 'Melee weapon heavy shield 100cm', 20, 1.72, 0, 0, 0, util.VN_CURDATE()), (38, 2, 32, 'Melee weapon combat fist 15cm', 30, 7.07, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH)), - (39, 1, 32, 'Ranged weapon longbow 200cm', 2, 103.49, 0, 0, 0, util.VN_CURDATE()); + (39, 1, 32, 'Ranged weapon longbow 200cm', 2, 103.49, 0, 0, 0, util.VN_CURDATE()), + (40, 2, 34, 'Melee weapon combat fist 15cm', 10.00, 3.91, 0, 0, 0, util.VN_CURDATE()), + (41, 2, 35, 'Melee weapon combat fist 15cm', 8.00, 3.01, 0, 0, 0, util.VN_CURDATE()), + (42, 2, 36, 'Melee weapon combat fist 15cm', 6.00, 2.50, 0, 0, 0, util.VN_CURDATE()); INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`) VALUES @@ -1247,14 +1257,18 @@ INSERT INTO `vn`.`operator` (`workerFk`, `numberOfWagons`, `trainFk`, `itemPacki INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`, `created`, `trainFk`) VALUES (1, 1106, 5, DATE_ADD(util.VN_CURDATE(),INTERVAL +1 DAY), 1), - (2, 1106, 14, util.VN_CURDATE(), 1); + (2, 1106, 14, util.VN_CURDATE(), 1), + (4, 49, 5, util.VN_CURDATE(), 1), + (5, 18, 5, util.VN_CURDATE(), 1); INSERT INTO `vn`.`ticketCollection`(`ticketFk`, `collectionFk`, `level`) VALUES (1, 1, 1), (2, 1, NULL), (3, 2, NULL), - (23, 1, NULL); + (23, 1, NULL), + (34, 4, 1), + (35, 5, 1); INSERT INTO `vn`.`genus`(`id`, `name`) VALUES @@ -3705,7 +3719,8 @@ INSERT IGNORE INTO vn.saleGroup SET id = 4, userFk = 1, parkingFk = 9, - sectorFk = 9992; + sectorFk = 9992, + ticketFk = 36; INSERT IGNORE INTO vn.sectorCollectionSaleGroup SET id = 9999, @@ -3807,3 +3822,13 @@ INSERT INTO `vn`.`ledgerCompany` SET INSERT INTO `vn`.`ledgerConfig` SET maxTolerance = 0.01; + +INSERT INTO vn.sectorCollection + SET id = 2, + userFk = 18, + sectorFk = 1; + +INSERT INTO vn.sectorCollectionSaleGroup + SET id = 8, + sectorCollectionFk = 2, + saleGroupFk = 4; diff --git a/modules/shelving/back/model-config.json b/modules/shelving/back/model-config.json index 89a0832b0..6f3ffb5ea 100644 --- a/modules/shelving/back/model-config.json +++ b/modules/shelving/back/model-config.json @@ -11,6 +11,12 @@ "Sector": { "dataSource": "vn" }, + "SectorCollection": { + "dataSource": "vn" + }, + "SectorCollectionSaleGroup": { + "dataSource": "vn" + }, "Train": { "dataSource": "vn" } diff --git a/modules/shelving/back/models/sectorCollection.json b/modules/shelving/back/models/sectorCollection.json new file mode 100644 index 000000000..bf2cc7985 --- /dev/null +++ b/modules/shelving/back/models/sectorCollection.json @@ -0,0 +1,24 @@ +{ + "name": "SectorCollection", + "base": "VnModel", + "options": { + "mysql": { + "table": "sectorCollection" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "created": { + "type": "date" + }, + "userFk": { + "type": "number" + }, + "sectorFk": { + "type": "number" + } + } +} diff --git a/modules/shelving/back/models/sectorCollectionSaleGroup.json b/modules/shelving/back/models/sectorCollectionSaleGroup.json new file mode 100644 index 000000000..421bdc885 --- /dev/null +++ b/modules/shelving/back/models/sectorCollectionSaleGroup.json @@ -0,0 +1,30 @@ +{ + "name": "SectorCollectionSaleGroup", + "base": "VnModel", + "options": { + "mysql": { + "table": "sectorCollectionSaleGroup" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "created": { + "type": "date" + } + }, + "relations": { + "sectorCollection": { + "type": "belongsTo", + "model": "SectorCollection", + "foreignKey": "sectorCollectionFk" + }, + "saleGroup": { + "type": "belongsTo", + "model": "SaleGroup", + "foreignKey": "saleGroupFk" + } + } +} diff --git a/modules/ticket/back/models/saleGroup.json b/modules/ticket/back/models/saleGroup.json index d5cf82cb5..aa78b4167 100644 --- a/modules/ticket/back/models/saleGroup.json +++ b/modules/ticket/back/models/saleGroup.json @@ -14,6 +14,9 @@ }, "parkingFk": { "type": "number" + }, + "ticketFk": { + "type": "number" } }, "relations": { -- 2.40.1 From 05e6e10337de5277eb066631ea568c366d58b5c6 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 30 May 2024 10:04:34 +0200 Subject: [PATCH 069/413] fix: refs #6889 fix back tests --- db/dump/fixtures.before.sql | 6 +++--- .../11060-tealGalax/00-createRoleProductionReviewer.sql | 6 +++--- modules/item/back/methods/item/specs/getBalance.spec.js | 2 +- .../back/methods/sales-monitor/specs/salesFilter.spec.js | 2 +- .../back/methods/route/specs/getSuggestedTickets.spec.js | 2 +- modules/ticket/back/methods/ticket/specs/filter.spec.js | 2 +- .../back/methods/ticket/specs/priceDifference.spec.js | 2 +- 7 files changed, 11 insertions(+), 11 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index c1ac37798..e42db7ace 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -763,9 +763,9 @@ INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeF (31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (33, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), - (34, 1, 1, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1103, 'BEJAR', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), - (35, 1, 1, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Somewhere in Philippines', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), - (36, 1, 1, 1, NULL, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Ant-Man Adventure', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL); + (34, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1103, 'BEJAR', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (35, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Somewhere in Philippines', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (36, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Ant-Man Adventure', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL); INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) VALUES diff --git a/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql b/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql index 6c4b8e0d1..b65740cc8 100644 --- a/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql +++ b/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql @@ -6,6 +6,6 @@ INSERT INTO account.role modified = util.VN_CURDATE(), editorFk = NULL; -UPDATE salix.ACL - SET principalId = 'productionReviewer' - WHERE property = 'isInPreparing'; \ No newline at end of file +-- UPDATE salix.ACL +-- SET principalId = 'productionReviewer' +-- WHERE property = 'isInPreparing'; \ No newline at end of file diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js index 5e5148595..728b5f33e 100644 --- a/modules/item/back/methods/item/specs/getBalance.spec.js +++ b/modules/item/back/methods/item/specs/getBalance.spec.js @@ -64,7 +64,7 @@ describe('item getBalance()', () => { const secondItemBalance = await models.Item.getBalance(ctx, secondFilter, options); expect(firstItemBalance[9].claimFk).toEqual(null); - expect(secondItemBalance[4].claimFk).toEqual(2); + expect(secondItemBalance[7].claimFk).toEqual(2); await tx.rollback(); } catch (e) { diff --git a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js index bdafd14e2..c3da7f08b 100644 --- a/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js +++ b/modules/monitor/back/methods/sales-monitor/specs/salesFilter.spec.js @@ -151,7 +151,7 @@ describe('SalesMonitor salesFilter()', () => { const result = await models.SalesMonitor.salesFilter(ctx, filter, options); const firstRow = result[0]; - expect(result.length).toEqual(12); + expect(result.length).toEqual(15); expect(firstRow.alertLevel).not.toEqual(0); await tx.rollback(); diff --git a/modules/route/back/methods/route/specs/getSuggestedTickets.spec.js b/modules/route/back/methods/route/specs/getSuggestedTickets.spec.js index 0acc6c1a7..b4b743de3 100644 --- a/modules/route/back/methods/route/specs/getSuggestedTickets.spec.js +++ b/modules/route/back/methods/route/specs/getSuggestedTickets.spec.js @@ -28,7 +28,7 @@ describe('route getSuggestedTickets()', () => { const result = await models.Route.getSuggestedTickets(routeID, options); - const length = result.length; + const length = result.length; // cambiar agenciaMode de los tickets por el 8 y ver si da algún problema const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; expect(result.length).toEqual(4); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index e495a41f5..8008acfaf 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -68,7 +68,7 @@ describe('ticket filter()', () => { const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); - expect(result.length).toEqual(7); + expect(result.length).toEqual(10); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js index e5c06b6dd..b49bbaba0 100644 --- a/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js +++ b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js @@ -84,7 +84,7 @@ describe('sale priceDifference()', () => { const {items} = await models.Ticket.priceDifference(ctx, options); - expect(items[0].movable).toEqual(410); + expect(items[0].movable).toEqual(386); expect(items[1].movable).toEqual(1810); await tx.rollback(); -- 2.40.1 From 5158017edd64e5adb7ec75b23975cdaa2ca3657d Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 30 May 2024 11:21:42 +0200 Subject: [PATCH 070/413] fix: refs #6889 fix back tests --- .../ticket/back/methods/ticket/specs/priceDifference.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js index b49bbaba0..7dc1c8ed2 100644 --- a/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js +++ b/modules/ticket/back/methods/ticket/specs/priceDifference.spec.js @@ -42,7 +42,7 @@ describe('sale priceDifference()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 1106}}}; + const ctx = {req: {accessToken: {userId: 1105}}}; ctx.args = { id: 1, landed: Date.vnNew(), -- 2.40.1 From 002111d8d1b0cd37f598ca19b4dd37b26790e244 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 30 May 2024 11:47:12 +0200 Subject: [PATCH 071/413] fix: refs #6889 allocate 'productionReviewer' role to revision dep. workers & check if is owner or reviewer --- .../00-createRoleProductionReviewer.sql | 9 +++++- .../route/specs/getSuggestedTickets.spec.js | 2 +- .../back/methods/ticket/isEditableOrThrow.js | 28 +++++++++++++------ 3 files changed, 28 insertions(+), 11 deletions(-) diff --git a/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql b/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql index b65740cc8..ad3e2f5b2 100644 --- a/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql +++ b/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql @@ -8,4 +8,11 @@ INSERT INTO account.role -- UPDATE salix.ACL -- SET principalId = 'productionReviewer' --- WHERE property = 'isInPreparing'; \ No newline at end of file +-- WHERE property = 'isInPreparing'; + +UPDATE account.user u + JOIN vn.workerDepartment wd ON wd.workerFk = u.id + JOIN vn.department d ON wd.departmentFk = d.id + JOIN account.role r ON r.name = 'productionReviewer' + SET u.role = r.id + WHERE d.name = 'REVISION'; \ No newline at end of file diff --git a/modules/route/back/methods/route/specs/getSuggestedTickets.spec.js b/modules/route/back/methods/route/specs/getSuggestedTickets.spec.js index b4b743de3..0acc6c1a7 100644 --- a/modules/route/back/methods/route/specs/getSuggestedTickets.spec.js +++ b/modules/route/back/methods/route/specs/getSuggestedTickets.spec.js @@ -28,7 +28,7 @@ describe('route getSuggestedTickets()', () => { const result = await models.Route.getSuggestedTickets(routeID, options); - const length = result.length; // cambiar agenciaMode de los tickets por el 8 y ver si da algún problema + const length = result.length; const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; expect(result.length).toEqual(4); diff --git a/modules/ticket/back/methods/ticket/isEditableOrThrow.js b/modules/ticket/back/methods/ticket/isEditableOrThrow.js index 16cff84f1..0adc9e0f9 100644 --- a/modules/ticket/back/methods/ticket/isEditableOrThrow.js +++ b/modules/ticket/back/methods/ticket/isEditableOrThrow.js @@ -8,18 +8,13 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const state = await models.TicketState.findOne({ - where: {ticketFk: id} - }, myOptions); - + const state = await models.TicketState.findOne({where: {ticketFk: id}}, myOptions); const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); + const isProductionReviewer = await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*'); const canEditWeeklyTicket = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'canEditWeekly', 'WRITE'); const alertLevel = state ? state.alertLevel : null; const ticket = await models.Ticket.findById(id, { - fields: ['clientFk'], - include: { - relation: 'client' - } + fields: ['clientFk'], include: {relation: 'client'} }, myOptions); const isLocked = await models.Ticket.isLocked(id, myOptions); @@ -29,10 +24,25 @@ module.exports = Self => { const isNormalClient = ticket && ticket.client().typeFk == 'normal'; const isEditable = !(alertLevelGreaterThanZero && isNormalClient); + const ticketCollection = await models.TicketCollection.findOne({ + include: {relation: 'collection'}, where: {ticketFk: id} + }, myOptions); + let workerId = ticketCollection?.collection()?.workerFk; + + if (!workerId) { + const saleGroup = await models.SaleGroup.findOne({fields: ['id'], where: {ticketFk: id}}, myOptions); + const sectorCollectionSaleGroup = saleGroup && await models.SectorCollectionSaleGroup.findOne({ + include: {relation: 'sectorCollection'}, where: {saleGroupFk: saleGroup.id} + }, myOptions); + + workerId = sectorCollectionSaleGroup?.sectorCollection()?.userFk; + } + const isOwner = workerId === ctx.req.accessToken.userId; + if (!ticket) throw new ForbiddenError(`The ticket doesn't exist.`); - if (!isEditable && !isRoleAdvanced) + if (!isEditable && !isRoleAdvanced && !isProductionReviewer && !isOwner) throw new ForbiddenError(`This ticket is not editable.`); if (isLocked && !isWeekly) -- 2.40.1 From 8212eb82c7e3e05f08fa5be02b625761b5f3a0d9 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 30 May 2024 14:29:13 +0200 Subject: [PATCH 072/413] refactor: refs #6889 improve file loading logic --- e2e/tests.js | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/e2e/tests.js b/e2e/tests.js index 829056f4c..e53dd8f7c 100644 --- a/e2e/tests.js +++ b/e2e/tests.js @@ -5,6 +5,7 @@ require('regenerator-runtime/runtime'); require('vn-loopback/server/boot/date')(); const getopts = require('getopts'); +const fs = require('fs'); const path = require('path'); const Myt = require('@verdnatura/myt/myt'); const Run = require('@verdnatura/myt/myt-run'); @@ -35,22 +36,9 @@ async function test() { const Jasmine = require('jasmine'); const jasmine = new Jasmine(); - const specFiles = [ - `./e2e/paths/01*/*[sS]pec.js`, - `./e2e/paths/02*/*[sS]pec.js`, - `./e2e/paths/03*/*[sS]pec.js`, - `./e2e/paths/04*/*[sS]pec.js`, - `./e2e/paths/05*/*[sS]pec.js`, - `./e2e/paths/06*/*[sS]pec.js`, - `./e2e/paths/07*/*[sS]pec.js`, - `./e2e/paths/08*/*[sS]pec.js`, - `./e2e/paths/09*/*[sS]pec.js`, - `./e2e/paths/10*/*[sS]pec.js`, - `./e2e/paths/11*/*[sS]pec.js`, - `./e2e/paths/12*/*[sS]pec.js`, - `./e2e/paths/13*/*[sS]pec.js`, - `./e2e/paths/**/*[sS]pec.js` - ]; + const e2ePath = './e2e/paths'; + const specFiles = fs.readdirSync(e2ePath).sort().map(folder => `${e2ePath}/${folder}/*[sS]pec.js`); + specFiles.push(`${e2ePath}/**/*[sS]pec.js`); jasmine.loadConfig({ spec_dir: '.', -- 2.40.1 From 8a54f7c5c7e408e790b360deb33c815651c386e4 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 30 May 2024 14:34:27 +0200 Subject: [PATCH 073/413] refactor: refs #6889 improve file loading logic --- e2e/tests.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/e2e/tests.js b/e2e/tests.js index e53dd8f7c..166d666e2 100644 --- a/e2e/tests.js +++ b/e2e/tests.js @@ -37,8 +37,11 @@ async function test() { const jasmine = new Jasmine(); const e2ePath = './e2e/paths'; - const specFiles = fs.readdirSync(e2ePath).sort().map(folder => `${e2ePath}/${folder}/*[sS]pec.js`); - specFiles.push(`${e2ePath}/**/*[sS]pec.js`); + const file = '*[sS]pec.js'; + const specFiles = fs.readdirSync(e2ePath) + .sort() + .map(folder => `${e2ePath}/${folder}/${file}`) + .concat(`${e2ePath}/**/${file}`); jasmine.loadConfig({ spec_dir: '.', -- 2.40.1 From bd82bb011a2283ccbf5aa175be7518637c1224b2 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 31 May 2024 08:44:30 +0200 Subject: [PATCH 074/413] fix(transferInvoice): separate invoice functionality from generating PDF and adapt tests --- loopback/locale/en.json | 5 +- loopback/locale/es.json | 5 +- loopback/locale/fr.json | 5 +- loopback/locale/pt.json | 5 +- .../invoiceOut/specs/transferinvoice.spec.js | 90 ++++++++++--------- .../methods/invoiceOut/transferInvoice.js | 28 ++++-- .../invoiceOut/front/descriptor-menu/index.js | 2 +- modules/ticket/back/methods/sale/clone.js | 1 + 8 files changed, 81 insertions(+), 60 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 551b544b6..48ec17535 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -227,5 +227,6 @@ "They're not your subordinate": "They're not your subordinate", "InvoiceIn is already booked": "InvoiceIn is already booked", "This workCenter is already assigned to this agency": "This workCenter is already assigned to this agency", - "You can only have one PDA": "You can only have one PDA" -} \ No newline at end of file + "You can only have one PDA": "You can only have one PDA", + "It has been invoiced but the PDF could not be generated": "It has been invoiced but the PDF could not be generated" +} diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 4a7e1505c..169b4bc01 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -359,5 +359,6 @@ "It was not able to create the invoice": "No se pudo crear la factura", "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)", "This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario", - "You can only have one PDA": "Solo puedes tener un PDA" -} \ No newline at end of file + "You can only have one PDA": "Solo puedes tener un PDA", + "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF" +} diff --git a/loopback/locale/fr.json b/loopback/locale/fr.json index 44f5e35d3..2bb23c3fc 100644 --- a/loopback/locale/fr.json +++ b/loopback/locale/fr.json @@ -356,5 +356,6 @@ "InvoiceIn is already booked": "La facture reçue est déjà comptabilisée", "This workCenter is already assigned to this agency": "Ce centre de travail est déjà assigné à cette agence", "Select ticket or client": "Choisissez un ticket ou un client", - "It was not able to create the invoice": "Il n'a pas été possible de créer la facture" -} \ No newline at end of file + "It was not able to create the invoice": "Il n'a pas été possible de créer la facture", + "It has been invoiced but the PDF could not be generated": "La facture a été émise mais le PDF n'a pas pu être généré" +} diff --git a/loopback/locale/pt.json b/loopback/locale/pt.json index b11eeefc6..1ebcfa3de 100644 --- a/loopback/locale/pt.json +++ b/loopback/locale/pt.json @@ -356,5 +356,6 @@ "InvoiceIn is already booked": "InvoiceIn já está reservado", "This workCenter is already assigned to this agency": "Este centro de trabalho já está atribuído a esta agência", "Select ticket or client": "Selecione um ticket ou cliente", - "It was not able to create the invoice": "Não foi possível criar a fatura" -} \ No newline at end of file + "It was not able to create the invoice": "Não foi possível criar a fatura", + "It has been invoiced but the PDF could not be generated": "Foi faturado, mas o PDF não pôde ser gerado" +} diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index eaaef3e26..cf656f6da 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -1,4 +1,4 @@ - +/* eslint max-len: ["error", { "code": 150 }]*/ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); @@ -17,27 +17,19 @@ describe('InvoiceOut transferInvoice()', () => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ active: activeCtx }); - spyOn(models.InvoiceOut, 'makePdfAndNotify'); }); it('should return the id of the created issued invoice', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; - const args = { - id: '4', - refFk: 'T4444444', - newClientFk: 1, - cplusRectificationTypeFk: 1, - siiTypeInvoiceOutFk: 1, - invoiceCorrectionTypeFk: 1 - }; - ctx.args = args; + const id = 4; + const newClient = 1; + spyOn(models.InvoiceOut, 'makePdfList'); + try { - const {clientFk: oldClient} = await models.InvoiceOut.findById(args.id, {fields: ['clientFk']}); + const {clientFk: oldClient} = await models.InvoiceOut.findById(id, {fields: ['clientFk']}); const invoicesBefore = await models.InvoiceOut.find({}, options); - const result = await models.InvoiceOut.transferInvoice( - ctx, - options); + const result = await models.InvoiceOut.transferInvoice(ctx, id, 'T4444444', newClient, 1, 1, 1, true, options); const invoicesAfter = await models.InvoiceOut.find({}, options); const rectificativeInvoice = invoicesAfter[invoicesAfter.length - 2]; const newInvoice = invoicesAfter[invoicesAfter.length - 1]; @@ -45,7 +37,7 @@ describe('InvoiceOut transferInvoice()', () => { expect(result).toBeDefined(); expect(invoicesAfter.length - invoicesBefore.length).toEqual(2); expect(rectificativeInvoice.clientFk).toEqual(oldClient); - expect(newInvoice.clientFk).toEqual(args.newClientFk); + expect(newInvoice.clientFk).toEqual(newClient); await tx.rollback(); } catch (e) { @@ -54,22 +46,13 @@ describe('InvoiceOut transferInvoice()', () => { } }); - it('should throw an UserError when it is the same client', async() => { + it('should throw an error when it is the same client', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; - const args = { - id: '1', - refFk: 'T1111111', - newClientFk: 1101, - cplusRectificationTypeFk: 1, - siiTypeInvoiceOutFk: 1, - invoiceCorrectionTypeFk: 1 - }; - ctx.args = args; + spyOn(models.InvoiceOut, 'makePdfList'); + try { - await models.InvoiceOut.transferInvoice( - ctx, - options); + await models.InvoiceOut.transferInvoice(ctx, '1', 'T1111111', 1101, 1, 1, 1, true, options); await tx.rollback(); } catch (e) { expect(e.message).toBe(`Select a different client`); @@ -77,26 +60,49 @@ describe('InvoiceOut transferInvoice()', () => { } }); - it('should throw an UserError when it is refund', async() => { + it('should throw an error when it is refund', async() => { const tx = await models.InvoiceOut.beginTransaction({}); const options = {transaction: tx}; - const args = { - id: '1', - refFk: 'T1111111', - newClientFk: 1102, - cplusRectificationTypeFk: 1, - siiTypeInvoiceOutFk: 1, - invoiceCorrectionTypeFk: 1 - }; - ctx.args = args; + spyOn(models.InvoiceOut, 'makePdfList'); try { - await models.InvoiceOut.transferInvoice( - ctx, - options); + await models.InvoiceOut.transferInvoice(ctx, '1', 'T1111111', 1102, 1, 1, 1, true, options); await tx.rollback(); } catch (e) { expect(e.message).toContain(`This ticket is already a refund`); await tx.rollback(); } }); + + it('should throw an error when pdf failed', async() => { + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + spyOn(models.InvoiceOut, 'makePdfList').and.returnValue(() => { + throw new Error('test'); + }); + + try { + await models.InvoiceOut.transferInvoice(ctx, '1', 'T1111111', 1102, 1, 1, 1, true, options); + await tx.rollback(); + } catch (e) { + expect(e.message).toContain(`It has been invoiced but the PDF could not be generated`); + await tx.rollback(); + } + }); + + it('should not generate an invoice', async() => { + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + spyOn(models.InvoiceOut, 'makePdfList'); + + let response; + try { + response = await models.InvoiceOut.transferInvoice(ctx, '1', 'T1111111', 1102, 1, 1, 1, false, options); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + + expect(response).not.toBeDefined(); + }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index b5eb9bed5..72e647efe 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -1,3 +1,4 @@ +/* eslint max-len: ["error", { "code": 160 }]*/ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { @@ -37,13 +38,13 @@ module.exports = Self => { required: true }, { - arg: 'checked', + arg: 'makeInvoice', type: 'boolean', required: true }, ], returns: { - type: 'boolean', + type: 'object', root: true }, http: { @@ -52,11 +53,11 @@ module.exports = Self => { } }); - Self.transferInvoice = async(ctx, options) => { + Self.transferInvoice = async(ctx, id, refFk, newClientFk, cplusRectificationTypeFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk, makeInvoice, options) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; - const {id, refFk, newClientFk, cplusRectificationTypeFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk} = ctx.args; - const checked = ctx.args.checked; + let invoiceId; + let tx; if (typeof options == 'object') Object.assign(myOptions, options); @@ -102,13 +103,22 @@ module.exports = Self => { await models.Ticket.invoiceTickets(ctx, refundTicketIds, invoiceCorrection, myOptions); - if (!checked) { - const [invoiceId] = await models.Ticket.invoiceTicketsAndPdf(ctx, clonedTicketIds, null, myOptions); - return invoiceId; - } + if (makeInvoice) + invoiceId = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, null, myOptions); + + tx && await tx.commit(); } catch (e) { if (tx) await tx.rollback(); throw e; } + + if (tx && makeInvoice) { + try { + await models.InvoiceOut.makePdfList(ctx, invoiceId, null); + } catch (e) { + throw new UserError('It has been invoiced but the PDF could not be generated'); + } + } + return invoiceId; }; }; diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index 0d7fb32dd..8ea4507ec 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -158,7 +158,7 @@ class Controller extends Section { cplusRectificationTypeFk: this.cplusRectificationType, siiTypeInvoiceOutFk: this.siiTypeInvoiceOut, invoiceCorrectionTypeFk: this.invoiceCorrectionType, - checked: this.checked + makeInvoice: this.checked }; this.$http.get(`Clients/${this.clientId}`).then(response => { diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index 77c40d8a0..fa1079fbe 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -135,6 +135,7 @@ module.exports = Self => { const now = Date.vnNew(); const ticket = await models.Ticket.findById(ticketId, null, myOptions); + if (!ctx.args) ctx.args = {}; ctx.args.clientId = ticket.clientFk; ctx.args.shipped = now; ctx.args.landed = now; -- 2.40.1 From 788f334e704a1347af0eb4dc3fa92e6a9592c539 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 31 May 2024 09:29:47 +0200 Subject: [PATCH 075/413] intros --- .../invoiceOut/specs/transferinvoice.spec.js | 12 ++++++++++-- .../back/methods/invoiceOut/transferInvoice.js | 13 +++++++++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js index cf656f6da..22787e730 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -1,4 +1,3 @@ -/* eslint max-len: ["error", { "code": 150 }]*/ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); @@ -29,7 +28,16 @@ describe('InvoiceOut transferInvoice()', () => { try { const {clientFk: oldClient} = await models.InvoiceOut.findById(id, {fields: ['clientFk']}); const invoicesBefore = await models.InvoiceOut.find({}, options); - const result = await models.InvoiceOut.transferInvoice(ctx, id, 'T4444444', newClient, 1, 1, 1, true, options); + const result = await models.InvoiceOut.transferInvoice( + ctx, + id, + 'T4444444', + newClient, + 1, + 1, + 1, + true, + options); const invoicesAfter = await models.InvoiceOut.find({}, options); const rectificativeInvoice = invoicesAfter[invoicesAfter.length - 2]; const newInvoice = invoicesAfter[invoicesAfter.length - 1]; diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index 72e647efe..f5530d772 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -1,4 +1,3 @@ -/* eslint max-len: ["error", { "code": 160 }]*/ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { @@ -53,7 +52,17 @@ module.exports = Self => { } }); - Self.transferInvoice = async(ctx, id, refFk, newClientFk, cplusRectificationTypeFk, siiTypeInvoiceOutFk, invoiceCorrectionTypeFk, makeInvoice, options) => { + Self.transferInvoice = async( + ctx, + id, + refFk, + newClientFk, + cplusRectificationTypeFk, + siiTypeInvoiceOutFk, + invoiceCorrectionTypeFk, + makeInvoice, + options + ) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; let invoiceId; -- 2.40.1 From 38bea60776d2ccc3dd18d7e35b332f26f56cb4d9 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 31 May 2024 09:49:58 +0200 Subject: [PATCH 076/413] refactor: refs #6889 script sql --- .../00-createRoleProductionReviewer.sql | 18 -------- .../11060-tealGalax/00-createRoleReviewer.sql | 46 +++++++++++++++++++ 2 files changed, 46 insertions(+), 18 deletions(-) delete mode 100644 db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql create mode 100644 db/versions/11060-tealGalax/00-createRoleReviewer.sql diff --git a/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql b/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql deleted file mode 100644 index ad3e2f5b2..000000000 --- a/db/versions/11060-tealGalax/00-createRoleProductionReviewer.sql +++ /dev/null @@ -1,18 +0,0 @@ -INSERT INTO account.role - SET name = 'productionReviewer', - description = 'Revisor de producción', - hasLogin = TRUE, - created = util.VN_CURDATE(), - modified = util.VN_CURDATE(), - editorFk = NULL; - --- UPDATE salix.ACL --- SET principalId = 'productionReviewer' --- WHERE property = 'isInPreparing'; - -UPDATE account.user u - JOIN vn.workerDepartment wd ON wd.workerFk = u.id - JOIN vn.department d ON wd.departmentFk = d.id - JOIN account.role r ON r.name = 'productionReviewer' - SET u.role = r.id - WHERE d.name = 'REVISION'; \ No newline at end of file diff --git a/db/versions/11060-tealGalax/00-createRoleReviewer.sql b/db/versions/11060-tealGalax/00-createRoleReviewer.sql new file mode 100644 index 000000000..21cb43434 --- /dev/null +++ b/db/versions/11060-tealGalax/00-createRoleReviewer.sql @@ -0,0 +1,46 @@ +use account; + +INSERT INTO account.role + SET name = 'reviewer', + description = 'Revisor de producción', + hasLogin = TRUE, + created = util.VN_CURDATE(), + modified = util.VN_CURDATE(), + editorFk = NULL; + +INSERT IGNORE INTO account.roleInherit( + role, + inheritsFrom +) + SELECT r1.id, + r2.id + FROM account.role r1 + JOIN account.role r2 + WHERE r2.name = 'production' + AND r1.name = 'reviewer' + UNION + SELECT ri.role, + r2.id + FROM account.roleInherit ri + JOIN account.role r1 ON r1.id = ri.role + JOIN account.role r2 ON r2.name = 'reviewer' + WHERE r1.name IN ('claimManager', 'productionBoss') + GROUP BY ri.role; + +DELETE ri + FROM account.roleInherit ri + JOIN account.role r1 ON ri.role = r1.id + JOIN account.role r2 ON ri.inheritsFrom = r2.id + WHERE r1.name = 'replenisher' + AND r2.name = 'buyer'; + +UPDATE salix.ACL + SET principalId = 'reviewer' + WHERE property = 'isInPreparing'; + +UPDATE account.user u + JOIN vn.workerDepartment wd ON wd.workerFk = u.id + JOIN vn.department d ON wd.departmentFk = d.id + JOIN account.role r ON r.name = 'reviewer' + SET u.role = r.id + WHERE d.name IN ('REVISION', 'PREVIA'); \ No newline at end of file -- 2.40.1 From e09a8f2eb77007e7add79d74858c44fb11d16bd2 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 31 May 2024 12:41:38 +0200 Subject: [PATCH 077/413] refs #6897 remove code redirection --- modules/entry/front/main/index.html | 20 +------------------- modules/entry/front/main/index.js | 7 ++++++- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/modules/entry/front/main/index.html b/modules/entry/front/main/index.html index f6a4c61fc..fd40910d9 100644 --- a/modules/entry/front/main/index.html +++ b/modules/entry/front/main/index.html @@ -1,22 +1,4 @@ - - - - - - - - - - + diff --git a/modules/entry/front/main/index.js b/modules/entry/front/main/index.js index 75f1d098a..cc0a8d6a3 100644 --- a/modules/entry/front/main/index.js +++ b/modules/entry/front/main/index.js @@ -1,7 +1,12 @@ import ngModule from '../module'; import ModuleMain from 'salix/components/module-main'; -export default class Entry extends ModuleMain {} +export default class Entry extends ModuleMain { + async $onInit() { + this.$state.go('home'); + window.location.href = await this.vnApp.getUrl(`entry/`); + } +} ngModule.vnComponent('vnEntry', { controller: Entry, -- 2.40.1 From 4772509b677f4916d4e7556434758177a0eedcbb Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 31 May 2024 12:51:06 +0200 Subject: [PATCH 078/413] fix: refs #6889 e2e tests --- db/dump/fixtures.before.sql | 6 ++-- .../11060-tealGalax/00-createRoleReviewer.sql | 28 +++++++++---------- .../05-ticket/01-sale/02_edit_sale.spec.js | 2 +- e2e/tests.js | 23 ++++++++++----- 4 files changed, 35 insertions(+), 24 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index e42db7ace..24225c99a 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1259,7 +1259,8 @@ INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`, `created`, `trainFk`) (1, 1106, 5, DATE_ADD(util.VN_CURDATE(),INTERVAL +1 DAY), 1), (2, 1106, 14, util.VN_CURDATE(), 1), (4, 49, 5, util.VN_CURDATE(), 1), - (5, 18, 5, util.VN_CURDATE(), 1); + (5, 18, 5, util.VN_CURDATE(), 1), + (6, 18, 5, util.VN_CURDATE(), 1); INSERT INTO `vn`.`ticketCollection`(`ticketFk`, `collectionFk`, `level`) VALUES @@ -1268,7 +1269,8 @@ INSERT INTO `vn`.`ticketCollection`(`ticketFk`, `collectionFk`, `level`) (3, 2, NULL), (23, 1, NULL), (34, 4, 1), - (35, 5, 1); + (35, 5, 1), + (8, 6, 1); INSERT INTO `vn`.`genus`(`id`, `name`) VALUES diff --git a/db/versions/11060-tealGalax/00-createRoleReviewer.sql b/db/versions/11060-tealGalax/00-createRoleReviewer.sql index 21cb43434..bf2984702 100644 --- a/db/versions/11060-tealGalax/00-createRoleReviewer.sql +++ b/db/versions/11060-tealGalax/00-createRoleReviewer.sql @@ -1,6 +1,6 @@ use account; -INSERT INTO account.role +INSERT INTO role SET name = 'reviewer', description = 'Revisor de producción', hasLogin = TRUE, @@ -8,29 +8,29 @@ INSERT INTO account.role modified = util.VN_CURDATE(), editorFk = NULL; -INSERT IGNORE INTO account.roleInherit( +INSERT INTO roleInherit( role, inheritsFrom ) SELECT r1.id, r2.id - FROM account.role r1 - JOIN account.role r2 - WHERE r2.name = 'production' - AND r1.name = 'reviewer' + FROM role r1 + JOIN role r2 + WHERE r1.name = 'reviewer' + AND r2.name = 'production' UNION SELECT ri.role, r2.id - FROM account.roleInherit ri - JOIN account.role r1 ON r1.id = ri.role - JOIN account.role r2 ON r2.name = 'reviewer' + FROM roleInherit ri + JOIN role r1 ON r1.id = ri.role + JOIN role r2 ON r2.name = 'reviewer' WHERE r1.name IN ('claimManager', 'productionBoss') GROUP BY ri.role; DELETE ri - FROM account.roleInherit ri - JOIN account.role r1 ON ri.role = r1.id - JOIN account.role r2 ON ri.inheritsFrom = r2.id + FROM roleInherit ri + JOIN role r1 ON ri.role = r1.id + JOIN role r2 ON ri.inheritsFrom = r2.id WHERE r1.name = 'replenisher' AND r2.name = 'buyer'; @@ -38,9 +38,9 @@ UPDATE salix.ACL SET principalId = 'reviewer' WHERE property = 'isInPreparing'; -UPDATE account.user u +UPDATE user u JOIN vn.workerDepartment wd ON wd.workerFk = u.id JOIN vn.department d ON wd.departmentFk = d.id - JOIN account.role r ON r.name = 'reviewer' + JOIN role r ON r.name = 'reviewer' SET u.role = r.id WHERE d.name IN ('REVISION', 'PREVIA'); \ No newline at end of file diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js index 4f54ad860..e0f32fc3a 100644 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js @@ -225,7 +225,7 @@ describe('Ticket Edit sale path', () => { }); it('should show error trying to delete a ticket with a refund', async() => { - await page.loginAndModule('production', 'ticket'); + await page.loginAndModule('salesPerson', 'ticket'); await page.accessToSearchResult('8'); await page.waitToClick(selectors.ticketDescriptor.moreMenu); await page.waitToClick(selectors.ticketDescriptor.moreMenuDeleteTicket); diff --git a/e2e/tests.js b/e2e/tests.js index 166d666e2..829056f4c 100644 --- a/e2e/tests.js +++ b/e2e/tests.js @@ -5,7 +5,6 @@ require('regenerator-runtime/runtime'); require('vn-loopback/server/boot/date')(); const getopts = require('getopts'); -const fs = require('fs'); const path = require('path'); const Myt = require('@verdnatura/myt/myt'); const Run = require('@verdnatura/myt/myt-run'); @@ -36,12 +35,22 @@ async function test() { const Jasmine = require('jasmine'); const jasmine = new Jasmine(); - const e2ePath = './e2e/paths'; - const file = '*[sS]pec.js'; - const specFiles = fs.readdirSync(e2ePath) - .sort() - .map(folder => `${e2ePath}/${folder}/${file}`) - .concat(`${e2ePath}/**/${file}`); + const specFiles = [ + `./e2e/paths/01*/*[sS]pec.js`, + `./e2e/paths/02*/*[sS]pec.js`, + `./e2e/paths/03*/*[sS]pec.js`, + `./e2e/paths/04*/*[sS]pec.js`, + `./e2e/paths/05*/*[sS]pec.js`, + `./e2e/paths/06*/*[sS]pec.js`, + `./e2e/paths/07*/*[sS]pec.js`, + `./e2e/paths/08*/*[sS]pec.js`, + `./e2e/paths/09*/*[sS]pec.js`, + `./e2e/paths/10*/*[sS]pec.js`, + `./e2e/paths/11*/*[sS]pec.js`, + `./e2e/paths/12*/*[sS]pec.js`, + `./e2e/paths/13*/*[sS]pec.js`, + `./e2e/paths/**/*[sS]pec.js` + ]; jasmine.loadConfig({ spec_dir: '.', -- 2.40.1 From ab9c11ef8448fc88f9d0f6407e8215e7088df689 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 31 May 2024 12:56:22 +0200 Subject: [PATCH 079/413] fix: refs #6889 modify fixtures --- db/dump/fixtures.before.sql | 2 +- e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 24225c99a..0b80df5d3 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1260,7 +1260,7 @@ INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`, `created`, `trainFk`) (2, 1106, 14, util.VN_CURDATE(), 1), (4, 49, 5, util.VN_CURDATE(), 1), (5, 18, 5, util.VN_CURDATE(), 1), - (6, 18, 5, util.VN_CURDATE(), 1); + (6, 49, 5, util.VN_CURDATE(), 1); INSERT INTO `vn`.`ticketCollection`(`ticketFk`, `collectionFk`, `level`) VALUES diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js index e0f32fc3a..4f54ad860 100644 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js @@ -225,7 +225,7 @@ describe('Ticket Edit sale path', () => { }); it('should show error trying to delete a ticket with a refund', async() => { - await page.loginAndModule('salesPerson', 'ticket'); + await page.loginAndModule('production', 'ticket'); await page.accessToSearchResult('8'); await page.waitToClick(selectors.ticketDescriptor.moreMenu); await page.waitToClick(selectors.ticketDescriptor.moreMenuDeleteTicket); -- 2.40.1 From ee09617b27c48c399b63517c70c9addf36021d73 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 31 May 2024 13:05:12 +0200 Subject: [PATCH 080/413] fix: refs #6889 e2e tests --- db/dump/fixtures.before.sql | 2 +- e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 0b80df5d3..24225c99a 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1260,7 +1260,7 @@ INSERT INTO `vn`.`collection`(`id`, `workerFk`, `stateFk`, `created`, `trainFk`) (2, 1106, 14, util.VN_CURDATE(), 1), (4, 49, 5, util.VN_CURDATE(), 1), (5, 18, 5, util.VN_CURDATE(), 1), - (6, 49, 5, util.VN_CURDATE(), 1); + (6, 18, 5, util.VN_CURDATE(), 1); INSERT INTO `vn`.`ticketCollection`(`ticketFk`, `collectionFk`, `level`) VALUES diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js index 4f54ad860..e0f32fc3a 100644 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js @@ -225,7 +225,7 @@ describe('Ticket Edit sale path', () => { }); it('should show error trying to delete a ticket with a refund', async() => { - await page.loginAndModule('production', 'ticket'); + await page.loginAndModule('salesPerson', 'ticket'); await page.accessToSearchResult('8'); await page.waitToClick(selectors.ticketDescriptor.moreMenu); await page.waitToClick(selectors.ticketDescriptor.moreMenuDeleteTicket); -- 2.40.1 From 2985e1c9e80dd7ff9b879199b2a9e38d3f13c7e1 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 31 May 2024 13:08:48 +0200 Subject: [PATCH 081/413] feat: roadMap refs #7195 --- back/models/warehouse.json | 33 +++++++++++++------ .../11081-wheatRaphis/00-firstScript.sql | 8 +++++ modules/route/back/models/roadmap.json | 12 +++---- 3 files changed, 37 insertions(+), 16 deletions(-) create mode 100644 db/versions/11081-wheatRaphis/00-firstScript.sql diff --git a/back/models/warehouse.json b/back/models/warehouse.json index dcbf7f2d2..69c74f153 100644 --- a/back/models/warehouse.json +++ b/back/models/warehouse.json @@ -9,21 +9,28 @@ }, "properties": { "id": { - "id": true, - "type": "number", - "forceId": false + "id": true, + "type": "number", + "forceId": false }, "name": { - "type": "string" + "type": "string" }, "code": { - "type": "string" + "type": "string" }, "isInventory": { - "type": "number" + "type": "number" }, - "isManaged":{ - "type": "boolean" + "isManaged": { + "type": "boolean" + } + }, + "relations": { + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" } }, "acls": [ @@ -34,5 +41,11 @@ "permission": "ALLOW" } ], - "scope" : {"where": {"isForTicket": {"neq": 0}}} -} + "scope": { + "where": { + "isForTicket": { + "neq": 0 + } + } + } +} \ No newline at end of file diff --git a/db/versions/11081-wheatRaphis/00-firstScript.sql b/db/versions/11081-wheatRaphis/00-firstScript.sql new file mode 100644 index 000000000..70bbaabdb --- /dev/null +++ b/db/versions/11081-wheatRaphis/00-firstScript.sql @@ -0,0 +1,8 @@ +-- Place your SQL code here + +USE vn; + +ALTER TABLE vn.roadmap ADD kmStart mediumint(9) DEFAULT NULL NULL; +ALTER TABLE vn.roadmap ADD kmEnd mediumint(9) DEFAULT NULL NULL; +ALTER TABLE vn.roadmap ADD started DATETIME NULL; +ALTER TABLE vn.roadmap ADD finished DATETIME NULL; diff --git a/modules/route/back/models/roadmap.json b/modules/route/back/models/roadmap.json index 01572d718..ac6cdae9f 100644 --- a/modules/route/back/models/roadmap.json +++ b/modules/route/back/models/roadmap.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "roadmap" + "table": "roadmap" } }, "properties": { @@ -43,8 +43,8 @@ "type": "string" } }, - "relations": { - "worker": { + "relations": { + "worker": { "type": "belongsTo", "model": "Worker", "foreignKey": "id" @@ -57,7 +57,7 @@ "roadmapStop": { "type": "hasMany", "model": "RoadmapStop", - "foreignKey": "roadmapFk" + "foreignKey": "roadMapFk" } - } -} + } +} \ No newline at end of file -- 2.40.1 From 836cfcbd07780f3f1267957c32046242838990e3 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 31 May 2024 13:58:26 +0200 Subject: [PATCH 082/413] refactor: refs #6889 sale tests e2e --- modules/ticket/back/models/specs/sale.spec.js | 309 +++++------------- 1 file changed, 87 insertions(+), 222 deletions(-) diff --git a/modules/ticket/back/models/specs/sale.spec.js b/modules/ticket/back/models/specs/sale.spec.js index d078dc8e2..d50c039db 100644 --- a/modules/ticket/back/models/specs/sale.spec.js +++ b/modules/ticket/back/models/specs/sale.spec.js @@ -1,42 +1,36 @@ /* eslint max-len: ["error", { "code": 150 }]*/ - -const models = require('vn-loopback/server/server').models; +const {models} = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); -describe('sale model ', () => { - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - function getActiveCtx(userId) { - return { - active: { - accessToken: {userId}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - } - }; +fdescribe('sale model ', () => { + const developerId = 9; + const buyerId = 35; + const employeeId = 1; + + const ctx = getCtx(developerId); + let tx; + let options; + + function getCtx(userId, active = false) { + const accessToken = {userId}; + const headers = {origin: 'localhost:5000'}; + if (!active) return {req: {accessToken, headers, __: () => {}}}; + return {active: {accessToken, http: {req: {headers}}}}; } + beforeEach(async() => { + tx = await models.Sale.beginTransaction({}); + options = {transaction: tx}; + }); + + afterEach(async() => await tx.rollback()); + describe('quantity field ', () => { it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { const saleId = 17; - const buyerId = 35; - const ctx = { - req: { - accessToken: {userId: buyerId}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - const tx = await models.Sale.beginTransaction({}); - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(buyerId)); + const ctx = getCtx(buyerId); + + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(buyerId, true)); spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY @@ -46,131 +40,74 @@ describe('sale model ', () => { return models.Ticket.rawSql(sqlStatement, params, options); }); - try { - const options = {transaction: tx}; + const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); - const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); + expect(isRoleAdvanced).toEqual(true); - expect(isRoleAdvanced).toEqual(true); + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + expect(originalLine.quantity).toEqual(30); - expect(originalLine.quantity).toEqual(30); + const newQuantity = originalLine.quantity + 1; + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - const newQuantity = originalLine.quantity + 1; - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(modifiedLine.quantity).toEqual(newQuantity); }); it('should update the quantity of a given sale current line', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(developerId, true)); - const tx = await models.Sale.beginTransaction({}); const saleId = 25; const newQuantity = 4; - try { - const options = {transaction: tx}; + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + expect(originalLine.quantity).toEqual(20); - expect(originalLine.quantity).toEqual(20); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(modifiedLine.quantity).toEqual(newQuantity); }); it('should throw an error if the quantity is negative and it is not a refund ticket', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); const saleId = 17; const newQuantity = -10; - const tx = await models.Sale.beginTransaction({}); - - let error; try { - const options = {transaction: tx}; - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); } catch (e) { - await tx.rollback(); - error = e; + expect(e).toEqual(new Error('You can only add negative amounts in refund tickets')); } - - expect(error).toEqual(new Error('You can only add negative amounts in refund tickets')); }); it('should update a negative quantity when is a ticket refund', async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(developerId, true)); - const tx = await models.Sale.beginTransaction({}); const saleId = 32; const newQuantity = -10; - try { - const options = {transaction: tx}; + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(modifiedLine.quantity).toEqual(newQuantity); }); it('should throw an error if the quantity is less than the minimum quantity of the item', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); - const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; const minQuantity = 30; const newQuantity = minQuantity - 1; - let error; try { - const options = {transaction: tx}; - const item = await models.Item.findById(itemId, null, options); await item.updateAttribute('minQuantity', minQuantity, options); spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { @@ -183,157 +120,90 @@ describe('sale model ', () => { }); await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); } catch (e) { - await tx.rollback(); - error = e; + expect(e).toEqual(new Error('The amount cannot be less than the minimum')); } - - expect(error).toEqual(new Error('The amount cannot be less than the minimum')); }); it('should change quantity if has minimum quantity and new quantity is equal than item available', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); - const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; const minQuantity = 30; const newQuantity = minQuantity - 1; - try { - const options = {transaction: tx}; + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT ${newQuantity} as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + }); + + describe('newPrice', () => { + it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); + + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; const item = await models.Item.findById(itemId, null, options); await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY - SELECT ${newQuantity} as available;`; + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 7.07 as price;`; params = null; } return models.Ticket.rawSql(sqlStatement, params, options); }); await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - 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 = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); - - const tx = await models.Sale.beginTransaction({}); - const itemId = 2; - const saleId = 17; - const minQuantity = 30; - const newQuantity = 31; - - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = ` - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 7.07 as price;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } }); it('should increase quantity when the new price is lower than the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); - const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; const minQuantity = 30; const newQuantity = 31; - try { - const options = {transaction: tx}; - - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { - if (sqlStatement.includes('catalog_calcFromItem')) { - sqlStatement = ` + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 1 as price;`; - params = null; - } - return models.Ticket.rawSql(sqlStatement, params, options); - }); + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); }); it('should throw error when increase quantity and the new price is higher than the previous one', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(employeeId, true)); - const tx = await models.Sale.beginTransaction({}); const itemId = 2; const saleId = 17; const minQuantity = 30; const newQuantity = 31; - let error; try { - const options = {transaction: tx}; - const item = await models.Item.findById(itemId, null, options); await item.updateAttribute('minQuantity', minQuantity, options); spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { @@ -347,14 +217,9 @@ describe('sale model ', () => { }); await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); } catch (e) { - await tx.rollback(); - error = e; + expect(e).toEqual(new Error('The price of the item changed')); } - - expect(error).toEqual(new Error('The price of the item changed')); }); }); }); -- 2.40.1 From dc8696b4224b973f3a31e9aa39cf679dac035c5a Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 31 May 2024 16:31:36 +0200 Subject: [PATCH 083/413] feat: refs #6889 add back tests --- db/dump/fixtures.before.sql | 21 ++- modules/ticket/back/models/specs/sale.spec.js | 170 ++++++++++++++---- 2 files changed, 149 insertions(+), 42 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 24225c99a..6818e7200 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -763,9 +763,10 @@ INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeF (31, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (32, 1, 8, 1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 2 DAY), 1103, 'Phone Box', 123, NULL, 0, 1, 5, 1, util.VN_CURDATE(), NULL, NULL), (33, 1, 7, 1, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL + 1 DAY), 1102, 'NY roofs', 122, NULL, 0, 3, 5, 1, util.VN_CURDATE(), NULL, NULL), - (34, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1103, 'BEJAR', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), - (35, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Somewhere in Philippines', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), - (36, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Ant-Man Adventure', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL); + (34, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1103, 'BEJAR', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (35, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Somewhere in Philippines', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (36, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Ant-Man Adventure', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), + (37, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1110, 'Deadpool swords', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL); INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) VALUES @@ -3834,3 +3835,17 @@ INSERT INTO vn.sectorCollectionSaleGroup SET id = 8, sectorCollectionFk = 2, saleGroupFk = 4; + +INSERT INTO vn.saleGroup (userFk, parkingFk, sectorFk, ticketFk) + VALUES + (1, 1, 1, 37); + +INSERT INTO vn.sectorCollection + SET id = 3, + userFk = 18, + sectorFk = 1; + +INSERT INTO vn.sectorCollectionSaleGroup + SET id = 9, + sectorCollectionFk = 3, + saleGroupFk = 6; \ No newline at end of file diff --git a/modules/ticket/back/models/specs/sale.spec.js b/modules/ticket/back/models/specs/sale.spec.js index d50c039db..1aa40802b 100644 --- a/modules/ticket/back/models/specs/sale.spec.js +++ b/modules/ticket/back/models/specs/sale.spec.js @@ -2,14 +2,24 @@ const {models} = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); -fdescribe('sale model ', () => { +describe('sale model ', () => { const developerId = 9; const buyerId = 35; const employeeId = 1; + const productionId = 49; + const salesPersonId = 18; + const reviewerId = 130; + + const barcode = '4444444444'; + const ticketCollectionProd = 34; + const ticketCollectionSalesPerson = 35; + const previaTicketSalesPerson = 36; + const previaTicketProd = 37; + const notEditableError = 'This ticket is not editable.'; const ctx = getCtx(developerId); let tx; - let options; + let opts; function getCtx(userId, active = false) { const accessToken = {userId}; @@ -20,7 +30,7 @@ fdescribe('sale model ', () => { beforeEach(async() => { tx = await models.Sale.beginTransaction({}); - options = {transaction: tx}; + opts = {transaction: tx}; }); afterEach(async() => await tx.rollback()); @@ -31,27 +41,27 @@ fdescribe('sale model ', () => { const ctx = getCtx(buyerId); spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(buyerId, true)); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT 100 as available;`; params = null; } - return models.Ticket.rawSql(sqlStatement, params, options); + return models.Ticket.rawSql(sqlStatement, params, opts); }); const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); expect(isRoleAdvanced).toEqual(true); - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); expect(originalLine.quantity).toEqual(30); const newQuantity = originalLine.quantity + 1; - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); expect(modifiedLine.quantity).toEqual(newQuantity); }); @@ -62,13 +72,13 @@ fdescribe('sale model ', () => { const saleId = 25; const newQuantity = 4; - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); expect(originalLine.quantity).toEqual(20); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); expect(modifiedLine.quantity).toEqual(newQuantity); }); @@ -80,7 +90,7 @@ fdescribe('sale model ', () => { const newQuantity = -10; try { - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); } catch (e) { expect(e).toEqual(new Error('You can only add negative amounts in refund tickets')); } @@ -92,9 +102,9 @@ fdescribe('sale model ', () => { const saleId = 32; const newQuantity = -10; - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, opts); expect(modifiedLine.quantity).toEqual(newQuantity); }); @@ -108,18 +118,18 @@ fdescribe('sale model ', () => { const newQuantity = minQuantity - 1; try { - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT 100 as available;`; params = null; } - return models.Ticket.rawSql(sqlStatement, params, options); + return models.Ticket.rawSql(sqlStatement, params, opts); }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); } catch (e) { expect(e).toEqual(new Error('The amount cannot be less than the minimum')); } @@ -133,19 +143,19 @@ fdescribe('sale model ', () => { const minQuantity = 30; const newQuantity = minQuantity - 1; - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available;`; params = null; } - return models.Ticket.rawSql(sqlStatement, params, options); + return models.Ticket.rawSql(sqlStatement, params, opts); }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); }); describe('newPrice', () => { @@ -157,19 +167,19 @@ fdescribe('sale model ', () => { const minQuantity = 30; const newQuantity = 31; - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = ` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 7.07 as price;`; params = null; } - return models.Ticket.rawSql(sqlStatement, params, options); + return models.Ticket.rawSql(sqlStatement, params, opts); }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); }); it('should increase quantity when the new price is lower than the previous one', async() => { @@ -180,19 +190,19 @@ fdescribe('sale model ', () => { const minQuantity = 30; const newQuantity = 31; - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = ` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 1 as price;`; params = null; } - return models.Ticket.rawSql(sqlStatement, params, options); + return models.Ticket.rawSql(sqlStatement, params, opts); }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); }); it('should throw error when increase quantity and the new price is higher than the previous one', async() => { @@ -204,23 +214,105 @@ fdescribe('sale model ', () => { const newQuantity = 31; try { - const item = await models.Item.findById(itemId, null, options); - await item.updateAttribute('minQuantity', minQuantity, options); - spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + const item = await models.Item.findById(itemId, null, opts); + await item.updateAttribute('minQuantity', minQuantity, opts); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, opts) => { if (sqlStatement.includes('catalog_calcFromItem')) { sqlStatement = ` CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 100000 as price;`; params = null; } - return models.Ticket.rawSql(sqlStatement, params, options); + return models.Ticket.rawSql(sqlStatement, params, opts); }); - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + await models.Sale.updateQuantity(ctx, saleId, newQuantity, opts); } catch (e) { expect(e).toEqual(new Error('The price of the item changed')); } }); }); }); + + describe('add a sale from a collection or previa ticket', () => { + it('if is allocated to them and alert level higher than 0 as Production role', async() => { + const ctx = getCtx(productionId); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(productionId, true)); + + const beforeSalesCollection = await models.Sale.count({ticketFk: ticketCollectionProd}, opts); + await models.Ticket.addSale(ctx, ticketCollectionProd, barcode, 20, opts); + const afterSalesCollection = await models.Sale.count({ticketFk: ticketCollectionProd}, opts); + + expect(afterSalesCollection).toEqual(beforeSalesCollection + 1); + + const beforeSalesPrevia = await models.Sale.count({ticketFk: previaTicketProd}, opts); + await models.Ticket.addSale(ctx, previaTicketProd, barcode, 20, opts); + const afterSalesPrevia = await models.Sale.count({ticketFk: previaTicketProd}, opts); + + expect(afterSalesPrevia).toEqual(beforeSalesPrevia + 1); + }); + + it('should throw an error if is not allocated to them and alert level higher than 0 as Production role', async() => { + const ctx = getCtx(productionId); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(productionId, true)); + + try { + await models.Ticket.addSale(ctx, ticketCollectionSalesPerson, barcode, 20, opts); + } catch ({message}) { + expect(message).toEqual(notEditableError); + } + + try { + await models.Ticket.addSale(ctx, previaTicketSalesPerson, barcode, 20, opts); + } catch ({message}) { + expect(message).toEqual(notEditableError); + } + }); + + it('if is allocated to them and alert level higher than 0 as salesPerson role', async() => { + const ctx = getCtx(salesPersonId); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(salesPersonId, true)); + + const beforeSalesCollection = await models.Sale.count({ticketFk: ticketCollectionSalesPerson}, opts); + await models.Ticket.addSale(ctx, ticketCollectionSalesPerson, barcode, 20, opts); + const afterSalesCollection = await models.Sale.count({ticketFk: ticketCollectionSalesPerson}, opts); + + expect(afterSalesCollection).toEqual(beforeSalesCollection + 1); + + const beforeSalesPrevia = await models.Sale.count({ticketFk: previaTicketSalesPerson}, opts); + await models.Ticket.addSale(ctx, previaTicketSalesPerson, barcode, 20, opts); + const afterSalesPrevia = await models.Sale.count({ticketFk: previaTicketSalesPerson}, opts); + + expect(afterSalesPrevia).toEqual(beforeSalesPrevia + 1); + }); + + it('should throw an error if is not allocated to them and alert level higher than 0 as salesPerson role', async() => { + const ctx = getCtx(salesPersonId); + + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(salesPersonId, true)); + + try { + await models.Ticket.addSale(ctx, ticketCollectionProd, barcode, 20, opts); + } catch ({message}) { + expect(message).toEqual(notEditableError); + } + }); + + it('if is a reviewer', async() => { + const ctx = getCtx(reviewerId); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getCtx(reviewerId, true)); + + const beforeSalesCollection = await models.Sale.count({ticketFk: ticketCollectionSalesPerson}, opts); + await models.Ticket.addSale(ctx, ticketCollectionSalesPerson, barcode, 20, opts); + const afterSalesCollection = await models.Sale.count({ticketFk: ticketCollectionSalesPerson}, opts); + + expect(afterSalesCollection).toEqual(beforeSalesCollection + 1); + + const beforeSalesPrevia = await models.Sale.count({ticketFk: previaTicketSalesPerson}, opts); + await models.Ticket.addSale(ctx, previaTicketSalesPerson, barcode, 20, opts); + const afterSalesPrevia = await models.Sale.count({ticketFk: previaTicketSalesPerson}, opts); + + expect(afterSalesPrevia).toEqual(beforeSalesPrevia + 1); + }); + }); }); -- 2.40.1 From ecd34e080d1e9b6549afc0b81dc285a595ef1ba7 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 3 Jun 2024 07:59:57 +0200 Subject: [PATCH 084/413] feat: refs #7039 deleteVirtualColumnCountry --- db/versions/11082-goldenCordyline/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11082-goldenCordyline/00-firstScript.sql diff --git a/db/versions/11082-goldenCordyline/00-firstScript.sql b/db/versions/11082-goldenCordyline/00-firstScript.sql new file mode 100644 index 000000000..71b98f4a9 --- /dev/null +++ b/db/versions/11082-goldenCordyline/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.country DROP COLUMN country; -- 2.40.1 From 790a637d4d9fd1e5ee0e7fcfe2ea2361d07ca9c5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 3 Jun 2024 09:25:48 +0200 Subject: [PATCH 085/413] feat: refs #6600 Add photoMotivation column to item table and create itemPhotoComment table --- .../00-addColumnPhotoMotivation.sql | 1 - .../11015-silverBamboo/00-photoMotivation.sql | 9 ++++++++ modules/item/back/model-config.json | 3 +++ modules/item/back/models/item.json | 6 +++++ .../item/back/models/itemPhotoComment.json | 22 +++++++++++++++++++ 5 files changed, 40 insertions(+), 1 deletion(-) delete mode 100644 db/versions/11015-silverBamboo/00-addColumnPhotoMotivation.sql create mode 100644 db/versions/11015-silverBamboo/00-photoMotivation.sql create mode 100644 modules/item/back/models/itemPhotoComment.json diff --git a/db/versions/11015-silverBamboo/00-addColumnPhotoMotivation.sql b/db/versions/11015-silverBamboo/00-addColumnPhotoMotivation.sql deleted file mode 100644 index 9f77dc88e..000000000 --- a/db/versions/11015-silverBamboo/00-addColumnPhotoMotivation.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE vn.item ADD COLUMN photoMotivation VARCHAR(255); \ No newline at end of file diff --git a/db/versions/11015-silverBamboo/00-photoMotivation.sql b/db/versions/11015-silverBamboo/00-photoMotivation.sql new file mode 100644 index 000000000..37cef29ab --- /dev/null +++ b/db/versions/11015-silverBamboo/00-photoMotivation.sql @@ -0,0 +1,9 @@ +ALTER TABLE vn.item ADD COLUMN photoMotivation VARCHAR(255); + +CREATE TABLE vn.itemPhotoComment ( + id int(11) NOT NULL AUTO_INCREMENT, + itemFk int(11) NOT NULL, + PRIMARY KEY (id), + FOREIGN KEY (itemFk) REFERENCES vn.item(id) ON UPDATE CASCADE ON DELETE CASCADE, + UNIQUE (itemFk) +); diff --git a/modules/item/back/model-config.json b/modules/item/back/model-config.json index 40d73f1a6..0cc100f98 100644 --- a/modules/item/back/model-config.json +++ b/modules/item/back/model-config.json @@ -35,6 +35,9 @@ "ItemPackingType": { "dataSource": "vn" }, + "ItemPhotoComment": { + "dataSource": "vn" + }, "ItemTag": { "dataSource": "vn" }, diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 7ec1daf7a..d7813a0f5 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -215,7 +215,13 @@ "type": "hasOne", "model": "Packaging", "foreignKey": "itemFk" + }, + "photoComment": { + "type": "hasOne", + "model": "itemPhotoComment", + "foreignKey": "itemFk" } + }, "scopes": { "withName": { diff --git a/modules/item/back/models/itemPhotoComment.json b/modules/item/back/models/itemPhotoComment.json new file mode 100644 index 000000000..4e2d14c5f --- /dev/null +++ b/modules/item/back/models/itemPhotoComment.json @@ -0,0 +1,22 @@ +{ + "name": "ItemPhotoComment", + "base": "VnModel", + "mixins": { + "Loggable": true + }, + "options": { + "mysql": { + "table": "itemPhotoComment" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Id" + }, + "itemFk": { + "type": "number" + } + } +} \ No newline at end of file -- 2.40.1 From 72630d613ba58d91292bc85ac289b735e9d17865 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 3 Jun 2024 09:32:03 +0200 Subject: [PATCH 086/413] fix: refs #6600 rollback --- .../11015-silverBamboo/00-photoMotivation.sql | 10 +-------- modules/item/back/model-config.json | 3 --- modules/item/back/models/item.json | 6 ----- .../item/back/models/itemPhotoComment.json | 22 ------------------- 4 files changed, 1 insertion(+), 40 deletions(-) delete mode 100644 modules/item/back/models/itemPhotoComment.json diff --git a/db/versions/11015-silverBamboo/00-photoMotivation.sql b/db/versions/11015-silverBamboo/00-photoMotivation.sql index 37cef29ab..366694e12 100644 --- a/db/versions/11015-silverBamboo/00-photoMotivation.sql +++ b/db/versions/11015-silverBamboo/00-photoMotivation.sql @@ -1,9 +1 @@ -ALTER TABLE vn.item ADD COLUMN photoMotivation VARCHAR(255); - -CREATE TABLE vn.itemPhotoComment ( - id int(11) NOT NULL AUTO_INCREMENT, - itemFk int(11) NOT NULL, - PRIMARY KEY (id), - FOREIGN KEY (itemFk) REFERENCES vn.item(id) ON UPDATE CASCADE ON DELETE CASCADE, - UNIQUE (itemFk) -); +ALTER TABLE vn.item ADD COLUMN photoMotivation VARCHAR(255); \ No newline at end of file diff --git a/modules/item/back/model-config.json b/modules/item/back/model-config.json index 0cc100f98..40d73f1a6 100644 --- a/modules/item/back/model-config.json +++ b/modules/item/back/model-config.json @@ -35,9 +35,6 @@ "ItemPackingType": { "dataSource": "vn" }, - "ItemPhotoComment": { - "dataSource": "vn" - }, "ItemTag": { "dataSource": "vn" }, diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index d7813a0f5..7ec1daf7a 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -215,13 +215,7 @@ "type": "hasOne", "model": "Packaging", "foreignKey": "itemFk" - }, - "photoComment": { - "type": "hasOne", - "model": "itemPhotoComment", - "foreignKey": "itemFk" } - }, "scopes": { "withName": { diff --git a/modules/item/back/models/itemPhotoComment.json b/modules/item/back/models/itemPhotoComment.json deleted file mode 100644 index 4e2d14c5f..000000000 --- a/modules/item/back/models/itemPhotoComment.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "name": "ItemPhotoComment", - "base": "VnModel", - "mixins": { - "Loggable": true - }, - "options": { - "mysql": { - "table": "itemPhotoComment" - } - }, - "properties": { - "id": { - "type": "number", - "id": true, - "description": "Id" - }, - "itemFk": { - "type": "number" - } - } -} \ No newline at end of file -- 2.40.1 From 340a8c119ecb48cd8eeac87f76975405a2b71e42 Mon Sep 17 00:00:00 2001 From: Jon Date: Mon, 3 Jun 2024 09:35:44 +0200 Subject: [PATCH 087/413] refactor: refs #6753 fix saveSign --- modules/ticket/back/methods/ticket/saveSign.js | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index 490b05320..b5c662089 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -140,14 +140,7 @@ module.exports = Self => { await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); - const deliveryState = await models.State.findOne({ - where: {code: 'DELIVERED'} - }, myOptions); - - await models.Ticket.state(ctx, { - ticketFk: ticketId, - stateFk: deliveryState.id - }, myOptions); + await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [params.ticketFk, params.code], myOptions); if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) { await models.Ticket.saveCmr(ctx, [ticketId], myOptions); -- 2.40.1 From 1382b24c1d4df1eac0feb9ac9239fa58a01e73b8 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 3 Jun 2024 09:38:35 +0200 Subject: [PATCH 088/413] refactor: refs #6600 add space --- modules/item/back/models/item.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 7ec1daf7a..10cff3e04 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -156,7 +156,7 @@ "type": "number", "description": "Min quantity" }, - "photoMotivation":{ + "photoMotivation": { "type": "string" } }, -- 2.40.1 From 7a92963886d65cdc95acc5a0fa2344ca600d3993 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 3 Jun 2024 10:21:25 +0200 Subject: [PATCH 089/413] fix acls --- db/versions/11083-purpleBamboo/00-firstScript.sql | 3 +++ modules/ticket/front/descriptor-menu/index.html | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) create mode 100644 db/versions/11083-purpleBamboo/00-firstScript.sql diff --git a/db/versions/11083-purpleBamboo/00-firstScript.sql b/db/versions/11083-purpleBamboo/00-firstScript.sql new file mode 100644 index 000000000..95e5c30a1 --- /dev/null +++ b/db/versions/11083-purpleBamboo/00-firstScript.sql @@ -0,0 +1,3 @@ + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Ticket','refund','WRITE','ALLOW','ROLE','logistic'); diff --git a/modules/ticket/front/descriptor-menu/index.html b/modules/ticket/front/descriptor-menu/index.html index cb7eeb8ee..3583b1202 100644 --- a/modules/ticket/front/descriptor-menu/index.html +++ b/modules/ticket/front/descriptor-menu/index.html @@ -152,7 +152,7 @@ -- 2.40.1 From b1a4b4202859a6f1fc1d5af068b9159eb7e09dac Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 3 Jun 2024 10:29:38 +0200 Subject: [PATCH 090/413] fix: refs #6404 change db language on local --- back/methods/mrw-config/createShipment.js | 2 +- db/dump/db.cnf | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index dd2ed883a..dd3d7fbd2 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -64,7 +64,7 @@ module.exports = Self => { JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk JOIN mrwService ms ON ms.agencyModeCodeFk = am.code - LEFT JOIN mrwServiceWeekday mw ON mw.weekdays = DATE_FORMAT(t.shipped, '%a') + LEFT JOIN mrwServiceWeekday mw ON mw.weekdays = DATE_FORMAT(t.shipped + INTERVAL 1 DAY, '%a', 'en_en') JOIN client c ON t.clientFk = c.id JOIN address a ON t.addressFk = a.id LEFT JOIN addressObservation oa ON oa.addressFk = a.id diff --git a/db/dump/db.cnf b/db/dump/db.cnf index 3dafaf514..f59c0eb4b 100644 --- a/db/dump/db.cnf +++ b/db/dump/db.cnf @@ -7,3 +7,6 @@ expire_logs_days = 2 binlog-ignore-db = tmp binlog-ignore-db = PERCONA_SCHEMA + +lc-messages = es_ES +lc_time_names = es_ES -- 2.40.1 From 39dcb7d6a83845229ffced6430ff48cfc0d4ab50 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 3 Jun 2024 10:30:20 +0200 Subject: [PATCH 091/413] fix: refs #6889 check if has collection or sectorCollection --- modules/ticket/back/methods/ticket/isEditableOrThrow.js | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/modules/ticket/back/methods/ticket/isEditableOrThrow.js b/modules/ticket/back/methods/ticket/isEditableOrThrow.js index 0adc9e0f9..555063093 100644 --- a/modules/ticket/back/methods/ticket/isEditableOrThrow.js +++ b/modules/ticket/back/methods/ticket/isEditableOrThrow.js @@ -27,17 +27,16 @@ module.exports = Self => { const ticketCollection = await models.TicketCollection.findOne({ include: {relation: 'collection'}, where: {ticketFk: id} }, myOptions); - let workerId = ticketCollection?.collection()?.workerFk; + let isOwner = ticketCollection?.collection()?.workerFk === ctx.req.accessToken.userId; - if (!workerId) { + if (!isOwner) { const saleGroup = await models.SaleGroup.findOne({fields: ['id'], where: {ticketFk: id}}, myOptions); const sectorCollectionSaleGroup = saleGroup && await models.SectorCollectionSaleGroup.findOne({ include: {relation: 'sectorCollection'}, where: {saleGroupFk: saleGroup.id} }, myOptions); - workerId = sectorCollectionSaleGroup?.sectorCollection()?.userFk; + isOwner = sectorCollectionSaleGroup?.sectorCollection()?.userFk === ctx.req.accessToken.userId; } - const isOwner = workerId === ctx.req.accessToken.userId; if (!ticket) throw new ForbiddenError(`The ticket doesn't exist.`); -- 2.40.1 From 349914743c6d417e2656e8fbce771c726ef2d330 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 3 Jun 2024 10:48:21 +0200 Subject: [PATCH 092/413] build: increase version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4df55c492..11911398d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.22.7", + "version": "24.22.8", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", -- 2.40.1 From 4703ebbdf3ce7922f16a52d852d90ee3abd94cbe Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 3 Jun 2024 11:38:09 +0200 Subject: [PATCH 093/413] refactor: refs #7519 Minor change --- db/dump/fixtures.before.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 6b8166caa..8bcedeb8d 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -831,9 +831,9 @@ INSERT INTO `vn`.`config`(`id`, `mdbServer`, `fakeEmail`, `defaultersMaxAmount`, INSERT INTO `vn`.`greugeType`(`id`, `name`, `code`) VALUES (1, 'Diff', 'diff'), - (2, 'Recobro', 'recovery'), - (3, 'Maná', 'mana'), - (4, 'Reclamación', 'claim'), + (2, 'Recovery', 'recovery'), + (3, 'Mana', 'mana'), + (4, 'Claim', 'claim'), (5, 'Heritage', 'heritage'), (6, 'Miscellaneous', 'miscellaneous'), (7, 'Freight Pickup', 'freightPickUp'); -- 2.40.1 From 8cef8eace7a92a8fb96fd124dd720fd07a455304 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 3 Jun 2024 11:41:09 +0200 Subject: [PATCH 094/413] refactor: refs #7519 Minor change --- db/routines/vn/procedures/claimRatio_add.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/claimRatio_add.sql b/db/routines/vn/procedures/claimRatio_add.sql index 36b9023da..2e999f738 100644 --- a/db/routines/vn/procedures/claimRatio_add.sql +++ b/db/routines/vn/procedures/claimRatio_add.sql @@ -79,7 +79,7 @@ BEGIN JOIN claimDestination cd ON cd.id = ce.claimDestinationFk JOIN claim c ON c.id = ce.claimFk JOIN claimState cs ON cs.id = c.claimStateFk - SET c.isChargedToMana = TRUE + SET ce.isGreuge = TRUE WHERE cd.description NOT IN ('Bueno', 'Corregido') AND NOT ce.isGreuge AND cs.code = 'resolved'; -- 2.40.1 From b8e95c02840358fb279008df97e0b4fed160bc0f Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 3 Jun 2024 11:46:52 +0200 Subject: [PATCH 095/413] refactor: refs #7519 Minor change --- db/routines/vn/procedures/claimRatio_add.sql | 6 ++---- db/versions/11028-silverCarnation/00-firstScript.sql | 10 ---------- 2 files changed, 2 insertions(+), 14 deletions(-) delete mode 100644 db/versions/11028-silverCarnation/00-firstScript.sql diff --git a/db/routines/vn/procedures/claimRatio_add.sql b/db/routines/vn/procedures/claimRatio_add.sql index 2e999f738..7def0837f 100644 --- a/db/routines/vn/procedures/claimRatio_add.sql +++ b/db/routines/vn/procedures/claimRatio_add.sql @@ -172,16 +172,14 @@ BEGIN GROUP BY clientFk ) sub ON sub.clientFk = cr.clientFk SET cr.priceIncreasing = GREATEST(0, ROUND(IFNULL(sub.greuge, 0) / - (IFNULL(cr.yearSale, 0) * vMonthToRefund / 12 ), 3)) - WHERE cr.dated = util.VN_CURDATE(); + (IFNULL(cr.yearSale, 0) * vMonthToRefund / 12 ), 3)); -- Protección neonatos UPDATE claimRatio cr JOIN firstTicketShipped fts ON fts.clientFk = cr.clientFk SET cr.priceIncreasing = 0, cr.claimingRate = 0 - WHERE fts.shipped > util.VN_CURDATE() - INTERVAL 1 MONTH - AND cr.dated = util.VN_CURDATE(); + WHERE fts.shipped > util.VN_CURDATE() - INTERVAL 1 MONTH; DROP TEMPORARY TABLE tTicketList; END$$ diff --git a/db/versions/11028-silverCarnation/00-firstScript.sql b/db/versions/11028-silverCarnation/00-firstScript.sql deleted file mode 100644 index 9d291f451..000000000 --- a/db/versions/11028-silverCarnation/00-firstScript.sql +++ /dev/null @@ -1,10 +0,0 @@ -UPDATE IGNORE bs.nightTask - SET `procedure` = 'claimRatio_add', - `schema` = 'vn' - WHERE `procedure` = 'claim_ratio_routine'; - -ALTER TABLE vn.claimRatio ADD dated DATE DEFAULT current_timestamp() NOT NULL; -ALTER TABLE vn.claimRatio CHANGE dated dated DATE DEFAULT current_timestamp() NOT NULL FIRST; -ALTER TABLE vn.claimRatio DROP FOREIGN KEY claimRatio_ibfk_1; -ALTER TABLE vn.claimRatio DROP PRIMARY KEY; -ALTER TABLE vn.claimRatio ADD CONSTRAINT claimRatio_pk PRIMARY KEY (dated,clientFk); -- 2.40.1 From 85d68890b898b7d3189f487ca2698dd4e9602b62 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 3 Jun 2024 12:11:26 +0200 Subject: [PATCH 096/413] refactor: refs #6701 New table clientRate --- db/routines/vn/triggers/claimRatio_afterInsert.sql | 9 +++++++++ db/versions/11084-whitePalmetto/00-firstScript.sql | 9 +++++++++ 2 files changed, 18 insertions(+) create mode 100644 db/routines/vn/triggers/claimRatio_afterInsert.sql create mode 100644 db/versions/11084-whitePalmetto/00-firstScript.sql diff --git a/db/routines/vn/triggers/claimRatio_afterInsert.sql b/db/routines/vn/triggers/claimRatio_afterInsert.sql new file mode 100644 index 000000000..080e636a2 --- /dev/null +++ b/db/routines/vn/triggers/claimRatio_afterInsert.sql @@ -0,0 +1,9 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`claimRatio_afterInsert` + AFTER INSERT ON `claimRatio` + FOR EACH ROW +BEGIN + INSERT INTO clientRate(clientFk, `value`) + VALUES(NEW.clientFk, NEW.priceIncreasing); +END$$ +DELIMITER ; diff --git a/db/versions/11084-whitePalmetto/00-firstScript.sql b/db/versions/11084-whitePalmetto/00-firstScript.sql new file mode 100644 index 000000000..c5f841ea4 --- /dev/null +++ b/db/versions/11084-whitePalmetto/00-firstScript.sql @@ -0,0 +1,9 @@ +CREATE TABLE `vn`.`clientRate` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL, + `dated` date NOT NULL DEFAULT current_timestamp(), + `value` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `clientRate_unique` (`clientFk`,`dated`), + CONSTRAINT `clientRate_client_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; \ No newline at end of file -- 2.40.1 From d3584691fa1f88e7addef2e15323f61914720be4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 3 Jun 2024 12:16:33 +0200 Subject: [PATCH 097/413] refactor: refs #6701 Minor change --- db/routines/vn/triggers/claimRatio_afterInsert.sql | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/triggers/claimRatio_afterInsert.sql b/db/routines/vn/triggers/claimRatio_afterInsert.sql index 080e636a2..ca618bb89 100644 --- a/db/routines/vn/triggers/claimRatio_afterInsert.sql +++ b/db/routines/vn/triggers/claimRatio_afterInsert.sql @@ -4,6 +4,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`claimRatio_afterInser FOR EACH ROW BEGIN INSERT INTO clientRate(clientFk, `value`) - VALUES(NEW.clientFk, NEW.priceIncreasing); + VALUES(NEW.clientFk, NEW.priceIncreasing) + ON DUPLICATE KEY UPDATE + `value` = VALUES(`value`); END$$ DELIMITER ; -- 2.40.1 From b9b0651069c1d58003dcfe4e45f738b73cd4ef6b Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 3 Jun 2024 12:38:57 +0200 Subject: [PATCH 098/413] fix: refs #6404 fix agency service selection --- back/methods/mrw-config/createShipment.js | 4 ++-- db/dump/db.cnf | 3 --- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index dd3d7fbd2..b5bea648d 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -57,14 +57,14 @@ module.exports = Self => { DATE_FORMAT(t.shipped, '%d/%m/%Y') created, t.shipped, CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference, - LPAD(IF(mw.params IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth,'0') serviceType, + LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth,'0') serviceType, IF(mw.weekdays, 'S', 'N') weekDays, oa.description deliveryObservation FROM expedition e JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk JOIN mrwService ms ON ms.agencyModeCodeFk = am.code - LEFT JOIN mrwServiceWeekday mw ON mw.weekdays = DATE_FORMAT(t.shipped + INTERVAL 1 DAY, '%a', 'en_en') + LEFT JOIN mrwServiceWeekday mw ON mw.weekdays | 1 << WEEKDAY(t.landed) JOIN client c ON t.clientFk = c.id JOIN address a ON t.addressFk = a.id LEFT JOIN addressObservation oa ON oa.addressFk = a.id diff --git a/db/dump/db.cnf b/db/dump/db.cnf index f59c0eb4b..3dafaf514 100644 --- a/db/dump/db.cnf +++ b/db/dump/db.cnf @@ -7,6 +7,3 @@ expire_logs_days = 2 binlog-ignore-db = tmp binlog-ignore-db = PERCONA_SCHEMA - -lc-messages = es_ES -lc_time_names = es_ES -- 2.40.1 From a73c98eebe6551c6a4b3752b05e9674ff36e2a23 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 3 Jun 2024 13:04:09 +0200 Subject: [PATCH 099/413] build(operator): console.log --- modules/worker/back/models/operator.js | 5 +++++ package.json | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index d46f3d934..8b562717e 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -17,6 +17,11 @@ module.exports = Self => { const {backupPrinterNotificationDelay} = await models.ProductionConfig.findOne(); if (backupPrinterNotificationDelay) { + console.log('operator delay:', + backupPrinterNotificationDelay, + Date.vnNow(), + new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000)) + ); const notifications = await models.NotificationQueue.find( {where: {created: {gte: new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000))}, notificationFk: notificationName, diff --git a/package.json b/package.json index fc8b709c9..b1ec06c69 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.24.1", + "version": "24.24.2", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", -- 2.40.1 From 35ae728e810006083dabef7c9c9e9cc8eee66845 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 3 Jun 2024 14:19:41 +0200 Subject: [PATCH 100/413] build(operator): console.log --- modules/worker/back/models/operator.js | 7 +++++++ package.json | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index d46f3d934..9652f3763 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -17,18 +17,25 @@ module.exports = Self => { const {backupPrinterNotificationDelay} = await models.ProductionConfig.findOne(); if (backupPrinterNotificationDelay) { + console.log('operator delay:', + backupPrinterNotificationDelay, + Date.vnNow(), + new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000)) + ); const notifications = await models.NotificationQueue.find( {where: {created: {gte: new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000))}, notificationFk: notificationName, status: 'sent' } }); + console.log('notifications: ', notifications); const criteria = {labelerId: labelerFk, sectorId: sectorFk}; const filteredNotifications = notifications.filter(notification => { const paramsObj = JSON.parse(notification.params); return Object.keys(criteria).every(key => criteria[key] === paramsObj?.[key]); }); + console.log('filteredNotifications: ', filteredNotifications); if (filteredNotifications.length >= 1) return; } diff --git a/package.json b/package.json index 4df55c492..11911398d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.22.7", + "version": "24.22.8", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", -- 2.40.1 From 9775e808a21ba6686b5fa8032daedef63f8e631a Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 3 Jun 2024 14:37:24 +0200 Subject: [PATCH 101/413] build(operator): remove console.log --- modules/worker/back/models/operator.js | 7 ------- 1 file changed, 7 deletions(-) diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index 9652f3763..d46f3d934 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -17,25 +17,18 @@ module.exports = Self => { const {backupPrinterNotificationDelay} = await models.ProductionConfig.findOne(); if (backupPrinterNotificationDelay) { - console.log('operator delay:', - backupPrinterNotificationDelay, - Date.vnNow(), - new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000)) - ); const notifications = await models.NotificationQueue.find( {where: {created: {gte: new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000))}, notificationFk: notificationName, status: 'sent' } }); - console.log('notifications: ', notifications); const criteria = {labelerId: labelerFk, sectorId: sectorFk}; const filteredNotifications = notifications.filter(notification => { const paramsObj = JSON.parse(notification.params); return Object.keys(criteria).every(key => criteria[key] === paramsObj?.[key]); }); - console.log('filteredNotifications: ', filteredNotifications); if (filteredNotifications.length >= 1) return; } -- 2.40.1 From c445bcb0baefe40da662d9412f1fe8ca93cde9ac Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 3 Jun 2024 14:39:32 +0200 Subject: [PATCH 102/413] build(operator): remove console.log --- modules/worker/back/models/operator.js | 5 ----- package.json | 2 +- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index 8b562717e..d46f3d934 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -17,11 +17,6 @@ module.exports = Self => { const {backupPrinterNotificationDelay} = await models.ProductionConfig.findOne(); if (backupPrinterNotificationDelay) { - console.log('operator delay:', - backupPrinterNotificationDelay, - Date.vnNow(), - new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000)) - ); const notifications = await models.NotificationQueue.find( {where: {created: {gte: new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000))}, notificationFk: notificationName, diff --git a/package.json b/package.json index b1ec06c69..be361ce7b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.24.2", + "version": "24.24.3", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", -- 2.40.1 From bbf027ede5dfc92039cd1bc9e928f46dfed7c9a3 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 3 Jun 2024 15:01:06 +0200 Subject: [PATCH 103/413] fix(operator): neq error --- modules/worker/back/models/operator.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/models/operator.js b/modules/worker/back/models/operator.js index d46f3d934..70e20af5b 100644 --- a/modules/worker/back/models/operator.js +++ b/modules/worker/back/models/operator.js @@ -20,7 +20,7 @@ module.exports = Self => { const notifications = await models.NotificationQueue.find( {where: {created: {gte: new Date(Date.vnNow() - (backupPrinterNotificationDelay * 1000))}, notificationFk: notificationName, - status: 'sent' + status: {neq: 'error'} } }); -- 2.40.1 From 3875bdb98db13d4006203d7b7caa546d2488ba7c Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 3 Jun 2024 15:01:25 +0200 Subject: [PATCH 104/413] build(operator): remove console.log --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 11911398d..e79f48b46 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.22.8", + "version": "24.22.9", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", -- 2.40.1 From 0b885ab773d665e1b8ff0cac7445a207d947f7e0 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 3 Jun 2024 15:06:29 +0200 Subject: [PATCH 105/413] build: increase version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e79f48b46..468d13156 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.22.9", + "version": "24.22.10", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", -- 2.40.1 From a13581ed9771469be59bbc0cec3ee8ecfe11b1f2 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 3 Jun 2024 16:31:38 +0200 Subject: [PATCH 106/413] feat: refs #6243 Add warehouseFk parameter --- modules/route/back/methods/route/cmrs.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/modules/route/back/methods/route/cmrs.js b/modules/route/back/methods/route/cmrs.js index 48d074624..0c25cbca5 100644 --- a/modules/route/back/methods/route/cmrs.js +++ b/modules/route/back/methods/route/cmrs.js @@ -47,6 +47,10 @@ module.exports = Self => { type: 'date', description: 'The to date filter', }, + { + arg: 'warehouseFk', + type: 'integer', + } ], returns: { type: ['object'], @@ -58,9 +62,10 @@ module.exports = Self => { } }); - Self.cmrs = async(filter, cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, shipped, options + Self.cmrs = async( + filter, cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, shipped, warehouseFk, options ) => { - const params = {cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, shipped}; + const params = {cmrFk, ticketFk, routeFk, country, clientFk, hasCmrDms, warehouseFk, shipped}; const conn = Self.dataSource.connector; let where = buildFilter(params, (param, value) => { @@ -89,7 +94,8 @@ module.exports = Self => { co.name country, t.clientFk, IF(sub.id, TRUE, FALSE) hasCmrDms, - DATE(t.shipped) shipped + DATE(t.shipped) shipped, + t.warehouseFk FROM ticket t JOIN ticketState ts ON ts.ticketFk = t.id JOIN state s ON s.id = ts.stateFk -- 2.40.1 From 5dd2e3b7d35baea70f944f96b6a3650db60c883f Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Mon, 3 Jun 2024 16:45:02 +0200 Subject: [PATCH 107/413] ci(Jenkinsfile): refs #7442 Tag image with build id --- Jenkinsfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 07f235cf7..d3dbfeddb 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -120,7 +120,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = packageJson.version + env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" } sh 'docker-compose build back' } @@ -158,7 +158,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = packageJson.version + env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" } sh 'gulp build' sh 'docker-compose build front' @@ -178,7 +178,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = packageJson.version + env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" } sh 'docker login --username $CREDENTIALS_USR --password $CREDENTIALS_PSW $REGISTRY' sh 'docker-compose push' @@ -212,7 +212,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = packageJson.version + env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" } withKubeConfig([ serverUrl: "$KUBERNETES_API", -- 2.40.1 From 882d5bf036c731a2b74888fcee367d8a554299ff Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 3 Jun 2024 18:39:11 +0200 Subject: [PATCH 108/413] feat: roadMap refs #7195 --- .../roadmapStop/getPalletMatchState.js | 63 +++++++++++++++++++ .../specs/getPalletMatchState.spec.js | 12 ++++ modules/route/back/models/roadmap.json | 12 ++++ modules/route/back/models/roadmapStop.js | 3 + 4 files changed, 90 insertions(+) create mode 100644 modules/route/back/methods/roadmapStop/getPalletMatchState.js create mode 100644 modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js create mode 100644 modules/route/back/models/roadmapStop.js diff --git a/modules/route/back/methods/roadmapStop/getPalletMatchState.js b/modules/route/back/methods/roadmapStop/getPalletMatchState.js new file mode 100644 index 000000000..efed64327 --- /dev/null +++ b/modules/route/back/methods/roadmapStop/getPalletMatchState.js @@ -0,0 +1,63 @@ +module.exports = Self => { + Self.remoteMethod('getPalletMatchState', { + description: 'Get pallet', + accessType: 'WRITE', + accepts: [{ + arg: 'roadMapStopFk', + type: 'number', + required: true, + description: 'The roadmapFk id' + }, + { + arg: 'state', + type: 'string', + required: true, + description: 'State code' + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/getPalletMatchState`, + verb: 'GET' + } + }); + + Self.getPalletMatchState = async(roadMapStopFk, state, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const result = await Self.rawSql(` + WITH tPallet AS( + SELECT ep.truckFk roadMapStop,ep.id pallet, e.id expedition, e.stateTypeFk + FROM vn.expeditionPallet ep + JOIN vn.expeditionScan es ON es.palletFk = ep.id + JOIN expedition e ON e.id = es.expeditionFk + WHERE ep.truckFk = ? + ),totalPalletExpedition AS( + SELECT t.*, COUNT(expedition) totalPalletExpedition + FROM tPallet t + GROUP BY expedition + ),totalPalletExpeditionCode AS( + SELECT t.*, COUNT(expedition) totalPalletExpeditionCode + FROM tPallet t + JOIN vn.expeditionStateType est ON est.id = t.stateTypeFk + WHERE code = ? + GROUP BY expedition + ) + SELECT t.roadMapStop, + t.pallet, + IF (tpe.totalPalletExpedition = tpec.totalPalletExpeditionCode, 'TRUE', 'FALSE') hasMatchStateCode + FROM tPallet t + LEFT JOIN totalPalletExpedition tpe ON tpe.expedition = t.expedition + LEFT JOIN totalPalletExpeditionCode tpec ON tpec.expedition = t.expedition + GROUP BY t.pallet;`, + [roadMapStopFk, state], + myOptions); + + return result; + }; +}; diff --git a/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js b/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js new file mode 100644 index 000000000..ac782561a --- /dev/null +++ b/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js @@ -0,0 +1,12 @@ + +const {models} = require('vn-loopback/server/server'); + +describe('roadMapStop getPalletMatchState()', () => { + fit('should return list of pallet with true or false if state is matched', async() => { + const roadmapStopFk = 1; + const state = 'ON DELIVERY'; + const result = await models.RoadmapStop.getPalletMatchState(roadmapStopFk, state); + + expect(result[0].hasMatchStateCode).toBe('TRUE'); + }); +}); diff --git a/modules/route/back/models/roadmap.json b/modules/route/back/models/roadmap.json index ac6cdae9f..5321af7c3 100644 --- a/modules/route/back/models/roadmap.json +++ b/modules/route/back/models/roadmap.json @@ -41,6 +41,18 @@ }, "driverName": { "type": "string" + }, + "kmStart": { + "type": "number" + }, + "kmEnd": { + "type": "number" + }, + "started": { + "type": "date" + }, + "finished": { + "type": "date" } }, "relations": { diff --git a/modules/route/back/models/roadmapStop.js b/modules/route/back/models/roadmapStop.js new file mode 100644 index 000000000..9e286776d --- /dev/null +++ b/modules/route/back/models/roadmapStop.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/roadmapStop/getPalletMatchState')(Self); +}; -- 2.40.1 From 9a7074d6003de431e992e8489181a79d0b515f7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 3 Jun 2024 20:16:27 +0200 Subject: [PATCH 109/413] hotfix: ledger_next transacciones refs #7523 --- .../vn/procedures/duaInvoiceInBooking.sql | 2 +- db/routines/vn/procedures/duaTaxBooking.sql | 2 +- .../vn/procedures/invoiceIn_booking.sql | 2 +- .../vn/procedures/invoiceOutBooking.sql | 2 +- .../vn/procedures/ledger_doCompensation.sql | 2 +- db/routines/vn/procedures/ledger_next.sql | 41 ++++--------------- db/routines/vn/procedures/ledger_nextTx.sql | 35 ++++++++++++++++ db/routines/vn/procedures/xdiario_new.sql | 2 +- .../vn/triggers/payment_beforeInsert.sql | 2 +- 9 files changed, 50 insertions(+), 40 deletions(-) create mode 100644 db/routines/vn/procedures/ledger_nextTx.sql diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index 035b4eab1..8b4df6a73 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -44,7 +44,7 @@ BEGIN JOIN dua d ON d.id = de.duaFk WHERE d.id = vDuaFk LIMIT 1; - CALL ledger_next(vFiscalYear, FALSE, vBookEntry); + CALL ledger_nextTx(vFiscalYear, vBookEntry); END IF; OPEN vInvoicesIn; diff --git a/db/routines/vn/procedures/duaTaxBooking.sql b/db/routines/vn/procedures/duaTaxBooking.sql index 8d8effe90..a50a10ca4 100644 --- a/db/routines/vn/procedures/duaTaxBooking.sql +++ b/db/routines/vn/procedures/duaTaxBooking.sql @@ -12,7 +12,7 @@ BEGIN WHERE id = vDuaFk; IF vBookNumber IS NULL OR NOT vBookNumber THEN - CALL ledger_next(YEAR(vBookDated), FALSE, vBookNumber); + CALL ledger_nextTx(YEAR(vBookDated), vBookNumber); END IF; -- Apunte de la aduana diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index cd311ba9d..ef124bb46 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -70,7 +70,7 @@ BEGIN SELECT YEAR(bookEntried) INTO vFiscalYear FROM tInvoiceIn LIMIT 1; IF vBookNumber IS NULL THEN - CALL ledger_next(vFiscalYear, FALSE, vBookNumber); + CALL ledger_nextTx(vFiscalYear, vBookNumber); END IF; -- Apunte del proveedor diff --git a/db/routines/vn/procedures/invoiceOutBooking.sql b/db/routines/vn/procedures/invoiceOutBooking.sql index b50b89eaf..9fc1c92b6 100644 --- a/db/routines/vn/procedures/invoiceOutBooking.sql +++ b/db/routines/vn/procedures/invoiceOutBooking.sql @@ -61,7 +61,7 @@ BEGIN WHERE io.id = vInvoice; SELECT YEAR(FECHA) INTO vFiscalYear FROM rs LIMIT 1; - CALL ledger_next(vFiscalYear, FALSE, vBookNumber); + CALL ledger_nextTx(vFiscalYear, vBookNumber); -- Linea del cliente INSERT INTO XDiario( ASIEN, diff --git a/db/routines/vn/procedures/ledger_doCompensation.sql b/db/routines/vn/procedures/ledger_doCompensation.sql index a9e4e4251..391575bac 100644 --- a/db/routines/vn/procedures/ledger_doCompensation.sql +++ b/db/routines/vn/procedures/ledger_doCompensation.sql @@ -28,7 +28,7 @@ BEGIN DECLARE vIsOriginalAClient BOOL; DECLARE vPayMethodCompensation INT; - CALL ledger_next(YEAR(vDated), FALSE, vNewBookEntry); + CALL ledger_nextTx(YEAR(vDated), vNewBookEntry); SELECT COUNT(id) INTO vIsOriginalAClient FROM client diff --git a/db/routines/vn/procedures/ledger_next.sql b/db/routines/vn/procedures/ledger_next.sql index 2d565ff99..0a390ab16 100644 --- a/db/routines/vn/procedures/ledger_next.sql +++ b/db/routines/vn/procedures/ledger_next.sql @@ -1,38 +1,21 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_next`( IN vFiscalYear INT, - IN vIsManageTransaction BOOLEAN, OUT vLastBookEntry INT ) +/** + * Devuelve un número de asiento válido, según el contador de asientos + * tabla vn.ledgerConfig, si no existe lo inicializa a 1 + * No inicia transacción, para transaccionar usar vn.ledger_nextTx + * + * @param vFiscalYear Id del año contable + * @return vLastBookEntry Id del asiento + */ BEGIN - DECLARE vHasStartTransaction BOOLEAN; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - - IF vHasStartTransaction THEN - ROLLBACK TO sp; - RESIGNAL; - ELSE - ROLLBACK; - CALL util.throw ('It has not been possible to generate a new ledger'); - END IF; - END; - IF vFiscalYear IS NULL THEN CALL util.throw('Fiscal year is required'); END IF; - IF NOT vIsManageTransaction THEN - SELECT @@in_transaction INTO vHasStartTransaction; - - IF NOT vHasStartTransaction THEN - START TRANSACTION; - ELSE - SAVEPOINT sp; - END IF; - END IF; - SELECT bookEntry + 1 INTO vLastBookEntry FROM ledgerCompany WHERE fiscalYear = vFiscalYear @@ -48,13 +31,5 @@ BEGIN UPDATE ledgerCompany SET bookEntry = vLastBookEntry WHERE fiscalYear = vFiscalYear; - - IF NOT vIsManageTransaction THEN - IF vHasStartTransaction THEN - RELEASE SAVEPOINT sp; - ELSE - COMMIT; - END IF; - END IF; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ledger_nextTx.sql b/db/routines/vn/procedures/ledger_nextTx.sql new file mode 100644 index 000000000..bdc0c3360 --- /dev/null +++ b/db/routines/vn/procedures/ledger_nextTx.sql @@ -0,0 +1,35 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_nextTx`( + IN vFiscalYear INT, + OUT vLastBookEntry INT +) +/** + * Devuelve un número de asiento válido, según el contador de asientos + * tabla vn.ledgerConfig, si no existe lo inicializa a 1 + * Lo hace transaccionando el proceso + * + * @param vFiscalYear Id del año contable + * @return vLastBookEntry Id del asiento + */ +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF vFiscalYear IS NULL THEN + CALL util.throw('Fiscal year is required'); + END IF; + + IF @@in_transaction THEN + CALL util.throw('This procedure should not be executed within a transaction'); + END IF; + + START TRANSACTION; + + CALL ledger_next(vFiscalYear, vLastBookEntry); + + COMMIT; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/xdiario_new.sql b/db/routines/vn/procedures/xdiario_new.sql index 83e1afa16..22a26184e 100644 --- a/db/routines/vn/procedures/xdiario_new.sql +++ b/db/routines/vn/procedures/xdiario_new.sql @@ -39,7 +39,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`xdiario_new`( */ BEGIN IF vBookNumber IS NULL THEN - CALL ledger_next(YEAR(vDated), FALSE, vBookNumber); + CALL ledger_nextTx(YEAR(vDated), vBookNumber); END IF; INSERT INTO XDiario diff --git a/db/routines/vn/triggers/payment_beforeInsert.sql b/db/routines/vn/triggers/payment_beforeInsert.sql index 337a54172..af369a69b 100644 --- a/db/routines/vn/triggers/payment_beforeInsert.sql +++ b/db/routines/vn/triggers/payment_beforeInsert.sql @@ -23,7 +23,7 @@ BEGIN FROM supplier WHERE id = NEW.supplierFk; - CALL ledger_next(YEAR(NEW.received), TRUE, vNewBookEntry); + CALL ledger_next(YEAR(NEW.received), vNewBookEntry); INSERT INTO XDiario ( ASIEN, -- 2.40.1 From 03201e1e2c0f2a8f53dd124de482c96b1cdfc7b9 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 4 Jun 2024 09:10:47 +0200 Subject: [PATCH 110/413] fix(ticket): throw error if id is null --- modules/ticket/front/card/index.js | 5 +++++ modules/ticket/front/locale/es.yml | 1 + 2 files changed, 6 insertions(+) diff --git a/modules/ticket/front/card/index.js b/modules/ticket/front/card/index.js index fa4ad4e39..34ab109c5 100644 --- a/modules/ticket/front/card/index.js +++ b/modules/ticket/front/card/index.js @@ -1,5 +1,6 @@ import ngModule from '../module'; import ModuleCard from 'salix/components/module-card'; +import UserError from 'core/lib/user-error'; class Controller extends ModuleCard { reload() { @@ -59,6 +60,10 @@ class Controller extends ModuleCard { ], }; + if (!this.$params.id) { + this.$state.go('ticket.index'); + throw new UserError(`You must select a ticket`); + } return this.$http.get(`Tickets/${this.$params.id}`, {filter}) .then(res => this.onData(res.data)); } diff --git a/modules/ticket/front/locale/es.yml b/modules/ticket/front/locale/es.yml index 748ba210f..2f448c034 100644 --- a/modules/ticket/front/locale/es.yml +++ b/modules/ticket/front/locale/es.yml @@ -64,6 +64,7 @@ You are going to delete this ticket: Vas a eliminar este ticket Ticket deleted. You can undo this action within the first hour: Ticket eliminado. Puedes deshacer esta acción durante la primera hora Search ticket by id or alias: Buscar tickets por identificador o alias ticket: ticket +You must select a ticket: Debes seleccionar un ticket #sections List: Listado -- 2.40.1 From a997ca0c58cd1fd383cdef456af5c469f2267eef Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 4 Jun 2024 10:08:17 +0200 Subject: [PATCH 111/413] build: add new version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index be361ce7b..8b8281e0d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.24.3", + "version": "24.26.0", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", -- 2.40.1 From da1b4649bb59414c6bde7be4511e73e6504754e6 Mon Sep 17 00:00:00 2001 From: jgallego Date: Tue, 4 Jun 2024 11:58:39 +0200 Subject: [PATCH 112/413] feat: refs #4560 sin expeditionTruck --- .../11063-purpleAnthurium/02-roadmapStopGrants.sql | 4 ++-- modules/route/back/model-config.json | 3 --- modules/route/back/models/expedition-truck.json | 9 --------- modules/route/back/models/roadmapStop.json | 2 +- modules/route/back/models/routesMonitor.json | 3 --- 5 files changed, 3 insertions(+), 18 deletions(-) delete mode 100644 modules/route/back/models/expedition-truck.json diff --git a/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql b/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql index d2c8354c0..bba1c019c 100644 --- a/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql +++ b/db/versions/11063-purpleAnthurium/02-roadmapStopGrants.sql @@ -3,8 +3,8 @@ DELETE FROM salix.ACL INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) VALUES - ('roadmapAddress', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), - ('roadmapAddress', '*', 'READ', 'ALLOW', 'ROLE', 'production'), + ('RoadmapAddress', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), + ('RoadmapAddress', '*', 'READ', 'ALLOW', 'ROLE', 'production'), ('Roadmap', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), ('Roadmap', '*', 'READ', 'ALLOW', 'ROLE', 'production'), ('RoadmapStop', '*', 'WRITE', 'ALLOW', 'ROLE', 'palletizerBoss'), diff --git a/modules/route/back/model-config.json b/modules/route/back/model-config.json index c315891fd..ccae87bd9 100644 --- a/modules/route/back/model-config.json +++ b/modules/route/back/model-config.json @@ -28,8 +28,5 @@ }, "RoutesMonitor": { "dataSource": "vn" - }, - "ExpeditionTruck": { - "dataSource": "vn" } } diff --git a/modules/route/back/models/expedition-truck.json b/modules/route/back/models/expedition-truck.json deleted file mode 100644 index fc9cd90f0..000000000 --- a/modules/route/back/models/expedition-truck.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "name": "ExpeditionTruck", - "base": "RoadmapStop", - "options": { - "mysql": { - "table": "expeditionTruck" - } - } -} diff --git a/modules/route/back/models/roadmapStop.json b/modules/route/back/models/roadmapStop.json index 527bbae98..74b02cd7a 100644 --- a/modules/route/back/models/roadmapStop.json +++ b/modules/route/back/models/roadmapStop.json @@ -36,7 +36,7 @@ }, "address": { "type": "belongsTo", - "model": "RoadmapAddress", + "model": "Address", "foreignKey": "addressFk" } } diff --git a/modules/route/back/models/routesMonitor.json b/modules/route/back/models/routesMonitor.json index 122026336..a14680b5c 100644 --- a/modules/route/back/models/routesMonitor.json +++ b/modules/route/back/models/routesMonitor.json @@ -48,9 +48,6 @@ "priority": { "type": "number" }, - "expeditionTruckFk": { - "type": "number" - }, "m3boxes": { "type": "number" }, -- 2.40.1 From 4089c7deb3fbdd424ff3f8d4624673aca3f638ea Mon Sep 17 00:00:00 2001 From: jgallego Date: Tue, 4 Jun 2024 12:23:28 +0200 Subject: [PATCH 113/413] feat: refs #4560 minorChanges --- db/dump/.dump/data.sql | 4 ++-- modules/route/back/locale/routesMonitor/en.yml | 1 - modules/route/back/locale/routesMonitor/es.yml | 1 - 3 files changed, 2 insertions(+), 4 deletions(-) diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index 8bc94e76f..3f2d8e22e 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -1772,8 +1772,8 @@ INSERT INTO `ACL` VALUES (688,'ClientSms','create','WRITE','ALLOW','ROLE','emplo INSERT INTO `ACL` VALUES (689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'); INSERT INTO `ACL` VALUES (691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'); -INSERT INTO `ACL` VALUES (692,'roadmapStop','*','*','ALLOW','ROLE','production'); -INSERT INTO `ACL` VALUES (693,'roadmapStop','*','*','ALLOW','ROLE','productionBoss'); +INSERT INTO `ACL` VALUES (692,'RoadmapStop','*','*','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (693,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'); diff --git a/modules/route/back/locale/routesMonitor/en.yml b/modules/route/back/locale/routesMonitor/en.yml index 0542ced54..c28c5cb4d 100644 --- a/modules/route/back/locale/routesMonitor/en.yml +++ b/modules/route/back/locale/routesMonitor/en.yml @@ -13,7 +13,6 @@ columns: m3: m3 priority: priority etd: etd - roadmapStopFk: truck m3boxes: m3 boxes bufferFk: buffer isPickingAllowed: is picking allowed diff --git a/modules/route/back/locale/routesMonitor/es.yml b/modules/route/back/locale/routesMonitor/es.yml index 1ea0532c6..a8e807626 100644 --- a/modules/route/back/locale/routesMonitor/es.yml +++ b/modules/route/back/locale/routesMonitor/es.yml @@ -13,7 +13,6 @@ columns: m3: m3 priority: prioridad etd: etd - roadmapStopFk: camión m3boxes: m3 cajas bufferFk: buffer isPickingAllowed: está permitido recoger -- 2.40.1 From 1927fbce4561f6c0e90a23398acb72d02cf80746 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 4 Jun 2024 15:39:02 +0200 Subject: [PATCH 114/413] hotfix: ledger_next transacciones refs #7523 --- back/tests.js | 4 ++-- db/.pullinfo.json | 2 +- db/routines/util/procedures/tx_commit.sql | 2 +- db/routines/util/procedures/tx_rollback.sql | 3 ++- db/routines/util/procedures/tx_start.sql | 2 +- db/routines/vn/procedures/ledger_nextTx.sql | 13 ++++--------- .../back/methods/travel/cloneWithEntries.js | 19 ++++++++++--------- .../travel/specs/cloneWithEntries.spec.js | 18 ++++++++---------- 8 files changed, 29 insertions(+), 34 deletions(-) diff --git a/back/tests.js b/back/tests.js index 50698eb92..fba3df4a8 100644 --- a/back/tests.js +++ b/back/tests.js @@ -98,8 +98,8 @@ async function test() { const SpecReporter = require('jasmine-spec-reporter').SpecReporter; runner.addReporter(new SpecReporter({ spec: { - displaySuccessful: opts.ci, - displayPending: opts.ci + displaySuccessful: true, + displayPending: true }, summary: { displayPending: false, diff --git a/db/.pullinfo.json b/db/.pullinfo.json index 0defed845..27d2c7535 100644 --- a/db/.pullinfo.json +++ b/db/.pullinfo.json @@ -9,7 +9,7 @@ }, "vn": { "view": { - "expeditionPallet_Print": "06613719475fcdba8309607c38cc78efc2e348cca7bc96b48dc3ae3c12426f54" + "expeditionPallet_Print": "ced2b84a114fcb99fce05f0c34f4fc03f3fa387bef92621be1bc306608a84345" } } } diff --git a/db/routines/util/procedures/tx_commit.sql b/db/routines/util/procedures/tx_commit.sql index fdf2f3ddb..8eb0c7426 100644 --- a/db/routines/util/procedures/tx_commit.sql +++ b/db/routines/util/procedures/tx_commit.sql @@ -6,7 +6,7 @@ BEGIN * * @param isTx es true si existe transacción asociada */ - IF isTx THEN + IF NOT isTx THEN COMMIT; END IF; END$$ diff --git a/db/routines/util/procedures/tx_rollback.sql b/db/routines/util/procedures/tx_rollback.sql index 96571af2c..e2c089f64 100644 --- a/db/routines/util/procedures/tx_rollback.sql +++ b/db/routines/util/procedures/tx_rollback.sql @@ -6,8 +6,9 @@ BEGIN * * @param isTx es true si existe transacción asociada */ - IF isTx THEN + IF NOT isTx THEN ROLLBACK; + RESIGNAL; END IF; END$$ DELIMITER ; diff --git a/db/routines/util/procedures/tx_start.sql b/db/routines/util/procedures/tx_start.sql index 9d9f16bb7..aa410ff72 100644 --- a/db/routines/util/procedures/tx_start.sql +++ b/db/routines/util/procedures/tx_start.sql @@ -6,7 +6,7 @@ BEGIN * * @param isTx es true si existe transacción asociada */ - IF isTx THEN + IF NOT isTx THEN START TRANSACTION; END IF; END$$ diff --git a/db/routines/vn/procedures/ledger_nextTx.sql b/db/routines/vn/procedures/ledger_nextTx.sql index bdc0c3360..abe96a21e 100644 --- a/db/routines/vn/procedures/ledger_nextTx.sql +++ b/db/routines/vn/procedures/ledger_nextTx.sql @@ -12,24 +12,19 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_nextTx`( * @return vLastBookEntry Id del asiento */ BEGIN + DECLARE vhasTx BOOL DEFAULT @@in_transaction; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - ROLLBACK; + CALL util.tx_rollback(vhasTx); RESIGNAL; END; IF vFiscalYear IS NULL THEN CALL util.throw('Fiscal year is required'); END IF; - - IF @@in_transaction THEN - CALL util.throw('This procedure should not be executed within a transaction'); - END IF; - - START TRANSACTION; + CALL util.tx_start(vhasTx); CALL ledger_next(vFiscalYear, vLastBookEntry); - - COMMIT; + CALL util.tx_commit(vhasTx); END$$ DELIMITER ; \ No newline at end of file diff --git a/modules/travel/back/methods/travel/cloneWithEntries.js b/modules/travel/back/methods/travel/cloneWithEntries.js index e5eb0b06c..12afad6e2 100644 --- a/modules/travel/back/methods/travel/cloneWithEntries.js +++ b/modules/travel/back/methods/travel/cloneWithEntries.js @@ -26,18 +26,17 @@ module.exports = Self => { Self.cloneWithEntries = async(ctx, id, options) => { const conn = Self.dataSource.connector; + let tx; const myOptions = {}; - let tx = options?.transaction; + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } try { - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - const travel = await Self.findById(id, { fields: [ 'id', @@ -89,6 +88,8 @@ module.exports = Self => { 'ref' ] }, myOptions); + + if (tx) await tx.commit(); return newTravel.id; } catch (e) { if (tx) await tx.rollback(); diff --git a/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js b/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js index 950da7bb1..8b3638db9 100644 --- a/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js +++ b/modules/travel/back/methods/travel/specs/cloneWithEntries.spec.js @@ -7,19 +7,22 @@ describe('Travel cloneWithEntries()', () => { const ctx = {req: {accessToken: {userId: currentUserId}}}; let newTravelId; it(`should clone the travel and the containing entries`, async() => { - const tx = await models.Travel.beginTransaction({ - }); + const tx = await models.Travel.beginTransaction({}); const warehouseThree = 3; const agencyModeOne = 1; + let travelRemoved; + try { const options = {transaction: tx}; + newTravelId = await models.Travel.cloneWithEntries(ctx, travelId, options); const travelEntries = await models.Entry.find({ where: { travelFk: newTravelId } }, options); - const newTravel = await models.Travel.findById(travelId); + const newTravel = await models.Travel.findById(travelId, null, options); + travelRemoved = await models.Travel.findById(newTravelId); expect(newTravelId).not.toEqual(travelId); expect(newTravel.ref).toEqual('fifth travel'); @@ -27,14 +30,9 @@ describe('Travel cloneWithEntries()', () => { expect(newTravel.warehouseOutFk).toEqual(warehouseThree); expect(newTravel.agencyModeFk).toEqual(agencyModeOne); expect(travelEntries.length).toBeGreaterThan(0); - await models.Entry.destroyAll({ - travelFk: newTravelId - }, options); - await models.Travel.destroyById(newTravelId, options); - await tx.rollback(); - const travelRemoved = await models.Travel.findById(newTravelId, options); - expect(travelRemoved).toBeNull(); + + await tx.rollback(); } catch (e) { if (tx) await tx.rollback(); throw e; -- 2.40.1 From c57f4db623c4bb8c7f667a7a1adc59d016028057 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 4 Jun 2024 15:41:53 +0200 Subject: [PATCH 115/413] hotfix: ledger_next transacciones refs #7523 --- db/.pullinfo.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/.pullinfo.json b/db/.pullinfo.json index 27d2c7535..0defed845 100644 --- a/db/.pullinfo.json +++ b/db/.pullinfo.json @@ -9,7 +9,7 @@ }, "vn": { "view": { - "expeditionPallet_Print": "ced2b84a114fcb99fce05f0c34f4fc03f3fa387bef92621be1bc306608a84345" + "expeditionPallet_Print": "06613719475fcdba8309607c38cc78efc2e348cca7bc96b48dc3ae3c12426f54" } } } -- 2.40.1 From e2adadb8da542398b7a3689906a4bacd4b52a7d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 4 Jun 2024 15:43:32 +0200 Subject: [PATCH 116/413] hotfix: ledger_next transacciones refs #7523 --- back/tests.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/back/tests.js b/back/tests.js index fba3df4a8..50698eb92 100644 --- a/back/tests.js +++ b/back/tests.js @@ -98,8 +98,8 @@ async function test() { const SpecReporter = require('jasmine-spec-reporter').SpecReporter; runner.addReporter(new SpecReporter({ spec: { - displaySuccessful: true, - displayPending: true + displaySuccessful: opts.ci, + displayPending: opts.ci }, summary: { displayPending: false, -- 2.40.1 From a9eb5f7d1ef9cc325b1ab10a23b93610dd35667b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 4 Jun 2024 15:45:54 +0200 Subject: [PATCH 117/413] hotfix: ledger_next transacciones refs #7523 --- db/routines/util/procedures/tx_rollback.sql | 1 - 1 file changed, 1 deletion(-) diff --git a/db/routines/util/procedures/tx_rollback.sql b/db/routines/util/procedures/tx_rollback.sql index e2c089f64..8909a96bb 100644 --- a/db/routines/util/procedures/tx_rollback.sql +++ b/db/routines/util/procedures/tx_rollback.sql @@ -8,7 +8,6 @@ BEGIN */ IF NOT isTx THEN ROLLBACK; - RESIGNAL; END IF; END$$ DELIMITER ; -- 2.40.1 From e4969f70616391f261cfced2107e05f78c530977 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 4 Jun 2024 16:43:09 +0200 Subject: [PATCH 118/413] Hotfix: ledger_next transacciones refs #7523 --- db/routines/util/procedures/tx_commit.sql | 6 +++--- db/routines/util/procedures/tx_rollback.sql | 4 ++-- db/routines/util/procedures/tx_start.sql | 6 +++--- db/routines/vn/procedures/ledger_nextTx.sql | 8 ++++---- db/routines/vn/procedures/travel_cloneWithEntries.sql | 10 +++++----- 5 files changed, 17 insertions(+), 17 deletions(-) diff --git a/db/routines/util/procedures/tx_commit.sql b/db/routines/util/procedures/tx_commit.sql index 8eb0c7426..35f96df8d 100644 --- a/db/routines/util/procedures/tx_commit.sql +++ b/db/routines/util/procedures/tx_commit.sql @@ -1,12 +1,12 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_commit`(isTx BOOL) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_commit`(vIsTx BOOL) BEGIN /** * Confirma los cambios asociados a una transacción. * - * @param isTx es true si existe transacción asociada + * @param vIsTx es true si existe transacción asociada */ - IF NOT isTx THEN + IF vIsTx THEN COMMIT; END IF; END$$ diff --git a/db/routines/util/procedures/tx_rollback.sql b/db/routines/util/procedures/tx_rollback.sql index 8909a96bb..82f771024 100644 --- a/db/routines/util/procedures/tx_rollback.sql +++ b/db/routines/util/procedures/tx_rollback.sql @@ -1,12 +1,12 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_rollback`(isTx BOOL) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_rollback`(vIsTx BOOL) BEGIN /** * Deshace los cambios asociados a una transacción. * * @param isTx es true si existe transacción asociada */ - IF NOT isTx THEN + IF vIsTx THEN ROLLBACK; END IF; END$$ diff --git a/db/routines/util/procedures/tx_start.sql b/db/routines/util/procedures/tx_start.sql index aa410ff72..41f8c94ee 100644 --- a/db/routines/util/procedures/tx_start.sql +++ b/db/routines/util/procedures/tx_start.sql @@ -1,12 +1,12 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_start`(isTx BOOL) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`tx_start`(vIsTx BOOL) BEGIN /** * Inicia una transacción. * - * @param isTx es true si existe transacción asociada + * @param vIsTx es true si existe transacción asociada */ - IF NOT isTx THEN + IF vIsTx THEN START TRANSACTION; END IF; END$$ diff --git a/db/routines/vn/procedures/ledger_nextTx.sql b/db/routines/vn/procedures/ledger_nextTx.sql index abe96a21e..98c157676 100644 --- a/db/routines/vn/procedures/ledger_nextTx.sql +++ b/db/routines/vn/procedures/ledger_nextTx.sql @@ -12,10 +12,10 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ledger_nextTx`( * @return vLastBookEntry Id del asiento */ BEGIN - DECLARE vhasTx BOOL DEFAULT @@in_transaction; + DECLARE vIsRequiredTx BOOL DEFAULT NOT @@in_transaction; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - CALL util.tx_rollback(vhasTx); + CALL util.tx_rollback(vIsRequiredTx); RESIGNAL; END; @@ -23,8 +23,8 @@ BEGIN CALL util.throw('Fiscal year is required'); END IF; - CALL util.tx_start(vhasTx); + CALL util.tx_start(vIsRequiredTx); CALL ledger_next(vFiscalYear, vLastBookEntry); - CALL util.tx_commit(vhasTx); + CALL util.tx_commit(vIsRequiredTx); END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/travel_cloneWithEntries.sql b/db/routines/vn/procedures/travel_cloneWithEntries.sql index 7cf9ee5ef..c51a68ecd 100644 --- a/db/routines/vn/procedures/travel_cloneWithEntries.sql +++ b/db/routines/vn/procedures/travel_cloneWithEntries.sql @@ -24,8 +24,8 @@ BEGIN DECLARE vEvaNotes VARCHAR(255); DECLARE vDone BOOL; DECLARE vAuxEntryFk INT; - DECLARE vTx BOOLEAN DEFAULT @@in_transaction; - DECLARE vRsEntry CURSOR FOR + DECLARE vDoTx BOOLEAN DEFAULT NOT @@in_transaction; + DECLARE vIsRequiredTx CURSOR FOR SELECT e.id FROM entry e JOIN travel t ON t.id = e.travelFk @@ -35,11 +35,11 @@ BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - CALL util.tx_rollback(vTx); + CALL util.tx_rollback(vIsRequiredTx); RESIGNAL; END; - CALL util.tx_start(vTx); + CALL util.tx_start(vIsRequiredTx); INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, cargoSupplierFk, kg,clonedFrom) SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3,cargoSupplierFk, kg,vTravelFk @@ -76,6 +76,6 @@ BEGIN SET @isModeInventory = FALSE; CLOSE vRsEntry; - CALL util.tx_commit(vTx); + CALL util.tx_commit(vIsRequiredTx); END$$ DELIMITER ; -- 2.40.1 From 35b4255505e0584525785774118282c5c12b7b68 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 4 Jun 2024 16:45:42 +0200 Subject: [PATCH 119/413] Hotfix: ledger_next transacciones refs #7523 --- db/routines/util/procedures/tx_rollback.sql | 2 +- db/routines/vn/procedures/travel_cloneWithEntries.sql | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/util/procedures/tx_rollback.sql b/db/routines/util/procedures/tx_rollback.sql index 82f771024..4b00f9ec1 100644 --- a/db/routines/util/procedures/tx_rollback.sql +++ b/db/routines/util/procedures/tx_rollback.sql @@ -4,7 +4,7 @@ BEGIN /** * Deshace los cambios asociados a una transacción. * - * @param isTx es true si existe transacción asociada + * @param vIsTx es true si existe transacción asociada */ IF vIsTx THEN ROLLBACK; diff --git a/db/routines/vn/procedures/travel_cloneWithEntries.sql b/db/routines/vn/procedures/travel_cloneWithEntries.sql index c51a68ecd..e2d086fc8 100644 --- a/db/routines/vn/procedures/travel_cloneWithEntries.sql +++ b/db/routines/vn/procedures/travel_cloneWithEntries.sql @@ -24,8 +24,8 @@ BEGIN DECLARE vEvaNotes VARCHAR(255); DECLARE vDone BOOL; DECLARE vAuxEntryFk INT; - DECLARE vDoTx BOOLEAN DEFAULT NOT @@in_transaction; - DECLARE vIsRequiredTx CURSOR FOR + DECLARE vIsRequiredTx BOOLEAN DEFAULT NOT @@in_transaction; + DECLARE vRsEntry CURSOR FOR SELECT e.id FROM entry e JOIN travel t ON t.id = e.travelFk -- 2.40.1 From 3b4cbe9e6c7b4a4860fbe6dd2b9703dcf8e9c6aa Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 4 Jun 2024 22:59:33 +0200 Subject: [PATCH 120/413] ci(Jenkinsfile): refs #7442 Remove ci from back tests --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index d3dbfeddb..7dccdd0b5 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -102,7 +102,7 @@ pipeline { NODE_ENV = '' } steps { - sh 'node back/tests.js --ci --junit --network jenkins' + sh 'node back/tests.js --junit' } post { always { -- 2.40.1 From 143930bc86478d6b74c346430788bd1cfa32bbec Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 5 Jun 2024 07:07:13 +0200 Subject: [PATCH 121/413] fix: warmFix setDeleted checks ticketRequest not answered --- modules/ticket/back/methods/ticket/setDeleted.js | 5 ++++- modules/ticket/back/methods/ticket/specs/setDeleted.spec.js | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index 9a9fd9056..2afdf44ac 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -71,7 +71,10 @@ module.exports = Self => { // Check for existing purchase requests const hasPurchaseRequests = await models.TicketRequest.count({ ticketFk: id, - isOk: true + or: [ + {isOk: true}, + {isOk: null} + ] }, myOptions); if (hasPurchaseRequests) diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js index 520a9e403..cb2a21d91 100644 --- a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js @@ -49,7 +49,7 @@ describe('ticket setDeleted()', () => { ctx.req.__ = value => { return value; }; - const ticketId = 23; + const ticketId = 24; const [sectorCollectionBefore] = await models.Ticket.rawSql( `SELECT COUNT(*) numberRows FROM vn.sectorCollection`, [], options); @@ -87,7 +87,7 @@ describe('ticket setDeleted()', () => { const [ticketCollectionOld] = await models.Ticket.rawSql( `SELECT COUNT(*) numberRows FROM vn.ticketCollection`, [], options); - const ticketId = 23; + const ticketId = 34; await models.Ticket.setDeleted(ctx, ticketId, options); -- 2.40.1 From 130d2b6b47d254f6294eaf694d3e90b592431c92 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 5 Jun 2024 08:05:46 +0200 Subject: [PATCH 122/413] feat: refs #7203 remove numbres alertLevel --- db/.pullinfo.json | 2 +- .../bi/procedures/claim_ratio_routine.sql | 3 +- .../hedera/procedures/item_getVisible.sql | 19 +++---- .../procedures/order_confirmWithUser.sql | 5 +- .../stock/procedures/log_refreshSale.sql | 3 +- db/routines/vn/procedures/invoiceOut_new.sql | 8 +-- .../vn/procedures/prepareTicketList.sql | 10 ++-- .../vn/procedures/productionControl.sql | 11 +++-- .../procedures/ticketGetVisibleAvailable.sql | 7 ++- .../vn/procedures/ticketMissed_List.sql | 49 ------------------- .../procedures/ticketParking_findSkipped.sql | 30 ++++++------ .../procedures/ticketStateToday_setState.sql | 27 +++++----- .../vn/procedures/ticketStateUpdate.sql | 26 ---------- .../vn/procedures/ticket_DelayTruck.sql | 3 +- .../vn/triggers/expedition_beforeInsert.sql | 14 +++--- 15 files changed, 80 insertions(+), 137 deletions(-) delete mode 100644 db/routines/vn/procedures/ticketMissed_List.sql delete mode 100644 db/routines/vn/procedures/ticketStateUpdate.sql diff --git a/db/.pullinfo.json b/db/.pullinfo.json index 0defed845..27d2c7535 100644 --- a/db/.pullinfo.json +++ b/db/.pullinfo.json @@ -9,7 +9,7 @@ }, "vn": { "view": { - "expeditionPallet_Print": "06613719475fcdba8309607c38cc78efc2e348cca7bc96b48dc3ae3c12426f54" + "expeditionPallet_Print": "ced2b84a114fcb99fce05f0c34f4fc03f3fa387bef92621be1bc306608a84345" } } } diff --git a/db/routines/bi/procedures/claim_ratio_routine.sql b/db/routines/bi/procedures/claim_ratio_routine.sql index 40b879483..3cf4bf8dc 100644 --- a/db/routines/bi/procedures/claim_ratio_routine.sql +++ b/db/routines/bi/procedures/claim_ratio_routine.sql @@ -65,11 +65,12 @@ BEGIN JOIN vn.ticketLastState ts ON ts.ticketFk = t.id JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk JOIN vn.state st ON st.id = tt.stateFk + JOIN vn.alertLevel al ON al.code = 'DELIVERED' WHERE sc.componentFk = 17 AND sc.isGreuge = 0 AND t.shipped >= '2016-10-01' AND t.shipped < util.VN_CURDATE() - AND st.alertLevel >= 3; + AND st.alertLevel >= al.id; DELETE g.* FROM vn.greuge g diff --git a/db/routines/hedera/procedures/item_getVisible.sql b/db/routines/hedera/procedures/item_getVisible.sql index 8e25eaab3..2f4ef32ab 100644 --- a/db/routines/hedera/procedures/item_getVisible.sql +++ b/db/routines/hedera/procedures/item_getVisible.sql @@ -5,7 +5,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`item_getVisible vType INT, vPrefix VARCHAR(255)) BEGIN - + /** * Gets visible items of the specified type at specified date. * @@ -14,7 +14,7 @@ BEGIN * @param vType The type id * @param vPrefix The article prefix to filter or %NULL for all * @return tmp.itemVisible Visible items - */ + */ DECLARE vPrefixLen SMALLINT; DECLARE vFilter VARCHAR(255) DEFAULT NULL; DECLARE vDateInv DATE DEFAULT vn.getInventoryDate(); @@ -23,13 +23,13 @@ BEGIN GET DIAGNOSTICS CONDITION 1 @message = MESSAGE_TEXT; CALL vn.mail_insert( - 'cau@verdnatura.es', - NULL, + 'cau@verdnatura.es', + NULL, CONCAT('hedera.item_getVisible error: ', @message), CONCAT( - 'warehouse: ', IFNULL(vWarehouse, ''), - ', Fecha:', IFNULL(vDate, ''), - ', tipo: ', IFNULL(vType,''), + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), ', prefijo: ', IFNULL(vPrefix,''))); RESIGNAL; END; @@ -74,9 +74,10 @@ BEGIN FROM vn.sale m JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id + JOIN vn.alertLevel al ON al.code = 'DELIVERED' WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() AND t.warehouseFk = vWarehouse - AND s.alertLevel = 3 + AND s.alertLevel = al.id ) t GROUP BY itemFk HAVING quantity > 0; @@ -108,7 +109,7 @@ BEGIN IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, CEIL(s.quantity / t.packing) etiquetas FROM vn.item i - JOIN `filter` f ON f.itemFk = i.id + JOIN `filter` f ON f.itemFk = i.id JOIN currentStock s ON s.itemFk = i.id LEFT JOIN tmp t ON t.itemFk = i.id LEFT JOIN vn.packaging p ON p.id = t.packagingFk diff --git a/db/routines/hedera/procedures/order_confirmWithUser.sql b/db/routines/hedera/procedures/order_confirmWithUser.sql index 0aeaaf65b..9c932aaa1 100644 --- a/db/routines/hedera/procedures/order_confirmWithUser.sql +++ b/db/routines/hedera/procedures/order_confirmWithUser.sql @@ -62,7 +62,7 @@ BEGIN END; -- Carga los datos del pedido - SELECT o.date_send, o.address_id, o.note, a.clientFk, + SELECT o.date_send, o.address_id, o.note, a.clientFk, o.company_id, o.agency_id, c.isTaxDataChecked INTO vDelivery, vAddress, vNotes, vClientId, vCompanyId, vAgencyModeId, vIsTaxDataChecked @@ -121,6 +121,7 @@ BEGIN ) SELECT t.id INTO vTicket FROM vn.ticket t + JOIN vn.alertLevel al ON al.code = 'FREE' LEFT JOIN tPrevia tp ON tp.ticketFk = t.id LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id JOIN hedera.`order` o @@ -131,7 +132,7 @@ BEGIN WHERE o.id = vSelf AND t.refFk IS NULL AND tp.ticketFk IS NULL - AND IFNULL(tls.alertLevel,0) = 0 + AND (tls.alertLevel IS NULL OR tls.alertLevel = al.id) LIMIT 1; -- Crea el ticket en el caso de no existir uno adecuado diff --git a/db/routines/stock/procedures/log_refreshSale.sql b/db/routines/stock/procedures/log_refreshSale.sql index 983616dca..3054f8ecb 100644 --- a/db/routines/stock/procedures/log_refreshSale.sql +++ b/db/routines/stock/procedures/log_refreshSale.sql @@ -16,12 +16,13 @@ BEGIN m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked + m.isPicked OR s.alertLevel > al.id isPicked FROM vn.sale m JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.item i ON i.id = m.itemFk JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.alertLevel al ON al.code = 'ON_PREPARATION' WHERE ( vTableId IS NULL OR (vTableName = 'ticket' AND t.id = vTableId) diff --git a/db/routines/vn/procedures/invoiceOut_new.sql b/db/routines/vn/procedures/invoiceOut_new.sql index 1b486df86..42c3f99da 100644 --- a/db/routines/vn/procedures/invoiceOut_new.sql +++ b/db/routines/vn/procedures/invoiceOut_new.sql @@ -80,8 +80,8 @@ BEGIN OR t.isDeleted OR c.hasToInvoice = FALSE OR itc.id IS NULL - OR a.id IS NULL - OR (vTaxArea = 'WORLD' + OR a.id IS NULL + OR (vTaxArea = 'WORLD' AND (a.customsAgentFk IS NULL OR a.incotermsFk IS NULL)); SELECT SUM(s.quantity * s.price * (100 - s.discount)/100) <> 0 @@ -153,7 +153,9 @@ BEGIN FROM tmp.ticketToInvoice ti LEFT JOIN ticketState ts ON ti.id = ts.ticketFk JOIN state s - WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id); + JOIN alertLevel al ON al.code = 'DELIVERED' + WHERE (ts.alertLevel IS NULL OR ts.alertLevel < al.id) + AND s.`code` = getAlert3State(ti.id); INSERT INTO ticketTracking(stateFk, ticketFk, userFk) SELECT * FROM tmp.updateInter; diff --git a/db/routines/vn/procedures/prepareTicketList.sql b/db/routines/vn/procedures/prepareTicketList.sql index f0f47f9a2..29c95cc9f 100644 --- a/db/routines/vn/procedures/prepareTicketList.sql +++ b/db/routines/vn/procedures/prepareTicketList.sql @@ -6,14 +6,16 @@ BEGIN (PRIMARY KEY (ticketFk)) ENGINE = MEMORY SELECT t.id ticketFk, t.clientFk - FROM vn.ticket t - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - JOIN vn.client c ON c.id = t.clientFk + FROM ticket t + JOIN alertLevel al ON al.code = 'DELIVERED' + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + JOIN client c ON c.id = t.clientFk + WHERE c.typeFk IN ('normal','handMaking','internalUse') AND ( t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate OR ( - ts.alertLevel < 3 + ts.alertLevel < al.id AND t.shipped >= vStartingDate AND t.shipped < util.VN_CURDATE() ) diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index b42645d1e..6505473fa 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`productionControl`( - vWarehouseFk INT, + vWarehouseFk INT, vScopeDays INT ) proc: BEGIN @@ -67,7 +67,7 @@ proc: BEGIN wk.code salesPersonCode, p.id provinceFk, tls.productionOrder, - IFNULL(tls.alertLevel, 0) alertLevel, + IFNULL(tls.alertLevel, al.id) alertLevel, t.isBoxed palletized, IF(rm.isPickingAllowed, rm.bufferFk, NULL) ubicacion, tlu.lastUpdated, @@ -81,6 +81,7 @@ proc: BEGIN rm.bufferFk FROM tmp.productionTicket tt JOIN ticket t ON tt.ticketFk = t.id + JOIN alertLevel al ON al.code = 'FREE' LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id LEFT JOIN `state` st ON st.id = tst.state LEFT JOIN client c ON c.id = t.clientFk @@ -101,7 +102,7 @@ proc: BEGIN LEFT JOIN parking pk ON pk.id = tp.parkingFk WHERE t.warehouseFk = vWarehouseFk AND dm.code IN ('AGENCY', 'DELIVERY', 'PICKUP'); - + UPDATE tmp.productionBuffer pb JOIN ( SELECT pb.ticketFk, GROUP_CONCAT(p.code) previaParking @@ -109,12 +110,12 @@ proc: BEGIN JOIN sale s ON s.ticketFk = pb.ticketFk JOIN saleGroupDetail sgd ON sgd.saleFk = s.id JOIN saleGroup sg ON sg.id = sgd.saleGroupFk - JOIN parking p ON p.id = sg.parkingFk + JOIN parking p ON p.id = sg.parkingFk GROUP BY pb.ticketFk ) t ON t.ticketFk = pb.ticketFk SET pb.previaParking = t.previaParking; - -- Problemas por ticket + -- Problemas por ticket ALTER TABLE tmp.productionBuffer CHANGE COLUMN `problem` `problem` VARCHAR(255), ADD COLUMN `collectionH` INT, diff --git a/db/routines/vn/procedures/ticketGetVisibleAvailable.sql b/db/routines/vn/procedures/ticketGetVisibleAvailable.sql index 07dfa69e5..3717d57e3 100644 --- a/db/routines/vn/procedures/ticketGetVisibleAvailable.sql +++ b/db/routines/vn/procedures/ticketGetVisibleAvailable.sql @@ -7,13 +7,16 @@ BEGIN DECLARE vShipped DATE; DECLARE vWarehouse TINYINT; DECLARE vAlertLevel INT; + DECLARE vAlertLevelFree INT; - SELECT t.warehouseFk, t.shipped, ts.alertLevel INTO vWarehouse, vShipped, vAlertLevel + SELECT t.warehouseFk, t.shipped, ts.alertLevel, al.id + INTO vWarehouse, vShipped, vAlertLevel, vAlertLevelFree FROM ticket t + JOIN alertLevel al ON al.code = 'FREE' LEFT JOIN ticketState ts ON ts.ticketFk = vTicket WHERE t.id = vTicket; - IF vAlertLevel IS NULL OR vAlertLevel = 0 THEN + IF vAlertLevel IS NULL OR vAlertLevel = vAlertLevelFree THEN IF vShipped >= util.VN_CURDATE() THEN CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped); END IF; diff --git a/db/routines/vn/procedures/ticketMissed_List.sql b/db/routines/vn/procedures/ticketMissed_List.sql deleted file mode 100644 index 6b0f66e6a..000000000 --- a/db/routines/vn/procedures/ticketMissed_List.sql +++ /dev/null @@ -1,49 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketMissed_List`(vTicketFk INT) -BEGIN - - DECLARE vParkingFk INT; - DECLARE vParked DATETIME; - DECLARE vLevel INT; - DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) - INTO vLevel, vCollectionFk - FROM vn.ticketCollection - WHERE ticketFk = vTicketFk - LIMIT 1; - - SELECT created, parkingFk - INTO vParked, vParkingFk - FROM vn.ticketParking - WHERE ticketFk = vTicketFk; - - SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia - FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND ( - ( - ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) - OR - ( tc.collectionFk = vCollectionFk AND LEFT(tc.level,1) < LEFT(vLevel,1) ) - ) - )) -- Etiquetas que no se han escaneado y ya estamos con una posterior - OR - (s.alertLevel > 1 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND tp.created < vParked - AND t.packages <=> 0); - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/ticketParking_findSkipped.sql b/db/routines/vn/procedures/ticketParking_findSkipped.sql index b00006ffe..ff72110c7 100644 --- a/db/routines/vn/procedures/ticketParking_findSkipped.sql +++ b/db/routines/vn/procedures/ticketParking_findSkipped.sql @@ -1,37 +1,37 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1)) BEGIN - + /** * Averigua los tickets que se han saltado por un error en el proceso encajado * @param vTicketFk Ticket * @param vItemPackingTypeFk Modo de encajado * @return un select con los tickets afectados - */ + */ DECLARE vParkingFk INT; DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vWagon INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) INTO vLevel, vWagon, vCollectionFk FROM vn.ticketCollection tc JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk WHERE ticketFk = vTicketFk ORDER BY c.id DESC LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk WHERE ticketFk = vTicketFk AND s.itemPackingTypeFk = vItemPackingTypeFk AND s.isPackagingArea ; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp JOIN vn.parking p ON p.id = tp.parkingFk @@ -42,23 +42,25 @@ BEGIN JOIN vn.zone z ON z.id = t.zoneFk JOIN vn.agencyMode am ON am.id = z.agencyModeFk JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 + JOIN vn.alertLevel alPacked ON alPacked.code = 'PACKED' + JOIN vn.alertLevel alOnPreparation ON alOnPreparation.code = 'ON_PREPARATION' + WHERE (s.alertLevel < alPacked.id AND tp.parkingFk = vParkingFk AND sc.isPackagingArea AND ( ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) OR - ( tc.collectionFk = vCollectionFk + ( tc.collectionFk = vCollectionFk AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) - OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) + OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) ) ) ) -- Etiquetas que no se han escaneado y ya estamos con una posterior OR - (s.alertLevel > 1 + (s.alertLevel > alOnPreparation.id AND tp.parkingFk = vParkingFk AND sc.isPackagingArea - AND tp.created < vParked + AND tp.created < vParked AND t.packages <=> 0); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticketStateToday_setState.sql b/db/routines/vn/procedures/ticketStateToday_setState.sql index 73a92bbb5..bd79043b4 100644 --- a/db/routines/vn/procedures/ticketStateToday_setState.sql +++ b/db/routines/vn/procedures/ticketStateToday_setState.sql @@ -1,26 +1,29 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* Modifica el estado de un ticket de hoy - * + * * @param vTicketFk el id del ticket * @param vStateCode estado a modificar del ticket - * + * */ - + DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM state s - JOIN ticketStateToday tst ON tst.state = s.id + DECLARE vAlertLevelPacked INT; + + SELECT s.alertLevel, al.id + INTO vAlertLevel, vAlertLevelPacked + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id + JOIN alertLevel al ON al.code = 'PACKED' WHERE tst.ticketFk = vTicketFk LIMIT 1; - - IF vAlertLevel < 2 THEN - + + IF vAlertLevel < vAlertLevelPacked THEN + CALL vn.ticket_setState(vTicketFk, vStateCode); - + END IF; END$$ diff --git a/db/routines/vn/procedures/ticketStateUpdate.sql b/db/routines/vn/procedures/ticketStateUpdate.sql deleted file mode 100644 index 4e19b7eb4..000000000 --- a/db/routines/vn/procedures/ticketStateUpdate.sql +++ /dev/null @@ -1,26 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) -BEGIN - - /* - * @deprecated:utilizar ticket_setState - */ - - DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM vn.state s - JOIN vn.ticketState ts ON ts.stateFk = s.id - WHERE ts.ticketFk = vTicketFk; - - IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN - - INSERT INTO ticketTracking(stateFk, ticketFk, userFk) - SELECT id, vTicketFk, account.myUser_getId() - FROM vn.state - WHERE `code` = vStateCode collate utf8_unicode_ci; - - END IF; - -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_DelayTruck.sql b/db/routines/vn/procedures/ticket_DelayTruck.sql index 7a3170d68..20601ee49 100644 --- a/db/routines/vn/procedures/ticket_DelayTruck.sql +++ b/db/routines/vn/procedures/ticket_DelayTruck.sql @@ -13,10 +13,11 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticket SELECT ticketFk FROM tmp.productionBuffer + JOIN alertLevel al ON al.code = 'FREE' WHERE shipped = util.VN_CURDATE() AND problem LIKE '%I:%' AND (HH <= vHour OR HH = vHour AND mm < vMinute) - AND alertLevel = 0; + AND alertLevel = al.id; OPEN cur1; diff --git a/db/routines/vn/triggers/expedition_beforeInsert.sql b/db/routines/vn/triggers/expedition_beforeInsert.sql index 685de72cb..2e5644a19 100644 --- a/db/routines/vn/triggers/expedition_beforeInsert.sql +++ b/db/routines/vn/triggers/expedition_beforeInsert.sql @@ -4,21 +4,21 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expedition_beforeInse FOR EACH ROW BEGIN DECLARE intcounter INT; - DECLARE vShipFk INT; SET NEW.editorFk = account.myUser_getId(); - IF NEW.freightItemFk IS NOT NULL THEN + IF NEW.freightItemFk IS NOT NULL THEN UPDATE ticket SET packages = IFNULL(packages, 0) + 1 WHERE id = NEW.ticketFk; - SELECT IFNULL(MAX(counter),0) +1 INTO intcounter - FROM expedition e - INNER JOIN ticket t1 ON e.ticketFk = t1.id + SELECT IFNULL(MAX(counter),0) + 1 INTO intcounter + FROM expedition e + JOIN alertLevel al ON al.code = 'DELIVERED' + JOIN ticket t1 ON e.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticketFk = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) AND t1.warehouseFk = t2.warehouseFk - WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < al.id AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; SET NEW.`counter` = intcounter; -- 2.40.1 From a0e79a778df7e229eaa17da67217c3ac86b20b38 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 5 Jun 2024 09:57:15 +0200 Subject: [PATCH 123/413] feat: refs #7496 deprecated ticket.isLabeled --- db/routines/vn2008/views/Saldos_Prevision.sql | 10 ---------- db/routines/vn2008/views/Tickets.sql | 1 - db/versions/11087-aquaDendro/00-firstScript.sql | 4 ++++ 3 files changed, 4 insertions(+), 11 deletions(-) delete mode 100644 db/routines/vn2008/views/Saldos_Prevision.sql create mode 100644 db/versions/11087-aquaDendro/00-firstScript.sql diff --git a/db/routines/vn2008/views/Saldos_Prevision.sql b/db/routines/vn2008/views/Saldos_Prevision.sql deleted file mode 100644 index f4749d30f..000000000 --- a/db/routines/vn2008/views/Saldos_Prevision.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE OR REPLACE DEFINER=`root`@`localhost` - SQL SECURITY DEFINER - VIEW `vn2008`.`Saldos_Prevision` -AS SELECT `fb`.`id` AS `Saldos_Prevision_id`, - `fb`.`description` AS `Descripcion`, - `fb`.`amount` AS `Importe`, - `fb`.`dated` AS `Fecha`, - `fb`.`accountingFk` AS `Id_Banco`, - `fb`.`companyFk` AS `empresa_id` -FROM `vn`.`forecastedBalance` `fb` \ No newline at end of file diff --git a/db/routines/vn2008/views/Tickets.sql b/db/routines/vn2008/views/Tickets.sql index c24b87b72..59dcb9100 100644 --- a/db/routines/vn2008/views/Tickets.sql +++ b/db/routines/vn2008/views/Tickets.sql @@ -21,7 +21,6 @@ AS SELECT `t`.`id` AS `Id_Ticket`, `t`.`workerFk` AS `Id_Trabajador`, `t`.`observations` AS `Observaciones`, `t`.`isSigned` AS `Firmado`, - `t`.`isLabeled` AS `Etiquetasemitidas`, `t`.`isPrinted` AS `PedidoImpreso`, `t`.`hour` AS `Hora`, `t`.`isBlocked` AS `blocked`, diff --git a/db/versions/11087-aquaDendro/00-firstScript.sql b/db/versions/11087-aquaDendro/00-firstScript.sql new file mode 100644 index 000000000..e53c231c3 --- /dev/null +++ b/db/versions/11087-aquaDendro/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.ticket MODIFY COLUMN IF EXISTS isLabeled__ tinyint(1) DEFAULT 0 NOT NULL COMMENT 'refs #7496 deprecated 2024-06-20'; + +ALTER TABLE IF EXISTS vn.forecastedBalance RENAME vn2008.call_information__; +ALTER TABLE IF EXISTS vn.forecastedBalance COMMENT='@deprecated 2024-05-21'; \ No newline at end of file -- 2.40.1 From f2b443021f067b3579c31f53efea981a11b67676 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 5 Jun 2024 10:03:37 +0200 Subject: [PATCH 124/413] hotfix: midnight deterministis refs #7213 --- db/routines/util/functions/midnight.sql | 2 +- db/routines/vn/functions/ticket_isTooLittle.sql | 2 +- db/routines/vn/procedures/ticket_setProblemRequest.sql | 2 +- .../vn/procedures/ticket_setProblemTooLittleItemCost.sql | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/db/routines/util/functions/midnight.sql b/db/routines/util/functions/midnight.sql index c80abdbb0..b37415682 100644 --- a/db/routines/util/functions/midnight.sql +++ b/db/routines/util/functions/midnight.sql @@ -1,7 +1,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `util`.`midnight`() RETURNS datetime - NOT DETERMINISTIC + DETERMINISTIC READS SQL DATA BEGIN diff --git a/db/routines/vn/functions/ticket_isTooLittle.sql b/db/routines/vn/functions/ticket_isTooLittle.sql index 2ce24f0fa..bcbf09035 100644 --- a/db/routines/vn/functions/ticket_isTooLittle.sql +++ b/db/routines/vn/functions/ticket_isTooLittle.sql @@ -14,7 +14,7 @@ BEGIN DECLARE vIsTooLittle TINYINT(1); SELECT (SUM(IFNULL(sv.litros, 0)) < vc.minTicketVolume - OR IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle + AND IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle FROM ticket t LEFT JOIN saleVolume sv ON sv.ticketFk = t.id JOIN volumeConfig vc diff --git a/db/routines/vn/procedures/ticket_setProblemRequest.sql b/db/routines/vn/procedures/ticket_setProblemRequest.sql index a5dc31472..19bba5b76 100644 --- a/db/routines/vn/procedures/ticket_setProblemRequest.sql +++ b/db/routines/vn/procedures/ticket_setProblemRequest.sql @@ -13,7 +13,7 @@ BEGIN ENGINE = MEMORY SELECT t.id ticketFk, FALSE hasProblem FROM ticket t - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (vSelf IS NULL OR t.id = vSelf); UPDATE tmp.ticket t diff --git a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql index 4403292fc..cd1f42783 100644 --- a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql +++ b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql @@ -16,7 +16,7 @@ BEGIN SELECT t.id ticketFk FROM vn.ticket t LEFT JOIN vn.sale s ON s.ticketFk = t.id - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (s.itemFk = vItemFk OR vItemFk IS NULL) GROUP BY t.id )SELECT ticketFk, ticket_isTooLittle(ticketFk) hasProblem -- 2.40.1 From 8b584a08dc73cba470f637c4d33c8d9d2775b73e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 5 Jun 2024 10:11:04 +0200 Subject: [PATCH 125/413] Hotfix: midnight deterministic refs #7213 --- .../vn/procedures/sale_setProblemComponentLackByComponent.sql | 2 +- db/routines/vn/procedures/ticket_setProblemFreeze.sql | 2 +- db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql index 62db0d9cf..b911327dd 100644 --- a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql +++ b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql @@ -18,7 +18,7 @@ BEGIN FROM ticket t JOIN sale s ON s.ticketFk = t.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (vComponentFk IS NULL OR sc.componentFk = vComponentFk) GROUP BY s.id) sub; diff --git a/db/routines/vn/procedures/ticket_setProblemFreeze.sql b/db/routines/vn/procedures/ticket_setProblemFreeze.sql index 2a5d67b0d..560bce612 100644 --- a/db/routines/vn/procedures/ticket_setProblemFreeze.sql +++ b/db/routines/vn/procedures/ticket_setProblemFreeze.sql @@ -13,7 +13,7 @@ BEGIN ENGINE = MEMORY SELECT t.id ticketFk, FALSE hasProblem FROM ticket t - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (vClientFk IS NULL OR t.clientFk = vClientFk); UPDATE tmp.ticket t diff --git a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql index b6c2d8533..00918426b 100644 --- a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql +++ b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql @@ -14,7 +14,7 @@ BEGIN SELECT t.id ticketFk, IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem FROM ticket t JOIN client c ON c.id = t.clientFk - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (c.id = vClientFk OR vClientFk IS NULL); CALL ticket_setProblem('isTaxDataChecked'); -- 2.40.1 From 82954ed299a6559fbfe3e4cb56da195bc15ab12d Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 5 Jun 2024 11:13:40 +0200 Subject: [PATCH 126/413] hotfix: ticket #176792 --- db/routines/vn/procedures/entry_updateComission.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/entry_updateComission.sql b/db/routines/vn/procedures/entry_updateComission.sql index ceed20d78..4ec4f6e58 100644 --- a/db/routines/vn/procedures/entry_updateComission.sql +++ b/db/routines/vn/procedures/entry_updateComission.sql @@ -23,7 +23,8 @@ BEGIN JOIN vn.travel t ON t.id = e.travelFk JOIN vn.warehouse w ON w.id = t.warehouseInFk WHERE t.shipped >= util.VN_CURDATE() - AND e.currencyFk = vCurrency; + AND e.currencyFk = vCurrency + AND NOT e.isBooked; SET vComission = currency_getCommission(vCurrency); -- 2.40.1 From 1fa22e71a980afc8f1ebed895b58e6ce4b22401f Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 5 Jun 2024 12:42:55 +0200 Subject: [PATCH 127/413] feat: refs #7203 nombre variables --- .../procedures/ticketParking_findSkipped.sql | 20 +++++++++---------- .../vn/triggers/expedition_beforeInsert.sql | 6 +++--- modules/account/back/models/role-inherit.json | 3 +++ 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/db/routines/vn/procedures/ticketParking_findSkipped.sql b/db/routines/vn/procedures/ticketParking_findSkipped.sql index ff72110c7..7713d5b50 100644 --- a/db/routines/vn/procedures/ticketParking_findSkipped.sql +++ b/db/routines/vn/procedures/ticketParking_findSkipped.sql @@ -34,16 +34,16 @@ BEGIN SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - JOIN vn.alertLevel alPacked ON alPacked.code = 'PACKED' - JOIN vn.alertLevel alOnPreparation ON alOnPreparation.code = 'ON_PREPARATION' + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk + JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.zone z ON z.id = t.zoneFk + JOIN vn.agencyMode am ON am.id = z.agencyModeFk + JOIN vn.state s ON s.id = tst.state + JOIN vn.alertLevel alPacked ON alPacked.code = 'PACKED' + JOIN vn.alertLevel alOnPreparation ON alOnPreparation.code = 'ON_PREPARATION' WHERE (s.alertLevel < alPacked.id AND tp.parkingFk = vParkingFk AND sc.isPackagingArea diff --git a/db/routines/vn/triggers/expedition_beforeInsert.sql b/db/routines/vn/triggers/expedition_beforeInsert.sql index 2e5644a19..e73ed9e49 100644 --- a/db/routines/vn/triggers/expedition_beforeInsert.sql +++ b/db/routines/vn/triggers/expedition_beforeInsert.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expedition_beforeInse BEFORE INSERT ON `expedition` FOR EACH ROW BEGIN - DECLARE intcounter INT; + DECLARE vMaxCounter INT; SET NEW.editorFk = account.myUser_getId(); @@ -11,7 +11,7 @@ BEGIN UPDATE ticket SET packages = IFNULL(packages, 0) + 1 WHERE id = NEW.ticketFk; - SELECT IFNULL(MAX(counter),0) + 1 INTO intcounter + SELECT IFNULL(MAX(counter),0) + 1 INTO vMaxCounter FROM expedition e JOIN alertLevel al ON al.code = 'DELIVERED' JOIN ticket t1 ON e.ticketFk = t1.id @@ -21,7 +21,7 @@ BEGIN WHERE t2.id = NEW.ticketFk AND ts.alertLevel < al.id AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; - SET NEW.`counter` = intcounter; + SET NEW.`counter` = vMaxCounter; END IF; END$$ DELIMITER ; diff --git a/modules/account/back/models/role-inherit.json b/modules/account/back/models/role-inherit.json index a89f47b77..30d526471 100644 --- a/modules/account/back/models/role-inherit.json +++ b/modules/account/back/models/role-inherit.json @@ -1,6 +1,9 @@ { "name": "RoleInherit", "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "account.roleInherit" -- 2.40.1 From a33f14ffa57e8416205eae2aefce2ef253983a18 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 5 Jun 2024 12:44:28 +0200 Subject: [PATCH 128/413] feat(transferInvoice): makePdf of refund --- loopback/locale/en.json | 4 +++- loopback/locale/es.json | 3 ++- loopback/locale/fr.json | 3 ++- loopback/locale/pt.json | 3 ++- .../back/methods/invoiceOut/transferInvoice.js | 10 ++++++++-- 5 files changed, 17 insertions(+), 6 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 48ec17535..a9b91a509 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -228,5 +228,7 @@ "InvoiceIn is already booked": "InvoiceIn is already booked", "This workCenter is already assigned to this agency": "This workCenter is already assigned to this agency", "You can only have one PDA": "You can only have one PDA", - "It has been invoiced but the PDF could not be generated": "It has been invoiced but the PDF could not be generated" + "It has been invoiced but the PDF could not be generated": "It has been invoiced but the PDF could not be generated", + "It has been invoiced but the PDF of refund not be generated": "It has been invoiced but the PDF of refund not be generated" + } diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 169b4bc01..80261afc7 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -360,5 +360,6 @@ "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)", "This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario", "You can only have one PDA": "Solo puedes tener un PDA", - "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF" + "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", + "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono" } diff --git a/loopback/locale/fr.json b/loopback/locale/fr.json index 2bb23c3fc..d3b69169f 100644 --- a/loopback/locale/fr.json +++ b/loopback/locale/fr.json @@ -357,5 +357,6 @@ "This workCenter is already assigned to this agency": "Ce centre de travail est déjà assigné à cette agence", "Select ticket or client": "Choisissez un ticket ou un client", "It was not able to create the invoice": "Il n'a pas été possible de créer la facture", - "It has been invoiced but the PDF could not be generated": "La facture a été émise mais le PDF n'a pas pu être généré" + "It has been invoiced but the PDF could not be generated": "La facture a été émise mais le PDF n'a pas pu être généré", + "It has been invoiced but the PDF of refund not be generated": "Il a été facturé mais le PDF de remboursement n'a pas été généré" } diff --git a/loopback/locale/pt.json b/loopback/locale/pt.json index 1ebcfa3de..9b5cf61bb 100644 --- a/loopback/locale/pt.json +++ b/loopback/locale/pt.json @@ -357,5 +357,6 @@ "This workCenter is already assigned to this agency": "Este centro de trabalho já está atribuído a esta agência", "Select ticket or client": "Selecione um ticket ou cliente", "It was not able to create the invoice": "Não foi possível criar a fatura", - "It has been invoiced but the PDF could not be generated": "Foi faturado, mas o PDF não pôde ser gerado" + "It has been invoiced but the PDF could not be generated": "Foi faturado, mas o PDF não pôde ser gerado", + "It has been invoiced but the PDF of refund not be generated": "Foi faturado mas não foi gerado o PDF do reembolso" } diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js index f5530d772..0c86e5810 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -66,6 +66,7 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; let invoiceId; + let refundId; let tx; if (typeof options == 'object') @@ -110,7 +111,7 @@ module.exports = Self => { }; const refundTicketIds = refundTickets.map(ticket => ticket.id); - await models.Ticket.invoiceTickets(ctx, refundTicketIds, invoiceCorrection, myOptions); + refundId = await models.Ticket.invoiceTickets(ctx, refundTicketIds, invoiceCorrection, myOptions); if (makeInvoice) invoiceId = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, null, myOptions); @@ -123,10 +124,15 @@ module.exports = Self => { if (tx && makeInvoice) { try { - await models.InvoiceOut.makePdfList(ctx, invoiceId, null); + await models.InvoiceOut.makePdfList(ctx, invoiceId); } catch (e) { throw new UserError('It has been invoiced but the PDF could not be generated'); } + try { + await models.InvoiceOut.makePdfList(ctx, refundId); + } catch (e) { + throw new UserError('It has been invoiced but the PDF of refund not be generated'); + } } return invoiceId; }; -- 2.40.1 From 40d40bd0bb9ef171ddd8b4e5633964938bbef314 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 5 Jun 2024 13:42:21 +0200 Subject: [PATCH 129/413] fix: refs #7335 hotFix cmrTicket --- db/routines/vn/triggers/ticket_afterUpdate.sql | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/triggers/ticket_afterUpdate.sql b/db/routines/vn/triggers/ticket_afterUpdate.sql index 0ce13e0a5..1c0a8be67 100644 --- a/db/routines/vn/triggers/ticket_afterUpdate.sql +++ b/db/routines/vn/triggers/ticket_afterUpdate.sql @@ -8,7 +8,9 @@ BEGIN SET hasNewRoute = TRUE WHERE ticketFk = NEW.id; - CALL ticket_doCmr(NEW.id); + IF NEW.cmrFk THEN + CALL ticket_doCmr(NEW.id); + END IF; END IF; END$$ DELIMITER ; -- 2.40.1 From 71ea1d1467af533a0d987908a90c88dfa79baa9d Mon Sep 17 00:00:00 2001 From: ivanm Date: Wed, 5 Jun 2024 14:53:59 +0200 Subject: [PATCH 130/413] refs #7536 modify itemShelvingRadar --- db/routines/vn/procedures/itemShelvingRadar.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/itemShelvingRadar.sql b/db/routines/vn/procedures/itemShelvingRadar.sql index 7875c4791..aa95d0503 100644 --- a/db/routines/vn/procedures/itemShelvingRadar.sql +++ b/db/routines/vn/procedures/itemShelvingRadar.sql @@ -49,7 +49,7 @@ BEGIN ish.isChecked, sub.isAllChecked FROM itemShelvingStock iss - JOIN itemShelving ish ON ish.shelvingFk = iss.shelvingFk + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk LEFT JOIN ( SELECT itemFk, IF( -- 2.40.1 From 638a5e9a1e6b379638ed55484b03b2e3f936d439 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 5 Jun 2024 15:44:11 +0200 Subject: [PATCH 131/413] Hotfix modificar entradas contabilizadas Ticket 191417 --- .../vn/procedures/entry_checkBooked.sql | 22 ----------------- .../vn/procedures/entry_isEditable.sql | 24 +++++++++++++++++++ db/routines/vn/triggers/buy_beforeDelete.sql | 2 +- db/routines/vn/triggers/buy_beforeInsert.sql | 2 +- db/routines/vn/triggers/buy_beforeUpdate.sql | 2 +- .../vn/triggers/entry_beforeDelete.sql | 2 +- .../vn/triggers/entry_beforeUpdate.sql | 2 +- 7 files changed, 29 insertions(+), 27 deletions(-) delete mode 100644 db/routines/vn/procedures/entry_checkBooked.sql create mode 100644 db/routines/vn/procedures/entry_isEditable.sql diff --git a/db/routines/vn/procedures/entry_checkBooked.sql b/db/routines/vn/procedures/entry_checkBooked.sql deleted file mode 100644 index 7ee1fee22..000000000 --- a/db/routines/vn/procedures/entry_checkBooked.sql +++ /dev/null @@ -1,22 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_checkBooked`( - vSelf INT -) -BEGIN -/** - * Comprueba si una entrada está contabilizada, - * y si lo está retorna un throw. - * - * @param vSelf Id de entrada - */ - DECLARE vIsBooked BOOL; - - SELECT isBooked INTO vIsBooked - FROM `entry` - WHERE id = vSelf; - - IF vIsBooked AND NOT IFNULL(@isModeInventory, FALSE) THEN - CALL util.throw('Entry is already booked'); - END IF; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql new file mode 100644 index 000000000..75e7d9c13 --- /dev/null +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -0,0 +1,24 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_isEditable`( + vSelf INT +) +BEGIN +/** + * Comprueba si una entrada se puede actualizar + * si no se puede retorna un throw. + * + * @param vSelf Id de entrada + */ + DECLARE vIsEditable BOOL; + + SELECT e.isBooked INTO vIsEditable + FROM `entry` e + JOIN entryType et ON et.code = e.typeFk + WHERE NOT et.isInformal + AND id = vSelf; + + IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN + CALL util.throw('Entry is not editable'); + END IF; +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/buy_beforeDelete.sql b/db/routines/vn/triggers/buy_beforeDelete.sql index 85f1cf298..1bbeadec9 100644 --- a/db/routines/vn/triggers/buy_beforeDelete.sql +++ b/db/routines/vn/triggers/buy_beforeDelete.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`buy_beforeDelete` BEFORE DELETE ON `buy` FOR EACH ROW BEGIN - CALL entry_checkBooked(OLD.entryFk); + CALL entry_isEditable(OLD.entryFk); IF OLD.printedStickers <> 0 THEN CALL util.throw("it is not possible to delete buys with printed labels "); END IF; diff --git a/db/routines/vn/triggers/buy_beforeInsert.sql b/db/routines/vn/triggers/buy_beforeInsert.sql index 6ad72916b..39befcaf1 100644 --- a/db/routines/vn/triggers/buy_beforeInsert.sql +++ b/db/routines/vn/triggers/buy_beforeInsert.sql @@ -15,7 +15,7 @@ trig: BEGIN LEAVE trig; END IF; - CALL entry_checkBooked(NEW.entryFk); + CALL entry_isEditable(NEW.entryFk); IF NEW.printedStickers <> 0 THEN CALL util.throw('it is not possible to create buy lines with printedstickers other than 0'); END IF; diff --git a/db/routines/vn/triggers/buy_beforeUpdate.sql b/db/routines/vn/triggers/buy_beforeUpdate.sql index 2403091c6..dc999095b 100644 --- a/db/routines/vn/triggers/buy_beforeUpdate.sql +++ b/db/routines/vn/triggers/buy_beforeUpdate.sql @@ -13,7 +13,7 @@ trig:BEGIN LEAVE trig; END IF; - CALL entry_checkBooked(OLD.entryFk); + CALL entry_isEditable(OLD.entryFk); SET NEW.editorFk = account.myUser_getId(); SELECT defaultEntry INTO vDefaultEntry diff --git a/db/routines/vn/triggers/entry_beforeDelete.sql b/db/routines/vn/triggers/entry_beforeDelete.sql index 1d2c84b9e..5b83daf77 100644 --- a/db/routines/vn/triggers/entry_beforeDelete.sql +++ b/db/routines/vn/triggers/entry_beforeDelete.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`entry_beforeDelete` BEFORE DELETE ON `entry` FOR EACH ROW BEGIN - CALL entry_checkBooked(OLD.id); + CALL entry_isEditable(OLD.id); DELETE FROM buy WHERE entryFk = OLD.id; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index d56db5e01..9b0d8f083 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -9,7 +9,7 @@ BEGIN DECLARE vTotalBuy INT; IF NEW.isBooked = OLD.isBooked THEN - CALL entry_checkBooked(OLD.id); + CALL entry_isEditable(OLD.id); ELSE IF NEW.isBooked THEN SELECT COUNT(*) INTO vTotalBuy -- 2.40.1 From b78ef97813591c29cdbf925da2370fb7312d2c9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 5 Jun 2024 15:50:16 +0200 Subject: [PATCH 132/413] Hotfix modificar entradas contabilizadas Ticket 191417 --- db/routines/vn/procedures/entry_isEditable.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql index 75e7d9c13..a05a1fd92 100644 --- a/db/routines/vn/procedures/entry_isEditable.sql +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -15,7 +15,7 @@ BEGIN FROM `entry` e JOIN entryType et ON et.code = e.typeFk WHERE NOT et.isInformal - AND id = vSelf; + AND e.id = vSelf; IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN CALL util.throw('Entry is not editable'); -- 2.40.1 From a79285cd3d2373f000a130760985c44ef376c7b0 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 5 Jun 2024 16:27:00 +0200 Subject: [PATCH 133/413] feat: refs #6273 register freelance --- modules/worker/back/methods/worker/new.js | 369 ++++++++---------- .../back/methods/worker/specs/new.spec.js | 235 ++++------- modules/worker/back/models/worker.json | 32 +- 3 files changed, 268 insertions(+), 368 deletions(-) diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 5316daf01..538d208fa 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -5,108 +5,80 @@ module.exports = Self => { Self.remoteMethodCtx('new', { description: 'Creates a new worker and returns the id', accessType: 'WRITE', - accepts: [ - { - arg: 'fi', - type: 'string', - description: `The worker fi`, - required: true, - }, - { - arg: 'name', - type: 'string', - description: `The user name`, - required: true, - }, - { - arg: 'firstName', - type: 'string', - description: `The worker firstname`, - required: true, - }, - { - arg: 'lastNames', - type: 'string', - description: `The worker lastnames`, - required: true, - }, - { - arg: 'email', - type: 'string', - description: `The worker email`, - required: true, - }, - { - arg: 'street', - type: 'string', - description: `The worker address`, - required: true, - }, - { - arg: 'city', - type: 'string', - description: `The worker city`, - required: true, - }, - { - arg: 'provinceFk', - type: 'number', - description: `The worker province`, - required: true, - }, - { - arg: 'companyFk', - type: 'number', - description: `The worker company`, - required: true, - }, - { - arg: 'postcode', - type: 'string', - description: `The worker postcode`, - required: true, - }, - { - arg: 'phone', - type: 'string', - description: `The worker phone`, - required: true, - }, - { - arg: 'code', - type: 'string', - description: `The worker code`, - required: true, - }, - { - arg: 'bossFk', - type: 'number', - description: `The worker boss`, - required: true, - }, - { - arg: 'birth', - type: 'date', - description: `The worker birth`, - required: true, - }, - { - arg: 'payMethodFk', - type: 'number', - description: `The client payMethod`, - required: true, - }, - { - arg: 'iban', - type: 'string', - description: `The client iban`, - }, - { - arg: 'bankEntityFk', - type: 'number', - description: `The client bank entity`, - } - ], + accepts: [{ + arg: 'fi', + type: 'string', + description: `The worker fi`, + }, { + arg: 'name', + type: 'string', + description: `The user name`, + }, { + arg: 'firstName', + type: 'string', + description: `The worker firstname`, + }, { + arg: 'lastNames', + type: 'string', + description: `The worker lastnames`, + }, { + arg: 'email', + type: 'string', + description: `The worker email`, + required: true, + }, { + arg: 'street', + type: 'string', + description: `The worker address`, + }, { + arg: 'city', + type: 'string', + description: `The worker city`, + }, { + arg: 'provinceFk', + type: 'number', + description: `The worker province`, + }, { + arg: 'companyFk', + type: 'number', + description: `The worker company`, + }, { + arg: 'postcode', + type: 'string', + description: `The worker postcode`, + }, { + arg: 'phone', + type: 'string', + description: `The worker phone`, + }, { + arg: 'code', + type: 'string', + description: `The worker code`, + }, { + arg: 'bossFk', + type: 'number', + description: `The worker boss`, + required: true, + }, { + arg: 'birth', + type: 'date', + description: `The worker birth`, + }, { + arg: 'payMethodFk', + type: 'number', + description: `The client payMethod`, + }, { + arg: 'iban', + type: 'string', + description: `The client iban`, + }, { + arg: 'bankEntityFk', + type: 'number', + description: `The client bank entity`, + }, { + arg: 'isFreelance', + type: 'boolean', + }], returns: { type: 'number', root: true, @@ -117,11 +89,30 @@ module.exports = Self => { }, }); - Self.new = async(ctx, options) => { + Self.new = async( + ctx, + fi, + name, + firstName, + lastNames, + email, + street, + city, + provinceFk, + companyFk, + postcode, + phone, + code, + bossFk, + birth, + payMethodFk, + iban, + bankEntityFk, + isFreelance, + options + ) => { const models = Self.app.models; const myOptions = {userId: ctx.req.accessToken.userId}; - const args = ctx.args; - let tx; if (typeof options == 'object') Object.assign(myOptions, options); @@ -132,131 +123,103 @@ module.exports = Self => { } let client; - + let user; try { - client = await models.Client.findOne( - { - where: {fi: args.fi}, - }, - myOptions - ); + client = await models.Client.findOne({where: {fi}}, myOptions); + const nickname = firstName.concat(' ', lastNames); + const {roleFk, businessTypeFk} = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']}); - if (!client) { - const nickname = args.firstName.concat(' ', args.lastNames); - const workerConfig = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']}); - const [randomPassword] = await models.Worker.rawSql( - 'SELECT account.passwordGenerate() as password;' - ); + if (!isFreelance) + if (!payMethodFk) throw new UserError('Payment method is required'); - const user = await models.VnUser.create( - { - name: args.name, - nickname, - password: randomPassword.password, - email: args.email, - roleFk: workerConfig.roleFk, - }, - myOptions - ); + if (isFreelance || !client) { + const [{password}] = await models.Worker.rawSql('SELECT account.passwordGenerate() as password;'); + user = await models.VnUser.create({ + name, + nickname, + password, + email, + roleFk, + }, myOptions); - await models.Account.create( - { - id: user.id, - }, - myOptions - ); + await models.Account.create({ + id: user.id + }, myOptions); + } else if (client) user = await models.VnUser.findById(client.id, null, myOptions); - const payMethod = await models.PayMethod.findById(args.payMethodFk, {fields: ['isIbanRequiredForClients']}); - if (payMethod.isIbanRequiredForClients && !args.iban) - throw new UserError(`That payment method requires an IBAN`); + if (!client && !isFreelance) { + const payMethod = await models.PayMethod.findById(payMethodFk, {fields: ['isIbanRequiredForClients']}); + if (payMethod.isIbanRequiredForClients && !iban) throw new UserError('That payment method requires an IBAN'); - await models.Worker.rawSql( - 'CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', + await models.Worker.rawSql('CALL vn.client_create(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [ - args.firstName, - args.lastNames, - args.fi, - args.street, - args.postcode, - args.city, - args.provinceFk, - args.companyFk, - args.phone, - args.email, + firstName, + lastNames, + fi, + street, + postcode, + city, + provinceFk, + companyFk, + phone, + email, user.id, ], - myOptions - ); + myOptions); - const address = await models.Address.create( - { - clientFk: user.id, - street: args.street, - city: args.city, - provinceFk: args.provinceFk, - postalCode: args.postcode, - mobile: args.phone, - nickname: nickname, - isDefaultAddress: true, - }, - myOptions - ); + const address = await models.Address.create({ + clientFk: user.id, + street: street, + city: city, + provinceFk: provinceFk, + postalCode: postcode, + mobile: phone, + nickname: nickname, + isDefaultAddress: true, + }, myOptions); - client = await models.Client.findById( - user.id, - {fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi']}, - myOptions - ); + client = await models.Client.findById(user.id, { + fields: ['id', 'name', 'socialName', 'street', 'city', 'iban', 'bankEntityFk', 'defaultAddressFk', 'businessTypeFk', 'fi'] + }, myOptions); - await client.updateAttributes( - { - payMethod: args.payMethod, - iban: args.iban, - bankEntityFk: args.bankEntityFk, - defaultAddressFk: address.id, - businessTypeFk: workerConfig.businessTypeFk, - }, - myOptions - ); + await client.updateAttributes({ + payMethod: payMethodFk, + iban, + bankEntityFk, + defaultAddressFk: address.id, + businessTypeFk, + }, myOptions); } - const user = await models.VnUser.findById(client.id, null, myOptions); - await user.updateAttribute('email', args.email, myOptions); + await user.updateAttribute('email', email, myOptions); await models.Worker.create({ - id: client.id, - code: args.code, - firstName: args.firstName, - lastName: args.lastNames, - bossFk: args.bossFk, - fi: args.fi, - birth: args.birth, + id: isFreelance ? user.id : client.id, + firstName, + lastName: lastNames, + code, + bossFk, + fi, + birth, }, myOptions); if (tx) await tx.commit(); - } catch (error) { + } catch (e) { if (tx) await tx.rollback(); - const code = error.code; - const message = error.sqlMessage; + const code = e.code; + const message = e.sqlMessage; - if (error.message && error.message.includes(`Email already exists`)) - throw new UserError(`This personal mail already exists`); + if (e.message && e.message.includes(`Email already exists`)) throw new UserError(`This personal mail already exists`); - if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) - throw new UserError(`This worker code already exists`); + if (code === 'ER_DUP_ENTRY' && message.includes(`CodigoTrabajador_UNIQUE`)) throw new UserError(`This worker code already exists`); - if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) - throw new UserError(`This worker already exists`); + if (code === 'ER_DUP_ENTRY' && message.includes(`PRIMARY`)) throw new UserError(`This worker already exists`); - throw error; + throw e; } - await models.VnUser.resetPassword({ - email: args.email, - emailTemplate: 'worker-welcome', - id: client.id - }); + await models.VnUser.resetPassword({email, emailTemplate: 'worker-welcome', id: client.id}); return {id: client.id}; }; diff --git a/modules/worker/back/methods/worker/specs/new.spec.js b/modules/worker/back/methods/worker/specs/new.spec.js index 66959e0a7..42c0d4124 100644 --- a/modules/worker/back/methods/worker/specs/new.spec.js +++ b/modules/worker/back/methods/worker/specs/new.spec.js @@ -1,189 +1,101 @@ -const models = require('vn-loopback/server/server').models; +const {models} = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); describe('Worker new', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); - + const developerId = 9; const employeeId = 1; - const defaultWorker = { - fi: '78457139E', - name: 'defaulterworker', - firstName: 'DEFAULT', - lastNames: 'WORKER', - email: 'defaultWorker@mydomain.com', - street: 'S/ DEFAULTWORKERSTREET', - city: 'defaultWorkerCity', - provinceFk: 1, - companyFk: 442, - postcode: '46680', - phone: '123456789', - code: 'DWW', - bossFk: 9, - birth: '2022-12-11T23:00:00.000Z', - payMethodFk: 1, - roleFk: 1 - }; + const bruceWayneId = 1101; + const accessToken = {accessToken: {userId: developerId}}; + const ctx = {req: accessToken}; + let tx; + let opts; - const req = {accessToken: {userId: 9}}; - - it('should return error if personal mail already exists', async() => { - const user = await models.VnUser.findById(employeeId, {fields: ['email']}); - - const tx = await models.Worker.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - const ctx = { - args: Object.assign({}, defaultWorker, {email: user.email}), - req - }; - - await models.Worker.new(ctx, options); - - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } - - expect(error.message).toEqual('This personal mail already exists'); + beforeAll(async() => { + const activeCtx = {accessToken, http: {req: {headers: {origin: 'http://localhost'}}}}; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: activeCtx}); }); - it('should return error if worker code already exists', async() => { - const worker = await models.Worker.findById(employeeId, {fields: ['code']}); - - const tx = await models.Worker.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - const ctx = { - args: Object.assign({}, defaultWorker, {code: worker.code}), - req - }; - - await models.Worker.new(ctx, options); - - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } - - expect(error.message).toEqual('This worker code already exists'); - }); - - it('should return error if worker already exists', async() => { - const worker = await models.Client.findById(employeeId, {fields: ['fi']}); - - const tx = await models.Worker.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - const ctx = { - args: Object.assign({}, defaultWorker, {fi: worker.fi}), - req - }; - await models.Worker.new(ctx, options); - - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } - - expect(error.message).toEqual('This worker already exists'); - }); - - it('should return error if payMethod require iban', async() => { - const payMethodIbanRequired = await models.PayMethod.findOne({ - where: { - isIbanRequiredForClients: true - }, - fields: ['id'] + describe('should return error', () => { + beforeEach(async() => { + tx = await models.Worker.beginTransaction({}); + opts = {transaction: tx}; }); - const tx = await models.Worker.beginTransaction({}); + afterEach(async() => await tx.rollback()); - let error; - try { - const options = {transaction: tx}; - const ctx = { - args: Object.assign({}, defaultWorker, {payMethodFk: payMethodIbanRequired.id}), - req - }; - await models.Worker.new(ctx, options); + it('if personal mail already exists', async() => { + const user = await models.VnUser.findById(employeeId, {fields: ['email']}); + try { + await createWorker(ctx, opts, {email: user.email}); + } catch (e) { + expect(e.message).toEqual('This personal mail already exists'); + } + }); - await tx.rollback(); - } catch (e) { - error = e; - await tx.rollback(); - } + it('if worker code already exists', async() => { + const worker = await models.Worker.findById(employeeId, {fields: ['code']}); + try { + await createWorker(ctx, opts, {code: worker.code}); + } catch (e) { + expect(e.message).toEqual('This worker code already exists'); + } + }); - expect(error.message).toEqual('That payment method requires an IBAN'); + it('if worker already exists', async() => { + const worker = await models.Client.findById(employeeId, {fields: ['fi']}); + try { + await createWorker(ctx, opts, {fi: worker.fi}); + } catch (e) { + expect(e.message).toEqual('This worker already exists'); + } + }); + + it('if payMethod require iban', async() => { + const payMethodIbanRequired = await models.PayMethod.findOne({ + fields: ['id'], where: {isIbanRequiredForClients: true} + }); + + try { + await createWorker(ctx, opts, {payMethodFk: payMethodIbanRequired.id}); + } catch (e) { + expect(e.message).toEqual('That payment method requires an IBAN'); + } + }); }); it('should create a new worker', async() => { let newWorker; try { - newWorker = await models.Worker.new({args: defaultWorker, req}); + newWorker = await createWorker(ctx); + + expect(newWorker.id).toBeDefined(); } finally { await removeWorker(newWorker.id); } - - expect(newWorker.id).toBeDefined(); }); it('should create a new client', async() => { let newWorker; - let client; try { - newWorker = await models.Worker.new({args: defaultWorker, req}); - client = await models.Client.findById(newWorker.id); + newWorker = await createWorker(ctx); + let client = await models.Client.findById(newWorker.id); + + expect(client).toBeDefined(); } finally { await removeWorker(newWorker.id); } - - expect(client).toBeDefined(); }); it('should create a new worker in client', async() => { - const bruceWayneId = 1101; const client = await models.Client.findById(bruceWayneId, {fields: ['fi', 'email']}); - - const newWorkerData = { - args: Object.assign( - {}, - defaultWorker, - { - fi: client.fi, - email: client.email - }), - req - }; let newWorker; try { - newWorker = await models.Worker.new(newWorkerData); + newWorker = await createWorker(ctx, undefined, {fi: client.fi, email: client.email}); + + expect(newWorker.id).toEqual(bruceWayneId); } finally { await models.Worker.destroyById(newWorker.id); } - - expect(newWorker.id).toEqual(bruceWayneId); }); }); @@ -194,3 +106,28 @@ async function removeWorker(id) { await models.Client.destroyById(id); await models.VnUser.destroyById(id); } + +async function createWorker(ctx, opts = undefined, params = {}) { + return models.Worker.new( + ctx, + params.fi ?? '78457139E', + params.name ?? 'defaulterworker', + params.firstName ?? 'DEFAULT', + params.lastNames ?? 'WORKER', + params.email ?? 'defaultWorker@mydomain.com', + params.street ?? 'S/ DEFAULTWORKERSTREET', + params.city ?? 'defaultWorkerCity', + params.provinceFk ?? 1, + params.companyFk ?? 442, + params.postcode ?? '46680', + params.phone ?? '123456789', + params.code ?? 'DWW', + params.bossFk ?? 9, + params.birth ?? '2022-12-11T23:00:00.000Z', + params.payMethodFk ?? 1, + undefined, + undefined, + params.isFreelance ?? false, + opts + ); +} diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 4e7617aab..4796c6373 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -25,43 +25,44 @@ "required": true }, "phone": { - "type" : "string" + "type": "string" }, "bossFk": { - "type" : "number" + "type": "number" }, "maritalStatus": { - "type" : "string" + "type": "string" }, "originCountryFk": { - "type" : "number" + "type": "number" }, "educationLevelFk": { - "type" : "number" + "type": "number" }, "SSN": { - "type" : "string" + "type": "string" }, "mobileExtension": { - "type" : "number" + "type": "number" }, "code": { - "type" : "string" + "type": "string", + "required": true }, "fi": { - "type" : "string" + "type": "string" }, "birth": { - "type" : "date" + "type": "date" }, "isF11Allowed": { - "type" : "boolean" + "type": "boolean" }, "sex": { - "type" : "string" + "type": "string" }, "isFreelance": { - "type" : "boolean" + "type": "boolean" }, "fiDueDate": { "type": "date" @@ -78,7 +79,6 @@ "isSsDiscounted": { "type": "boolean" } - }, "relations": { "user": { @@ -117,7 +117,7 @@ "foreignKey": "workerFk" } }, - "acls":[ + "acls": [ { "property": "__get__locker", "accessType": "READ", @@ -126,4 +126,4 @@ "principalId": "$owner" } ] -} +} \ No newline at end of file -- 2.40.1 From 8188bdbcb01821bcac21066eb6c0c825d2d1d6d8 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 5 Jun 2024 17:12:37 +0200 Subject: [PATCH 134/413] fix: refs #6273 use userId --- modules/worker/back/methods/worker/new.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 538d208fa..b9a303d18 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -194,7 +194,7 @@ module.exports = Self => { await user.updateAttribute('email', email, myOptions); await models.Worker.create({ - id: isFreelance ? user.id : client.id, + id: user.id, firstName, lastName: lastNames, code, @@ -219,8 +219,8 @@ module.exports = Self => { throw e; } - await models.VnUser.resetPassword({email, emailTemplate: 'worker-welcome', id: client.id}); + await models.VnUser.resetPassword({email, emailTemplate: 'worker-welcome', id: user.id}); - return {id: client.id}; + return {id: user.id}; }; }; -- 2.40.1 From 14afd8246ac82ad4629e0d5677a7c4fe9da8cc18 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 5 Jun 2024 17:38:48 +0200 Subject: [PATCH 135/413] feat: refs #6273 add back test --- modules/worker/back/methods/worker/new.js | 4 +++- .../worker/back/methods/worker/specs/new.spec.js | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index b9a303d18..4a4bd9449 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -134,12 +134,14 @@ module.exports = Self => { if (isFreelance || !client) { const [{password}] = await models.Worker.rawSql('SELECT account.passwordGenerate() as password;'); + const freelancer = isFreelance && await models.VnRole.findOne({fields: ['id'], where: {name: 'freelancer'}}); + user = await models.VnUser.create({ name, nickname, password, email, - roleFk, + roleFk: freelancer ? freelancer.id : roleFk, }, myOptions); await models.Account.create({ diff --git a/modules/worker/back/methods/worker/specs/new.spec.js b/modules/worker/back/methods/worker/specs/new.spec.js index 42c0d4124..5a5649154 100644 --- a/modules/worker/back/methods/worker/specs/new.spec.js +++ b/modules/worker/back/methods/worker/specs/new.spec.js @@ -97,6 +97,19 @@ describe('Worker new', () => { await models.Worker.destroyById(newWorker.id); } }); + + it('should create a new external worker', async() => { + let newWorker; + try { + newWorker = await createWorker(ctx, undefined, {isFreelance: true}); + const client = await models.Client.findById(newWorker.id); + + expect(newWorker.id).toBeDefined(); + expect(client).toBeNull(); + } finally { + await removeWorker(newWorker.id); + } + }); }); async function removeWorker(id) { -- 2.40.1 From 268c0a984cfb9e4b0b2b1b8c0db12fe51bd34480 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 6 Jun 2024 12:28:34 +0200 Subject: [PATCH 136/413] feat isScanned refs #7276 --- db/.pullinfo.json | 2 +- db/versions/11089-blueMastic/00-firstScript.sql | 5 +++++ .../expedition-state/addExpeditionState.js | 2 ++ .../ticket/back/models/expedition-state.json | 17 ++++++++++------- 4 files changed, 18 insertions(+), 8 deletions(-) create mode 100644 db/versions/11089-blueMastic/00-firstScript.sql diff --git a/db/.pullinfo.json b/db/.pullinfo.json index 0defed845..27d2c7535 100644 --- a/db/.pullinfo.json +++ b/db/.pullinfo.json @@ -9,7 +9,7 @@ }, "vn": { "view": { - "expeditionPallet_Print": "06613719475fcdba8309607c38cc78efc2e348cca7bc96b48dc3ae3c12426f54" + "expeditionPallet_Print": "ced2b84a114fcb99fce05f0c34f4fc03f3fa387bef92621be1bc306608a84345" } } } diff --git a/db/versions/11089-blueMastic/00-firstScript.sql b/db/versions/11089-blueMastic/00-firstScript.sql new file mode 100644 index 000000000..a3a92c56c --- /dev/null +++ b/db/versions/11089-blueMastic/00-firstScript.sql @@ -0,0 +1,5 @@ +-- Place your SQL code here + +USE vn; + +ALTER TABLE vn.expeditionState ADD isScanned tinyint(1) DEFAULT false NOT NULL; diff --git a/modules/ticket/back/methods/expedition-state/addExpeditionState.js b/modules/ticket/back/methods/expedition-state/addExpeditionState.js index 8eab1a838..80d74ee92 100644 --- a/modules/ticket/back/methods/expedition-state/addExpeditionState.js +++ b/modules/ticket/back/methods/expedition-state/addExpeditionState.js @@ -44,11 +44,13 @@ module.exports = Self => { const typeFk = expeditionStateType.id; expeditionId = expedition.expeditionFk; + const isScannedExpedition = expedition.isScanned ?? false; await models.ExpeditionState.create({ expeditionFk: expedition.expeditionFk, typeFk, userFk: userId, + isScanned: isScannedExpedition, }, myOptions); } diff --git a/modules/ticket/back/models/expedition-state.json b/modules/ticket/back/models/expedition-state.json index eda0f79fd..159a9275e 100644 --- a/modules/ticket/back/models/expedition-state.json +++ b/modules/ticket/back/models/expedition-state.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "expeditionState" + "table": "expeditionState" } }, "properties": { @@ -23,13 +23,16 @@ }, "userFk": { "type": "number" + }, + "isScanned": { + "type": "boolean" } }, "relations": { - "expeditionStateType": { - "type": "belongsTo", - "model": "ExpeditionStateType", - "foreignKey": "typeFk" - } + "expeditionStateType": { + "type": "belongsTo", + "model": "ExpeditionStateType", + "foreignKey": "typeFk" + } } -} +} \ No newline at end of file -- 2.40.1 From 5a6e2a2b31a1a5a52ac952787f0607d851ca94bc Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 6 Jun 2024 15:45:39 +0200 Subject: [PATCH 138/413] fix: refs #6942 create invoiceIn acl --- db/versions/11090-silverErica/00-firstScript.sql | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 db/versions/11090-silverErica/00-firstScript.sql diff --git a/db/versions/11090-silverErica/00-firstScript.sql b/db/versions/11090-silverErica/00-firstScript.sql new file mode 100644 index 000000000..ec4959de9 --- /dev/null +++ b/db/versions/11090-silverErica/00-firstScript.sql @@ -0,0 +1,3 @@ +INSERT INTO salix.ACL(model,property,accessType,permission,principalType,principalId) + VALUES('InvoiceIn', 'create', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceIn', 'create', 'WRITE', 'ALLOW', 'ROLE', 'buyer'); \ No newline at end of file -- 2.40.1 From 1912fdd45dcffd4553b0c48931c3ff3043b1057f Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 6 Jun 2024 17:26:23 +0200 Subject: [PATCH 139/413] refactor: refs #6286 replace name --- .../back/methods/worker-time-control/weeklyHourRecordEmail.js | 2 +- modules/worker/front/time-control/index.js | 2 +- modules/worker/front/time-control/index.spec.js | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js index 816a1d22b..53bc8d022 100644 --- a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js +++ b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js @@ -35,7 +35,7 @@ module.exports = Self => { root: true }, http: { - path: '/weekly-hour-hecord-email', + path: '/weekly-hour-record-email', verb: 'POST' } }); diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 9a4c4b559..7f7bad137 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -430,7 +430,7 @@ class Controller extends Section { workerId: this.worker.id, state: 'SENDED' }; - this.$http.post(`WorkerTimeControls/weekly-hour-hecord-email`, params) + this.$http.post(`WorkerTimeControls/weekly-hour-record-email`, params) .then(() => { this.getMailStates(this.date); this.vnApp.showSuccess(this.$t('Email sended')); diff --git a/modules/worker/front/time-control/index.spec.js b/modules/worker/front/time-control/index.spec.js index 8610da46e..42df4ba9b 100644 --- a/modules/worker/front/time-control/index.spec.js +++ b/modules/worker/front/time-control/index.spec.js @@ -260,7 +260,7 @@ describe('Component vnWorkerTimeControl', () => { controller.date = today; controller.weekNumber = 1; - $httpBackend.expect('POST', 'WorkerTimeControls/weekly-hour-hecord-email').respond(); + $httpBackend.expect('POST', 'WorkerTimeControls/weekly-hour-record-email').respond(); controller.resendEmail(); $httpBackend.flush(); -- 2.40.1 From f7c2fd824f529fe40826c249894fe7f515e8ddf7 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 7 Jun 2024 07:05:22 +0200 Subject: [PATCH 140/413] feat: refs #7496 changesRequested --- db/versions/11087-aquaDendro/00-firstScript.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/versions/11087-aquaDendro/00-firstScript.sql b/db/versions/11087-aquaDendro/00-firstScript.sql index e53c231c3..3490919a9 100644 --- a/db/versions/11087-aquaDendro/00-firstScript.sql +++ b/db/versions/11087-aquaDendro/00-firstScript.sql @@ -1,4 +1,4 @@ ALTER TABLE vn.ticket MODIFY COLUMN IF EXISTS isLabeled__ tinyint(1) DEFAULT 0 NOT NULL COMMENT 'refs #7496 deprecated 2024-06-20'; -ALTER TABLE IF EXISTS vn.forecastedBalance RENAME vn2008.call_information__; -ALTER TABLE IF EXISTS vn.forecastedBalance COMMENT='@deprecated 2024-05-21'; \ No newline at end of file +ALTER TABLE IF EXISTS vn.forecastedBalance RENAME vn.forecastedBalance__ ; +ALTER TABLE IF EXISTS vn.forecastedBalance__ COMMENT='@deprecated 2024-05-21'; \ No newline at end of file -- 2.40.1 From 70eddb6ce2308450d3c72dd1f4a250972ee287bd Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 7 Jun 2024 08:18:07 +0200 Subject: [PATCH 141/413] refactor: refs #7419 Added index ticketLog --- db/versions/11092-azureBirch/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11092-azureBirch/00-firstScript.sql diff --git a/db/versions/11092-azureBirch/00-firstScript.sql b/db/versions/11092-azureBirch/00-firstScript.sql new file mode 100644 index 000000000..12b9d7a20 --- /dev/null +++ b/db/versions/11092-azureBirch/00-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX ticketLog_creationDate_IDX USING BTREE ON vn.ticketLog (creationDate,changedModel,`action`); -- 2.40.1 From cdc18ed84fdfd05d3ee070c3615c7cc77e6e5f62 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 7 Jun 2024 08:32:59 +0200 Subject: [PATCH 142/413] refs #6897 fix entry Salix --- e2e/paths/10-travel/03_descriptor.spec.js | 102 --------------- e2e/paths/12-entry/01_summary.spec.js | 47 ------- e2e/paths/12-entry/02_descriptor.spec.js | 49 -------- e2e/paths/12-entry/03_latestBuys.spec.js | 116 ------------------ e2e/paths/12-entry/04_create.spec.js | 34 ----- e2e/paths/12-entry/05_basicData.spec.js | 81 ------------ e2e/paths/12-entry/06_observations.spec.js | 65 ---------- e2e/paths/12-entry/07_buys.spec.js | 69 ----------- modules/entry/front/main/index.html | 21 ++++ modules/entry/front/main/index.js | 5 +- .../travel/front/descriptor-menu/index.html | 8 +- modules/travel/front/descriptor-menu/index.js | 5 + 12 files changed, 31 insertions(+), 571 deletions(-) delete mode 100644 e2e/paths/12-entry/01_summary.spec.js delete mode 100644 e2e/paths/12-entry/02_descriptor.spec.js delete mode 100644 e2e/paths/12-entry/03_latestBuys.spec.js delete mode 100644 e2e/paths/12-entry/04_create.spec.js delete mode 100644 e2e/paths/12-entry/05_basicData.spec.js delete mode 100644 e2e/paths/12-entry/06_observations.spec.js delete mode 100644 e2e/paths/12-entry/07_buys.spec.js diff --git a/e2e/paths/10-travel/03_descriptor.spec.js b/e2e/paths/10-travel/03_descriptor.spec.js index 4723cc4a3..f066a74ca 100644 --- a/e2e/paths/10-travel/03_descriptor.spec.js +++ b/e2e/paths/10-travel/03_descriptor.spec.js @@ -33,106 +33,4 @@ describe('Travel descriptor path', () => { expect(state).toBe('travel.card.summary'); }); - - it('should be redirected to the create entry view', async() => { - await page.waitToClick(selectors.travelDescriptor.dotMenu); - await page.waitToClick(selectors.travelDescriptor.dotMenuAddEntry); - await page.waitForState('entry.create'); - const state = await page.getState(); - - expect(state).toBe('entry.create'); - }); - - it('should check some data was imported from the travel', async() => { - const travel = await page.waitToGetProperty(selectors.entryCreate.travel, 'value'); - const campany = await page.waitToGetProperty(selectors.entryCreate.company, 'value'); - - expect(travel).toContain('Warehouse'); - expect(campany).toContain('VNL'); - }); - - it('should navigate back to the travel index', async() => { - await page.waitToClick('.cancel'); - await page.waitToClick(selectors.globalItems.homeButton); - await page.selectModule('travel'); - await page.waitForState('travel.index'); - const state = await page.getState(); - - expect(state).toBe('travel.index'); - }); - - it('should click on the add entry button of the third result to be redirected to create entry', async() => { - await page.keyboard.press('Enter'); - await page.waitToClick(selectors.travelIndex.firstTravelAddEntryButton); - await page.waitForState('entry.create'); - const state = await page.getState(); - - expect(state).toBe('entry.create'); - }); - - it('should check again some data was imported from the travel', async() => { - const travel = await page.waitToGetProperty(selectors.entryCreate.travel, 'value'); - const campany = await page.waitToGetProperty(selectors.entryCreate.company, 'value'); - - expect(travel).toContain('Warehouse'); - expect(campany).toContain('VNL'); - }); - - it('should navigate to the travel summary of a given travel', async() => { - await page.waitToClick('.cancel'); - await page.waitToClick(selectors.globalItems.homeButton); - await page.selectModule('travel'); - await page.write(selectors.travelIndex.generalSearchFilter, '3'); - await page.keyboard.press('Enter'); - await page.waitForState('travel.card.summary'); - const state = await page.getState(); - - expect(state).toBe('travel.card.summary'); - }); - - it('should be redirected to the create travel when using the clone option of the dot menu', async() => { - await page.waitToClick(selectors.travelDescriptor.dotMenu); - await page.waitToClick(selectors.travelDescriptor.dotMenuClone); - await page.respondToDialog('accept'); - await page.waitForState('travel.create'); - const state = await page.getState(); - - expect(state).toBe('travel.create'); - }); - - it('should edit the data to clone and then get redirected to the cloned travel basic data', async() => { - await page.clearInput(selectors.travelCreate.reference); - await page.write(selectors.travelCreate.reference, 'reference'); - await page.autocompleteSearch(selectors.travelCreate.agency, 'entanglement'); - await page.pickDate(selectors.travelCreate.shipped); - await page.pickDate(selectors.travelCreate.landed); - await page.autocompleteSearch(selectors.travelCreate.warehouseOut, 'warehouse one'); - await page.autocompleteSearch(selectors.travelCreate.warehouseIn, 'warehouse two'); - await page.waitToClick(selectors.travelCreate.saveButton); - await page.waitForState('travel.card.basicData'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should update the landed date to a future date to enable cloneWithEntries', async() => { - const nextMonth = Date.vnNew(); - nextMonth.setMonth(nextMonth.getMonth() + 1); - await page.pickDate(selectors.travelBasicData.deliveryDate, nextMonth); - await page.waitToClick(selectors.travelBasicData.save); - await page.waitForState('travel.card.basicData'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should navigate to the summary and then clone the travel and its entries using the descriptor menu to get redirected to the cloned travel basic data', async() => { - await page.waitToClick('vn-icon[icon="launch"]'); - await page.waitForState('travel.card.summary'); - await page.waitForTimeout(1000); - await page.waitToClick(selectors.travelDescriptor.dotMenu); - await page.waitToClick(selectors.travelDescriptor.dotMenuCloneWithEntries); - await page.waitToClick(selectors.travelDescriptor.acceptClonation); - await page.waitForState('travel.card.basicData'); - }); }); diff --git a/e2e/paths/12-entry/01_summary.spec.js b/e2e/paths/12-entry/01_summary.spec.js deleted file mode 100644 index b846bc4c8..000000000 --- a/e2e/paths/12-entry/01_summary.spec.js +++ /dev/null @@ -1,47 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Entry summary path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'entry'); - await page.accessToSearchResult('4'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should reach the second entry summary section', async() => { - await page.waitForState('entry.card.summary'); - }); - - it(`should display details from the entry on the header`, async() => { - await page.waitForTextInElement(selectors.entrySummary.header, 'The farmer'); - const result = await page.waitToGetProperty(selectors.entrySummary.header, 'innerText'); - - expect(result).toContain('The farmer'); - }); - - it('should display some entry details like the reference', async() => { - const result = await page.waitToGetProperty(selectors.entrySummary.reference, 'innerText'); - - expect(result).toContain('Movement 4'); - }); - - it('should display other entry details like the confirmed', async() => { - const result = await page.checkboxState(selectors.entrySummary.confirmed, 'innerText'); - - expect(result).toContain('unchecked'); - }); - - it('should display all buys for the entry', async() => { - const result = await page.countElement(selectors.entrySummary.anyBuyLine); - - expect(result).toEqual(4); - }); -}); diff --git a/e2e/paths/12-entry/02_descriptor.spec.js b/e2e/paths/12-entry/02_descriptor.spec.js deleted file mode 100644 index 997a6065c..000000000 --- a/e2e/paths/12-entry/02_descriptor.spec.js +++ /dev/null @@ -1,49 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Entry descriptor path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'entry'); - await page.accessToSearchResult('2'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should reach the second entry summary section', async() => { - await page.waitForState('entry.card.summary'); - }); - - it('should show some entry information', async() => { - const result = await page.waitToGetProperty(selectors.entryDescriptor.agency, 'innerText'); - - expect(result).toContain('inhouse pickup'); - }); - - it('should click the travels button to be redirected to the travels index filtered by the current agency', async() => { - await page.waitToClick(selectors.entryDescriptor.travelsQuicklink); - await page.expectURL('/travel/index'); - await page.expectURL('agencyModeFk'); - }); - - it('should go back to the entry summary', async() => { - await page.waitToClick(selectors.globalItems.homeButton); - await page.selectModule('entry'); - await page.accessToSearchResult('2'); - await page.waitForState('entry.card.summary'); - }); - - it('should click the entries button to be redirected to the entries index filtered by the current supplier', async() => { - await page.waitToClick(selectors.entryDescriptor.entriesQuicklink); - await page.expectURL('/entry/index'); - await page.expectURL('supplierFk'); - await page.expectURL('to'); - await page.expectURL('from'); - }); -}); diff --git a/e2e/paths/12-entry/03_latestBuys.spec.js b/e2e/paths/12-entry/03_latestBuys.spec.js deleted file mode 100644 index 9ec072912..000000000 --- a/e2e/paths/12-entry/03_latestBuys.spec.js +++ /dev/null @@ -1,116 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Entry lastest buys path', () => { - let browser; - let page; - const httpRequests = []; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - page.on('request', req => { - if (req.url().includes(`Buys/latestBuysFilter`)) - httpRequests.push(req.url()); - }); - await page.loginAndModule('buyer', 'entry'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should access the latest buys seccion and search not seeing the edit buys button yet', async() => { - await page.waitToClick(selectors.entryLatestBuys.latestBuysSectionButton); - await page.waitForSelector(selectors.entryLatestBuys.editBuysButton, {visible: false}); - }); - - it('should filter by name', async() => { - await page.write(selectors.entryLatestBuys.generalSearchInput, 'Melee'); - await page.keyboard.press('Enter'); - await page.waitToClick(selectors.entryLatestBuys.chip); - - expect(httpRequests.find(req => req.includes(('search=Melee')))).toBeDefined(); - }); - - it('should filter by reign and type', async() => { - await page.click(selectors.entryLatestBuys.firstReignIcon); - await page.autocompleteSearch(selectors.entryLatestBuys.typeInput, 'Alstroemeria'); - await page.click(selectors.entryLatestBuys.chip); - - expect(httpRequests.find(req => req.includes(('categoryFk')))).toBeDefined(); - expect(httpRequests.find(req => req.includes(('typeFk')))).toBeDefined(); - }); - - it('should filter by sales person', async() => { - await page.autocompleteSearch(selectors.entryLatestBuys.salesPersonInput, 'buyerNick'); - await page.waitToClick(selectors.entryLatestBuys.chip); - - expect(httpRequests.find(req => req.includes(('salesPersonFk')))).toBeDefined(); - }); - - it('should filter by supplier', async() => { - await page.autocompleteSearch(selectors.entryLatestBuys.supplierInput, 'Farmer King'); - await page.waitToClick(selectors.entryLatestBuys.chip); - - expect(httpRequests.find(req => req.includes(('supplierFk')))).toBeDefined(); - }); - - it('should filter by active', async() => { - await page.waitToClick(selectors.entryLatestBuys.activeCheck); - await page.waitToClick(selectors.entryLatestBuys.activeCheck); - await page.waitToClick(selectors.entryLatestBuys.chip); - - expect(httpRequests.find(req => req.includes(('active=true')))).toBeDefined(); - expect(httpRequests.find(req => req.includes(('active=false')))).toBeDefined(); - }); - - it('should filter by visible', async() => { - await page.waitToClick(selectors.entryLatestBuys.visibleCheck); - await page.waitToClick(selectors.entryLatestBuys.visibleCheck); - await page.waitToClick(selectors.entryLatestBuys.chip); - - expect(httpRequests.find(req => req.includes(('visible=true')))).toBeDefined(); - expect(httpRequests.find(req => req.includes(('visible=false')))).toBeDefined(); - }); - - it('should filter by floramondo', async() => { - await page.waitToClick(selectors.entryLatestBuys.floramondoCheck); - await page.waitToClick(selectors.entryLatestBuys.floramondoCheck); - await page.waitToClick(selectors.entryLatestBuys.chip); - - expect(httpRequests.find(req => req.includes(('floramondo=true')))).toBeDefined(); - expect(httpRequests.find(req => req.includes(('floramondo=false')))).toBeDefined(); - }); - - it('should filter by tag Color', async() => { - await page.waitToClick(selectors.entryLatestBuys.addTagButton); - await page.autocompleteSearch(selectors.entryLatestBuys.itemTagInput, 'Color'); - await page.autocompleteSearch(selectors.entryLatestBuys.itemTagValueInput, 'Brown'); - await page.waitToClick(selectors.entryLatestBuys.chip); - - expect(httpRequests.find(req => req.includes(('tags')))).toBeDefined(); - }); - - it('should select all lines but one and then check the edit buys button appears', async() => { - await page.waitToClick(selectors.entryLatestBuys.allBuysCheckBox); - await page.waitToClick(selectors.entryLatestBuys.secondBuyCheckBox); - await page.waitForSelector(selectors.entryLatestBuys.editBuysButton, {visible: true}); - }); - - it('should open the edit dialog', async() => { - await page.waitToClick(selectors.entryLatestBuys.editBuysButton); - await page.waitForSelector(selectors.entryLatestBuys.fieldAutocomplete, {visible: true}); - }); - - it('should search for the "Description" and type a new one for the items in each selected buy', async() => { - await page.autocompleteSearch(selectors.entryLatestBuys.fieldAutocomplete, 'Description'); - await page.write(selectors.entryLatestBuys.newValueInput, 'Crafted item'); - await page.waitToClick(selectors.entryLatestBuys.acceptEditBuysDialog); - }); - - it('should navigate to the entry.buy section by clicking one of the buys', async() => { - await page.waitToClick(selectors.entryLatestBuys.firstBuy); - await page.waitForState('entry.card.buy.index'); - }); -}); diff --git a/e2e/paths/12-entry/04_create.spec.js b/e2e/paths/12-entry/04_create.spec.js deleted file mode 100644 index 537637671..000000000 --- a/e2e/paths/12-entry/04_create.spec.js +++ /dev/null @@ -1,34 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Entry create path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'entry'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should click the create entry button to open the form', async() => { - await page.waitToClick(selectors.entryIndex.createEntryButton); - await page.waitForState('entry.create'); - }); - - it('should fill the form to create a valid entry then redirect to basic Data', async() => { - await page.autocompleteSearch(selectors.entryIndex.newEntrySupplier, 'The farmer'); - await page.autocompleteSearch(selectors.entryIndex.newEntryTravel, 'Warehouse'); - await page.autocompleteSearch(selectors.entryIndex.newEntryCompany, 'ORN'); - - await page.waitToClick(selectors.entryIndex.saveNewEntry); - await page.waitForNavigation({ - waitUntil: 'load', - }); - await page.waitForState('entry.card.basicData'); - }); -}); diff --git a/e2e/paths/12-entry/05_basicData.spec.js b/e2e/paths/12-entry/05_basicData.spec.js deleted file mode 100644 index f1f14f8da..000000000 --- a/e2e/paths/12-entry/05_basicData.spec.js +++ /dev/null @@ -1,81 +0,0 @@ -import getBrowser from '../../helpers/puppeteer'; - -const $ = { - reference: 'vn-entry-basic-data vn-textfield[ng-model="$ctrl.entry.reference"]', - invoiceNumber: 'vn-entry-basic-data vn-textfield[ng-model="$ctrl.entry.invoiceNumber"]', - notes: 'vn-entry-basic-data vn-textfield[ng-model="$ctrl.entry.notes"]', - observations: 'vn-entry-basic-data vn-textarea[ng-model="$ctrl.entry.observation"]', - supplier: 'vn-entry-basic-data vn-autocomplete[ng-model="$ctrl.entry.supplierFk"]', - currency: 'vn-entry-basic-data vn-autocomplete[ng-model="$ctrl.entry.currencyFk"]', - commission: 'vn-entry-basic-data vn-input-number[ng-model="$ctrl.entry.commission"]', - company: 'vn-entry-basic-data vn-autocomplete[ng-model="$ctrl.entry.companyFk"]', - ordered: 'vn-entry-basic-data vn-check[ng-model="$ctrl.entry.isOrdered"]', - confirmed: 'vn-entry-basic-data vn-check[ng-model="$ctrl.entry.isConfirmed"]', - inventory: 'vn-entry-basic-data vn-check[ng-model="$ctrl.entry.isExcludedFromAvailable"]', - raid: 'vn-entry-basic-data vn-check[ng-model="$ctrl.entry.isRaid"]', - booked: 'vn-entry-basic-data vn-check[ng-model="$ctrl.entry.isBooked"]', - save: 'vn-entry-basic-data button[type=submit]', -}; - -describe('Entry basic data path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'entry'); - await page.accessToSearchResult('2'); - await page.accessToSection('entry.card.basicData'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should edit the basic data and confirm the reference was edited', async() => { - await page.write($.reference, 'new movement 8'); - await page.write($.invoiceNumber, 'new movement 8'); - await page.write($.observations, ' edited'); - await page.autocompleteSearch($.supplier, 'Plants nick'); - await page.autocompleteSearch($.currency, 'eur'); - await page.clearInput($.commission); - await page.write($.commission, '100'); - await page.autocompleteSearch($.company, 'CCs'); - await page.waitToClick($.ordered); - await page.waitToClick($.confirmed); - await page.waitToClick($.inventory); - await page.waitToClick($.raid); - await page.waitToClick($.booked); - await page.waitToClick($.save); - const message = await page.waitForSnackbar(); - - await page.reloadSection('entry.card.basicData'); - const reference = await page.waitToGetProperty($.reference, 'value'); - const supplier = await page.waitToGetProperty($.supplier, 'value'); - const invoiceNumber = await page.waitToGetProperty($.invoiceNumber, 'value'); - const observations = await page.waitToGetProperty($.observations, 'value'); - const currency = await page.waitToGetProperty($.currency, 'value'); - const commission = await page.waitToGetProperty($.commission, 'value'); - const company = await page.waitToGetProperty($.company, 'value'); - const ordered = await page.checkboxState($.ordered); - const confirmed = await page.checkboxState($.confirmed); - const inventory = await page.checkboxState($.inventory); - const raid = await page.checkboxState($.raid); - const booked = await page.checkboxState($.booked); - - expect(message.text).toContain('Data saved!'); - expect(reference).toEqual('new movement 8'); - expect(supplier).toEqual('Plants nick'); - expect(invoiceNumber).toEqual('new movement 8'); - expect(observations).toEqual('observation two edited'); - expect(currency).toEqual('EUR'); - expect(commission).toEqual('100'); - expect(company).toEqual('CCs'); - expect(ordered).toBe('checked'); - expect(confirmed).toBe('checked'); - expect(inventory).toBe('checked'); - expect(raid).toBe('checked'); - expect(booked).toBe('unchecked'); - }); -}); diff --git a/e2e/paths/12-entry/06_observations.spec.js b/e2e/paths/12-entry/06_observations.spec.js deleted file mode 100644 index dcad44fb0..000000000 --- a/e2e/paths/12-entry/06_observations.spec.js +++ /dev/null @@ -1,65 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Entry observations path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'entry'); - await page.accessToSearchResult('2'); - await page.accessToSection('entry.card.observation'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it(`should add two new observations of the same type then fail to save as they can't be repeated`, async() => { - await page.waitToClick(selectors.entryObservations.addNewObservation); - await page.waitToClick(selectors.entryObservations.addNewObservation); - await page.autocompleteSearch(selectors.entryObservations.firstObservationType, 'SalesPerson'); - await page.autocompleteSearch(selectors.entryObservations.secondObservationType, 'SalesPerson'); - await page.write(selectors.entryObservations.firstObservationDescription, 'first observation'); - await page.write(selectors.entryObservations.secondObservationDescription, 'second observation'); - await page.waitToClick(selectors.entryObservations.saveObservationsButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain(`The observation type can't be repeated`); - }); - - it('should set the 2nd observation of a different one and successfully save both', async() => { - await page.autocompleteSearch(selectors.entryObservations.secondObservationType, 'Delivery'); - await page.waitToClick(selectors.entryObservations.saveObservationsButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should reload the section and make sure the first observation type was saved correctly', async() => { - await page.reloadSection('entry.card.observation'); - const result = await page.waitToGetProperty(selectors.entryObservations.firstObservationType, 'value'); - - expect(result).toEqual('SalesPerson'); - }); - - it('should make sure the first observation description was saved correctly', async() => { - const result = await page.waitToGetProperty(selectors.entryObservations.firstObservationDescription, 'value'); - - expect(result).toEqual('first observation'); - }); - - it('should make sure the second observation type was saved correctly', async() => { - const result = await page.waitToGetProperty(selectors.entryObservations.secondObservationType, 'value'); - - expect(result).toEqual('Delivery'); - }); - - it('should make sure the second observation description was saved correctly', async() => { - const result = await page.waitToGetProperty(selectors.entryObservations.secondObservationDescription, 'value'); - - expect(result).toEqual('second observation'); - }); -}); diff --git a/e2e/paths/12-entry/07_buys.spec.js b/e2e/paths/12-entry/07_buys.spec.js deleted file mode 100644 index b960673ec..000000000 --- a/e2e/paths/12-entry/07_buys.spec.js +++ /dev/null @@ -1,69 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Entry import, create and edit buys path', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('buyer', 'entry'); - await page.accessToSearchResult('3'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should count the summary buys and find there only one at this point', async() => { - const buysCount = await page.countElement(selectors.entrySummary.anyBuyLine); - - expect(buysCount).toEqual(2); - }); - - it('should navigate to the buy section and then click the import button opening the import form', async() => { - await page.accessToSection('entry.card.buy.index'); - await page.waitToClick(selectors.entryBuys.importButton); - await page.waitForState('entry.card.buy.import'); - }); - - it('should fill the form, import the a JSON file and select items for each import and confirm import', async() => { - let currentDir = process.cwd(); - let filePath = `${currentDir}/e2e/assets/07_import_buys.json`; - - const [fileChooser] = await Promise.all([ - page.waitForFileChooser(), - page.waitToClick(selectors.entryBuys.file) - ]); - await fileChooser.accept([filePath]); - - await page.waitForTextInField(selectors.entryBuys.ref, '200573095, 200573106, 200573117, 200573506'); - await page.waitForTextInField(selectors.entryBuys.observation, '729-6340 2846'); - - await page.autocompleteSearch(selectors.entryBuys.firstImportedItem, 'Ranged weapon longbow 200cm'); - await page.autocompleteSearch(selectors.entryBuys.secondImportedItem, 'Ranged weapon longbow 200cm'); - await page.autocompleteSearch(selectors.entryBuys.thirdImportedItem, 'Ranged weapon sniper rifle 113cm'); - await page.autocompleteSearch(selectors.entryBuys.fourthImportedItem, 'Melee weapon heavy shield 100cm'); - - await page.waitToClick(selectors.entryBuys.importBuysButton); - - const message = await page.waitForSnackbar(); - const state = await page.getState(); - - expect(message.text).toContain('Data saved!'); - expect(state).toBe('entry.card.buy.index'); - }); - - it('should count the buys to find 4 buys have been added', async() => { - await page.waitForNumberOfElements(selectors.entryBuys.anyBuyLine, 6); - }); - - it('should delete the four buys that were just added', async() => { - await page.waitToClick(selectors.entryBuys.allBuyCheckbox); - await page.waitToClick(selectors.entryBuys.firstBuyCheckbox); - await page.waitToClick(selectors.entryBuys.deleteBuysButton); - await page.waitToClick(selectors.globalItems.acceptButton); - await page.waitForNumberOfElements(selectors.entryBuys.anyBuyLine, 1); - }); -}); diff --git a/modules/entry/front/main/index.html b/modules/entry/front/main/index.html index fd40910d9..d55fbd60b 100644 --- a/modules/entry/front/main/index.html +++ b/modules/entry/front/main/index.html @@ -1,3 +1,24 @@ + + + + + + + + + + + + diff --git a/modules/entry/front/main/index.js b/modules/entry/front/main/index.js index cc0a8d6a3..69bddc7fc 100644 --- a/modules/entry/front/main/index.js +++ b/modules/entry/front/main/index.js @@ -2,10 +2,7 @@ import ngModule from '../module'; import ModuleMain from 'salix/components/module-main'; export default class Entry extends ModuleMain { - async $onInit() { - this.$state.go('home'); - window.location.href = await this.vnApp.getUrl(`entry/`); - } + } ngModule.vnComponent('vnEntry', { diff --git a/modules/travel/front/descriptor-menu/index.html b/modules/travel/front/descriptor-menu/index.html index 9b408994f..19831860b 100644 --- a/modules/travel/front/descriptor-menu/index.html +++ b/modules/travel/front/descriptor-menu/index.html @@ -26,8 +26,8 @@ Delete travel Add entry @@ -35,7 +35,7 @@ - - - this.$state.go('travel.card.basicData', {id: res.data})); -- 2.40.1 From 310c2383cb7f76eae9383ea16843fb7ba6d98c0f Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 7 Jun 2024 09:08:21 +0200 Subject: [PATCH 143/413] fix: refs #6286 replace id for reason --- .../methods/worker-time-control/updateWorkerTimeControlMail.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js index 3594f05fe..3fd743fe3 100644 --- a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js +++ b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js @@ -63,7 +63,7 @@ module.exports = Self => { }, { state: args.state, - reason: args.workerId, + reason: args.reason, year: args.year, week: args.week, workerFk: args.workerId -- 2.40.1 From 7c0fa6dbb9f27bbabbd78a08612f6f6e0b1e9c14 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 7 Jun 2024 09:18:52 +0200 Subject: [PATCH 144/413] feat isScannedExpedition refs #7276 --- db/routines/vn/procedures/expedition_getFromRoute.sql | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/expedition_getFromRoute.sql b/db/routines/vn/procedures/expedition_getFromRoute.sql index 2b4de5662..3742ef4fb 100644 --- a/db/routines/vn/procedures/expedition_getFromRoute.sql +++ b/db/routines/vn/procedures/expedition_getFromRoute.sql @@ -15,7 +15,8 @@ BEGIN t.addressFk, a.nickname, sub2.itemPackingTypeConcat, - est.code + est.code, + sub5.isScanned FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = e.ticketFk @@ -33,6 +34,11 @@ BEGIN GROUP BY sub.ticketFk ) sub2 ON sub2.ticketFk = t.id LEFT JOIN expeditionStateType est ON est.id = e.stateTypeFk + LEFT JOIN (SELECT es.expeditionFk, isScanned + FROM expeditionState es + JOIN (SELECT expeditionFk, MAX(id) maxId + FROM expeditionState es + GROUP BY expeditionFk)sub4 ON sub4.maxId = es.id)sub5 ON sub5.expeditionFk = e.id WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE ORDER BY r.created, t.priority DESC; END$$ -- 2.40.1 From 48550bd986f6eb72862a7489da6796de34d6051d Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 7 Jun 2024 11:35:03 +0200 Subject: [PATCH 145/413] refs #6897 fix remove --- back/nodemonConfig.json | 3 +- .../01_summary_and_descriptor.spec.js | 5 - front/module-import.js | 37 ++- modules/entry/front/basic-data/index.html | 234 --------------- modules/entry/front/basic-data/index.js | 68 ----- modules/entry/front/basic-data/style.scss | 3 - modules/entry/front/buy/import/index.html | 205 -------------- modules/entry/front/buy/import/index.js | 159 ----------- modules/entry/front/buy/import/index.spec.js | 199 ------------- modules/entry/front/buy/import/style.scss | 5 - modules/entry/front/buy/index/index.html | 243 ---------------- modules/entry/front/buy/index/index.js | 81 ------ modules/entry/front/buy/index/index.spec.js | 92 ------ modules/entry/front/buy/index/locale/es.yml | 3 - modules/entry/front/buy/index/style.scss | 42 --- modules/entry/front/buy/locale/es.yml | 8 - modules/entry/front/card/index.html | 5 - modules/entry/front/card/index.js | 59 ---- modules/entry/front/create/index.html | 69 ----- modules/entry/front/create/index.js | 43 --- modules/entry/front/create/locale/es.yml | 2 - modules/entry/front/create/style.scss | 10 - .../entry/front/descriptor-popover/index.html | 3 - .../entry/front/descriptor-popover/index.js | 9 - modules/entry/front/descriptor/index.html | 65 ----- modules/entry/front/descriptor/index.js | 99 ------- modules/entry/front/descriptor/index.spec.js | 40 --- modules/entry/front/descriptor/locale/es.yml | 7 - modules/entry/front/index.js | 14 - modules/entry/front/index/locale/es.yml | 17 -- .../front/latest-buys-search-panel/index.html | 242 ---------------- .../front/latest-buys-search-panel/index.js | 61 ---- .../latest-buys-search-panel/index.spec.js | 56 ---- .../front/latest-buys-search-panel/style.scss | 70 ----- modules/entry/front/latest-buys/index.html | 267 ------------------ modules/entry/front/latest-buys/index.js | 209 -------------- modules/entry/front/latest-buys/index.spec.js | 100 ------- modules/entry/front/latest-buys/locale/en.yml | 2 - modules/entry/front/latest-buys/locale/es.yml | 19 -- modules/entry/front/latest-buys/style.scss | 7 - modules/entry/front/locale/es.yml | 6 - modules/entry/front/log/index.html | 1 - modules/entry/front/log/index.js | 7 - modules/entry/front/log/locale/es.yml | 1 - modules/entry/front/main/index.html | 25 -- modules/entry/front/main/index.js | 11 - modules/entry/front/note/index.html | 72 ----- modules/entry/front/note/index.js | 20 -- modules/entry/front/routes.json | 92 +----- modules/entry/front/search-panel/index.html | 100 ------- modules/entry/front/search-panel/index.js | 7 - .../entry/front/search-panel/locale/es.yml | 9 - modules/entry/front/summary/index.html | 196 ------------- modules/entry/front/summary/index.js | 33 --- modules/entry/front/summary/index.spec.js | 49 ---- modules/entry/front/summary/locale/es.yml | 11 - modules/entry/front/summary/style.scss | 30 -- modules/item/front/routes.json | 8 +- modules/travel/front/routes.json | 8 +- 59 files changed, 28 insertions(+), 3520 deletions(-) delete mode 100644 modules/entry/front/basic-data/index.html delete mode 100644 modules/entry/front/basic-data/index.js delete mode 100644 modules/entry/front/basic-data/style.scss delete mode 100644 modules/entry/front/buy/import/index.html delete mode 100644 modules/entry/front/buy/import/index.js delete mode 100644 modules/entry/front/buy/import/index.spec.js delete mode 100644 modules/entry/front/buy/import/style.scss delete mode 100644 modules/entry/front/buy/index/index.html delete mode 100644 modules/entry/front/buy/index/index.js delete mode 100644 modules/entry/front/buy/index/index.spec.js delete mode 100644 modules/entry/front/buy/index/locale/es.yml delete mode 100644 modules/entry/front/buy/index/style.scss delete mode 100644 modules/entry/front/buy/locale/es.yml delete mode 100644 modules/entry/front/card/index.html delete mode 100644 modules/entry/front/card/index.js delete mode 100644 modules/entry/front/create/index.html delete mode 100644 modules/entry/front/create/index.js delete mode 100644 modules/entry/front/create/locale/es.yml delete mode 100644 modules/entry/front/create/style.scss delete mode 100644 modules/entry/front/descriptor-popover/index.html delete mode 100644 modules/entry/front/descriptor-popover/index.js delete mode 100644 modules/entry/front/descriptor/index.html delete mode 100644 modules/entry/front/descriptor/index.js delete mode 100644 modules/entry/front/descriptor/index.spec.js delete mode 100644 modules/entry/front/descriptor/locale/es.yml delete mode 100644 modules/entry/front/index/locale/es.yml delete mode 100644 modules/entry/front/latest-buys-search-panel/index.html delete mode 100644 modules/entry/front/latest-buys-search-panel/index.js delete mode 100644 modules/entry/front/latest-buys-search-panel/index.spec.js delete mode 100644 modules/entry/front/latest-buys-search-panel/style.scss delete mode 100644 modules/entry/front/latest-buys/index.html delete mode 100644 modules/entry/front/latest-buys/index.js delete mode 100644 modules/entry/front/latest-buys/index.spec.js delete mode 100644 modules/entry/front/latest-buys/locale/en.yml delete mode 100644 modules/entry/front/latest-buys/locale/es.yml delete mode 100644 modules/entry/front/latest-buys/style.scss delete mode 100644 modules/entry/front/locale/es.yml delete mode 100644 modules/entry/front/log/index.html delete mode 100644 modules/entry/front/log/index.js delete mode 100644 modules/entry/front/log/locale/es.yml delete mode 100644 modules/entry/front/main/index.html delete mode 100644 modules/entry/front/main/index.js delete mode 100644 modules/entry/front/note/index.html delete mode 100644 modules/entry/front/note/index.js delete mode 100644 modules/entry/front/search-panel/index.html delete mode 100644 modules/entry/front/search-panel/index.js delete mode 100644 modules/entry/front/search-panel/locale/es.yml delete mode 100644 modules/entry/front/summary/index.html delete mode 100644 modules/entry/front/summary/index.js delete mode 100644 modules/entry/front/summary/index.spec.js delete mode 100644 modules/entry/front/summary/locale/es.yml delete mode 100644 modules/entry/front/summary/style.scss diff --git a/back/nodemonConfig.json b/back/nodemonConfig.json index 5138bc30e..c468a2f73 100644 --- a/back/nodemonConfig.json +++ b/back/nodemonConfig.json @@ -8,7 +8,6 @@ "modules/account/front/**/*", "modules/claim/front/**/*", "modules/client/front/**/*", - "modules/entry/front/**/*", "modules/invoiceIn/front/**/*", "modules/invoiceOut/front/**/*", "modules/item/front/**/*", @@ -22,4 +21,4 @@ "modules/worker/front/**/*", "modules/zone/front/**/*" ] -} \ No newline at end of file +} diff --git a/e2e/paths/13-supplier/01_summary_and_descriptor.spec.js b/e2e/paths/13-supplier/01_summary_and_descriptor.spec.js index e82f851ea..a2e194e42 100644 --- a/e2e/paths/13-supplier/01_summary_and_descriptor.spec.js +++ b/e2e/paths/13-supplier/01_summary_and_descriptor.spec.js @@ -65,11 +65,6 @@ describe('Supplier summary & descriptor path', () => { await page.waitForState('supplier.card.summary'); }); - it(`should navigate to the supplier's entries`, async() => { - await page.waitToClick(selectors.supplierDescriptor.entriesButton); - await page.waitForState('entry.index'); - }); - it(`should navigate back to suppliers but a different one this time`, async() => { await page.waitToClick(selectors.globalItems.homeButton); await page.waitForState('home'); diff --git a/front/module-import.js b/front/module-import.js index bc547deeb..85731c72c 100755 --- a/front/module-import.js +++ b/front/module-import.js @@ -1,27 +1,26 @@ export default function moduleImport(moduleName) { // TODO: Webpack watches module backend files when using dynamic import - //return import( + // return import( // /* webpackInclude: /modules\/[a-z0-9-]+\/front\/index.js$/ */ // '../modules/'+ moduleName +'/front/index.js' - //); + // ); - switch(moduleName) { - case 'client' : return import('client/front'); - case 'item' : return import('item/front'); - case 'ticket' : return import('ticket/front'); - case 'order' : return import('order/front'); - case 'claim' : return import('claim/front'); - case 'zone' : return import('zone/front'); - case 'travel' : return import('travel/front'); - case 'worker' : return import('worker/front'); - case 'invoiceOut' : return import('invoiceOut/front'); - case 'invoiceIn' : return import('invoiceIn/front'); - case 'route' : return import('route/front'); - case 'entry' : return import('entry/front'); - case 'account' : return import('account/front'); - case 'supplier' : return import('supplier/front'); - case 'shelving' : return import('shelving/front'); - case 'monitor' : return import('monitor/front'); + switch (moduleName) { + case 'client': return import('client/front'); + case 'item': return import('item/front'); + case 'ticket': return import('ticket/front'); + case 'order': return import('order/front'); + case 'claim': return import('claim/front'); + case 'zone': return import('zone/front'); + case 'travel': return import('travel/front'); + case 'worker': return import('worker/front'); + case 'invoiceOut': return import('invoiceOut/front'); + case 'invoiceIn': return import('invoiceIn/front'); + case 'route': return import('route/front'); + case 'account': return import('account/front'); + case 'supplier': return import('supplier/front'); + case 'shelving': return import('shelving/front'); + case 'monitor': return import('monitor/front'); } } diff --git a/modules/entry/front/basic-data/index.html b/modules/entry/front/basic-data/index.html deleted file mode 100644 index 57de1c5f7..000000000 --- a/modules/entry/front/basic-data/index.html +++ /dev/null @@ -1,234 +0,0 @@ - - - - - -
- - - - -
#{{::nickname}}
-
#{{::id}}
-
-
- - -
- {{::agencyModeName}} - {{::warehouseInName}} ({{::shipped | date: 'dd/MM/yyyy'}}) → - {{::warehouseOutName}} ({{::landed | date: 'dd/MM/yyyy'}}) -
-
#{{::id}}
-
- - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - - - - ID - Agency - Warehouse Out - Warehouse In - Shipped - Landed - - - - - - - {{::travel.id}} - - - {{::travel.agency.name}} - {{::travel.warehouseOut.name}} - {{::travel.warehouseIn.name}} - {{::travel.shipped | date: 'dd/MM/yyyy'}} - {{::travel.landed | date: 'dd/MM/yyyy'}} - - - - - - - - diff --git a/modules/entry/front/basic-data/index.js b/modules/entry/front/basic-data/index.js deleted file mode 100644 index 564a3df5c..000000000 --- a/modules/entry/front/basic-data/index.js +++ /dev/null @@ -1,68 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - showFilterDialog(travel) { - this.activeTravel = travel; - this.travelFilterParams = {}; - this.travelFilter = { - include: [ - { - relation: 'agency', - scope: { - fields: ['name'] - } - }, - { - relation: 'warehouseIn', - scope: { - fields: ['name'] - } - }, - { - relation: 'warehouseOut', - scope: { - fields: ['name'] - } - } - ] - }; - - this.$.filterDialog.show(); - } - - selectTravel(id) { - this.entry.travelFk = id; - this.$.filterDialog.hide(); - } - - filter() { - const filter = this.travelFilter; - const params = this.travelFilterParams; - const where = {}; - for (let key in params) { - const value = params[key]; - if (!value) continue; - - switch (key) { - case 'agencyModeFk': - case 'warehouseInFk': - case 'warehouseOutFk': - case 'shipped': - case 'landed': - where[key] = value; - } - } - - filter.where = where; - this.$.travelsModel.applyFilter(filter); - } -} -ngModule.vnComponent('vnEntryBasicData', { - template: require('./index.html'), - bindings: { - entry: '<' - }, - controller: Controller -}); diff --git a/modules/entry/front/basic-data/style.scss b/modules/entry/front/basic-data/style.scss deleted file mode 100644 index 508aa9091..000000000 --- a/modules/entry/front/basic-data/style.scss +++ /dev/null @@ -1,3 +0,0 @@ -.travelFilter{ - width: 950px; -} diff --git a/modules/entry/front/buy/import/index.html b/modules/entry/front/buy/import/index.html deleted file mode 100644 index 28396434c..000000000 --- a/modules/entry/front/buy/import/index.html +++ /dev/null @@ -1,205 +0,0 @@ - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ItemDescriptionSizePackingGroupingBuying valueBox
- - - {{::id}} - {{::name}} - - - - - - - {{::buy.description | dashIfEmpty}}{{::buy.size | dashIfEmpty}}{{::buy.packing | dashIfEmpty}}{{::buy.grouping | dashIfEmpty}}{{::buy.buyingValue | currency: 'EUR':2}} - - -
-
-
- - - - - - -
-
- - - - - - - - - - - - - - - - - - - - - - - - - - ID - Item - Size - Producer - Color - - - - - - - {{::item.id}} - - - {{::item.name}} - {{::item.size}} - {{::item.producerName}} - {{::item.inkName}} - - - - - - - - \ No newline at end of file diff --git a/modules/entry/front/buy/import/index.js b/modules/entry/front/buy/import/index.js deleted file mode 100644 index ba0a98e62..000000000 --- a/modules/entry/front/buy/import/index.js +++ /dev/null @@ -1,159 +0,0 @@ -import ngModule from '../../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -class Controller extends Section { - constructor($element, $) { - super($element, $); - this.import = { - file: '', - invoice: null, - buys: [] - }; - } - - onFileChange($event) { - const input = $event.target; - const file = input.files[0]; - - const reader = new FileReader(); - reader.onload = event => - this.fillData(event.target.result); - reader.readAsText(file, 'UTF-8'); - } - - fillData(raw) { - const data = JSON.parse(raw); - const [invoice] = data.invoices; - - this.$.$applyAsync(() => { - this.import.observation = invoice.tx_awb; - - const companyName = invoice.tx_company; - const boxes = invoice.boxes; - const buys = []; - for (let box of boxes) { - const boxVolume = box.nu_length * box.nu_width * box.nu_height; - for (let product of box.products) { - const packing = product.nu_stems_bunch * product.nu_bunches; - buys.push({ - description: product.nm_product, - companyName: companyName, - size: product.nu_length, - packing: packing, - grouping: product.nu_stems_bunch, - buyingValue: parseFloat(product.mny_rate_stem), - volume: boxVolume, - }); - } - } - - const boxesId = boxes.map(box => box.id_box); - this.import.ref = boxesId.join(', '); - - this.fetchBuys(buys); - }); - } - - fetchBuys(buys) { - const params = {buys}; - const query = `Entries/${this.$params.id}/importBuysPreview`; - this.$http.post(query, params).then(res => { - this.import.buys = res.data; - }); - } - - onSubmit() { - try { - const params = this.import; - const hasAnyEmptyRow = params.buys.some(buy => { - return buy.itemFk == null; - }); - - if (hasAnyEmptyRow) - throw new Error(`Some of the imported buys doesn't have an item`); - - const query = `Entries/${this.$params.id}/importBuys`; - return this.$http.post(query, params) - .then(() => this.vnApp.showSuccess(this.$t('Data saved!'))) - .then(() => this.$state.go('entry.card.buy.index')); - } catch (e) { - this.vnApp.showError(this.$t(e.message)); - return false; - } - } - - itemSearchFunc($search) { - return /^\d+$/.test($search) - ? {id: $search} - : {name: {like: '%' + $search + '%'}}; - } - - showFilterDialog(buy) { - this.activeBuy = buy; - this.itemFilterParams = {}; - this.itemFilter = { - include: [ - { - relation: 'producer', - scope: { - fields: ['name'] - } - }, - { - relation: 'ink', - scope: { - fields: ['name'] - } - } - ] - }; - - this.$.filterDialog.show(); - } - - selectItem(id) { - this.activeBuy['itemFk'] = id; - this.$.filterDialog.hide(); - } - - filter() { - const filter = this.itemFilter; - const params = this.itemFilterParams; - const where = {}; - - for (let key in params) { - const value = params[key]; - if (!value) continue; - - switch (key) { - case 'name': - where[key] = {like: `%${value}%`}; - break; - case 'producerFk': - case 'typeFk': - case 'size': - case 'inkFk': - where[key] = value; - } - } - - filter.where = where; - this.$.itemsModel.applyFilter(filter); - } - - onKeyPress($event) { - if ($event.key === 'Enter') - this.filter(); - } -} - -Controller.$inject = ['$element', '$scope']; - -ngModule.vnComponent('vnEntryBuyImport', { - template: require('./index.html'), - controller: Controller, - bindings: { - worker: '<' - } -}); diff --git a/modules/entry/front/buy/import/index.spec.js b/modules/entry/front/buy/import/index.spec.js deleted file mode 100644 index 036f52074..000000000 --- a/modules/entry/front/buy/import/index.spec.js +++ /dev/null @@ -1,199 +0,0 @@ -import './index.js'; - -describe('Entry', () => { - describe('Component vnEntryBuyImport', () => { - let controller; - let $httpParamSerializer; - let $httpBackend; - - beforeEach(ngModule('entry')); - - beforeEach(angular.mock.inject(($componentController, $compile, $rootScope, _$httpParamSerializer_, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - $httpParamSerializer = _$httpParamSerializer_; - let $element = $compile(' { - it(`should call to the fillData() method`, () => { - controller.fetchBuys = jest.fn(); - - const rawData = `{ - "invoices": [ - { - "tx_awb": "123456", - "boxes": [ - { - "id_box": 1, - "nu_length": 1, - "nu_width": 15, - "nu_height": 80, - "products": [ - { - "nm_product": "Bow", - "nu_length": 1, - "nu_stems_bunch": 1, - "nu_bunches": 1, - "mny_rate_stem": 5.77 - } - - ] - }, - { - "id_box": 2, - "nu_length": 25, - "nu_width": 1, - "nu_height": 45, - "products": [ - { - "nm_product": "Arrow", - "nu_length": 25, - "nu_stems_bunch": 1, - "nu_bunches": 1, - "mny_rate_stem": 2.16 - } - ] - } - ] - } - ]}`; - const expectedBuys = [ - { - 'buyingValue': 5.77, - 'description': 'Bow', - 'grouping': 1, - 'packing': 1, - 'size': 1, - 'volume': 1200}, - - { - 'buyingValue': 2.16, - 'description': 'Arrow', - 'grouping': 1, - 'packing': 1, - 'size': 25, - 'volume': 1125} - ]; - controller.fillData(rawData); - controller.$.$apply(); - - const importData = controller.import; - - expect(importData.observation).toEqual('123456'); - expect(importData.ref).toEqual('1, 2'); - - expect(controller.fetchBuys).toHaveBeenCalledWith(expectedBuys); - }); - }); - - describe('fetchBuys()', () => { - it(`should perform a query to fetch the buys data`, () => { - const buys = [ - { - 'buyingValue': 5.77, - 'description': 'Bow', - 'grouping': 1, - 'packing': 1, - 'size': 1, - 'volume': 1200}, - - { - 'buyingValue': 2.16, - 'description': 'Arrow', - 'grouping': 1, - 'packing': 1, - 'size': 25, - 'volume': 1125} - ]; - - const query = `Entries/1/importBuysPreview`; - $httpBackend.expectPOST(query).respond(200, buys); - controller.fetchBuys(buys); - $httpBackend.flush(); - - const importData = controller.import; - - expect(importData.buys.length).toEqual(2); - }); - }); - - describe('onSubmit()', () => { - it(`should throw an error when some of the rows doesn't have an item`, () => { - jest.spyOn(controller.vnApp, 'showError'); - - controller.import = { - observation: '123456', - ref: '1, 2', - buys: [ - { - 'buyingValue': 5.77, - 'description': 'Bow', - 'grouping': 1, - 'packing': 1, - 'size': 1, - 'volume': 1200}, - { - 'buyingValue': 2.16, - 'description': 'Arrow', - 'grouping': 1, - 'packing': 1, - 'size': 25, - 'volume': 1125} - ] - }; - - controller.onSubmit(); - - const message = `Some of the imported buys doesn't have an item`; - - expect(controller.vnApp.showError).toHaveBeenCalledWith(message); - }); - - it(`should now perform a query to update columns`, () => { - jest.spyOn(controller.vnApp, 'showSuccess'); - controller.$state.go = jest.fn(); - - controller.import = { - observation: '123456', - ref: '1, 2', - buys: [ - { - 'itemFk': 10, - 'buyingValue': 5.77, - 'description': 'Bow', - 'grouping': 1, - 'packing': 1, - 'size': 1, - 'volume': 1200}, - { - 'itemFk': 11, - 'buyingValue': 2.16, - 'description': 'Arrow', - 'grouping': 1, - 'packing': 1, - 'size': 25, - 'volume': 1125} - ] - }; - const params = controller.import; - - const query = `Entries/1/importBuys`; - $httpBackend.expectPOST(query, params).respond(200, params.buys); - controller.onSubmit(); - $httpBackend.flush(); - - const importData = controller.import; - - expect(importData.buys.length).toEqual(2); - - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); - expect(controller.$state.go).toHaveBeenCalledWith('entry.card.buy.index'); - }); - }); - }); -}); diff --git a/modules/entry/front/buy/import/style.scss b/modules/entry/front/buy/import/style.scss deleted file mode 100644 index 9b2fb7688..000000000 --- a/modules/entry/front/buy/import/style.scss +++ /dev/null @@ -1,5 +0,0 @@ -.itemFilter { - vn-table.scrollable { - height: 500px - } -} \ No newline at end of file diff --git a/modules/entry/front/buy/index/index.html b/modules/entry/front/buy/index/index.html deleted file mode 100644 index 0e0c69788..000000000 --- a/modules/entry/front/buy/index/index.html +++ /dev/null @@ -1,243 +0,0 @@ - - - - - - -
- - - - - - -

Subtotal {{$ctrl.ticket.totalWithoutVat | currency: 'EUR':2}}

-

VAT {{$ctrl.ticket.totalWithVat - $ctrl.ticket.totalWithoutVat | currency: 'EUR':2}}

-

Total {{$ctrl.ticket.totalWithVat | currency: 'EUR':2}}

-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - ItemQuantityPackageStickersWeightPackingGroupingBuying valueGrouping pricePacking priceImport
- - - - - {{::buy.item.id}} - - - -
{{::name}}
-
#{{::id}}
-
-
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {{buy.quantity * buy.buyingValue | currency: 'EUR':2}} - -
- - - {{::buy.item.itemType.code}} - - - - {{::buy.item.size}} - - - - {{::buy.item.minPrice | currency: 'EUR':2}} - - -
- {{::buy.item.name}} - -

{{::buy.item.subName}}

-
-
- - -
-
-
-
-
- - - - - - -
- - - - diff --git a/modules/entry/front/buy/index/index.js b/modules/entry/front/buy/index/index.js deleted file mode 100644 index 9131c31f6..000000000 --- a/modules/entry/front/buy/index/index.js +++ /dev/null @@ -1,81 +0,0 @@ -import ngModule from '../../module'; -import './style.scss'; -import Section from 'salix/components/section'; - -export default class Controller extends Section { - saveBuy(buy) { - const missingData = !buy.itemFk || !buy.quantity || !buy.packagingFk; - if (missingData) return; - - let options; - if (buy.id) { - options = { - query: `Buys/${buy.id}`, - method: 'patch' - }; - } - this.$http[options.method](options.query, buy).then(res => { - if (!res.data) return; - - buy = Object.assign(buy, res.data); - this.vnApp.showSuccess(this.$t('Data saved!')); - }); - } - - /** - * Returns checked instances - * - * @return {Array} Checked instances - */ - selectedBuys() { - if (!this.buys) return; - - return this.buys.filter(buy => { - return buy.checked; - }); - } - - deleteBuys() { - const buys = this.selectedBuys(); - const actualInstances = buys.filter(buy => buy.id); - - const params = {buys: actualInstances}; - - if (actualInstances.length) { - this.$http.post(`Buys/deleteBuys`, params).then(() => { - this.vnApp.showSuccess(this.$t('Data saved!')); - }); - } - buys.forEach(buy => { - const index = this.buys.indexOf(buy); - this.buys.splice(index, 1); - }); - } - - toggleGroupingMode(buy, mode) { - const groupingMode = mode === 'grouping' ? mode : 'packing'; - const newGroupingMode = buy.groupingMode === groupingMode ? null : groupingMode; - const params = { - groupingMode: newGroupingMode - }; - - this.$http.patch(`Buys/${buy.id}`, params).then(() => { - buy.groupingMode = newGroupingMode; - this.vnApp.showSuccess(this.$t('Data saved!')); - }); - } - - itemSearchFunc($search) { - return /^\d+$/.test($search) - ? {id: $search} - : {name: {like: '%' + $search + '%'}}; - } -} - -ngModule.vnComponent('vnEntryBuyIndex', { - template: require('./index.html'), - controller: Controller, - bindings: { - entry: '<' - } -}); diff --git a/modules/entry/front/buy/index/index.spec.js b/modules/entry/front/buy/index/index.spec.js deleted file mode 100644 index f5c6d1bdb..000000000 --- a/modules/entry/front/buy/index/index.spec.js +++ /dev/null @@ -1,92 +0,0 @@ -/* eslint max-len: ["error", { "code": 150 }]*/ -import './index.js'; - -describe('Entry buy', () => { - let controller; - let $httpBackend; - - beforeEach(ngModule('entry')); - - beforeEach(angular.mock.inject(($componentController, $compile, $rootScope, _$httpParamSerializer_, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - let $element = $compile(' { - it(`should call the buys patch route if the received buy has an ID`, () => { - const buy = {id: 1, itemFk: 1, quantity: 1, packagingFk: 1}; - - const query = `Buys/${buy.id}`; - - $httpBackend.expectPATCH(query).respond(200); - controller.saveBuy(buy); - $httpBackend.flush(); - }); - }); - - describe('deleteBuys()', () => { - it(`should perform no queries if all buys to delete were not actual instances`, () => { - controller.buys = [ - {checked: true}, - {checked: true}, - {checked: false}]; - - controller.deleteBuys(); - - expect(controller.buys.length).toEqual(1); - }); - - it(`should perform a query to delete as there's an actual instance at least`, () => { - controller.buys = [ - {checked: true, id: 1}, - {checked: true}, - {checked: false}]; - - const query = 'Buys/deleteBuys'; - - $httpBackend.expectPOST(query).respond(200); - controller.deleteBuys(); - $httpBackend.flush(); - - expect(controller.buys.length).toEqual(1); - }); - }); - - describe('toggleGroupingMode()', () => { - it(`should toggle grouping mode from grouping to packing`, () => { - const buy = {id: 999, groupingMode: 'grouping'}; - - const query = `Buys/${buy.id}`; - $httpBackend.expectPATCH(query, {groupingMode: 'packing'}).respond(200); - controller.toggleGroupingMode(buy, 'packing'); - $httpBackend.flush(); - }); - - it(`should toggle grouping mode from packing to grouping`, () => { - const buy = {id: 999, groupingMode: 'packing'}; - const query = `Buys/${buy.id}`; - $httpBackend.expectPATCH(query, {groupingMode: 'grouping'}).respond(200); - controller.toggleGroupingMode(buy, 'grouping'); - $httpBackend.flush(); - }); - - it(`should toggle off the grouping mode if it was packing to packing`, () => { - const buy = {id: 999, groupingMode: 'packing'}; - const query = `Buys/${buy.id}`; - $httpBackend.expectPATCH(query, {groupingMode: null}).respond(200); - controller.toggleGroupingMode(buy, 'packing'); - $httpBackend.flush(); - }); - - it(`should toggle off the grouping mode if it was grouping to grouping`, () => { - const buy = {id: 999, groupingMode: 'grouping'}; - const query = `Buys/${buy.id}`; - $httpBackend.expectPATCH(query, {groupingMode: null}).respond(200); - controller.toggleGroupingMode(buy, 'grouping'); - $httpBackend.flush(); - }); - }); -}); diff --git a/modules/entry/front/buy/index/locale/es.yml b/modules/entry/front/buy/index/locale/es.yml deleted file mode 100644 index 0a1ecf5b1..000000000 --- a/modules/entry/front/buy/index/locale/es.yml +++ /dev/null @@ -1,3 +0,0 @@ -Buys: Compras -Delete buy(s): Eliminar compra(s) -Add buy: Añadir compra \ No newline at end of file diff --git a/modules/entry/front/buy/index/style.scss b/modules/entry/front/buy/index/style.scss deleted file mode 100644 index 3fad252df..000000000 --- a/modules/entry/front/buy/index/style.scss +++ /dev/null @@ -1,42 +0,0 @@ -@import "variables"; - - -vn-entry-buy-index vn-card { - max-width: $width-xl; - - .dark-row { - background-color: lighten($color-marginal, 10%); - } - - thead tr { - border: 1px solid white;; - } - - tbody tr:nth-child(1), - tbody tr:nth-child(2) { - border-left: 1px solid $color-spacer; - border-right: 1px solid $color-spacer; - } - - tbody tr:nth-child(2) { - border-bottom: 1px solid $color-spacer; - } - - tbody{ - border-bottom: 1px solid $color-spacer; - } - - tbody:last-child { - border-bottom: 0; - } - - tbody tr:nth-child(3) { - height: inherit - } - - tr { - margin-bottom: 10px; - } -} - -$color-font-link-medium: lighten($color-font-link, 20%) diff --git a/modules/entry/front/buy/locale/es.yml b/modules/entry/front/buy/locale/es.yml deleted file mode 100644 index 55828a3c6..000000000 --- a/modules/entry/front/buy/locale/es.yml +++ /dev/null @@ -1,8 +0,0 @@ -reference: Referencia -Observation: Observación -Box: Embalaje -Import buys: Importar compras -Some of the imported buys doesn't have an item: Algunas de las compras importadas no tienen un artículo -JSON files only: Solo ficheros JSON -Filter item: Filtrar artículo -Filter...: Filtrar... \ No newline at end of file diff --git a/modules/entry/front/card/index.html b/modules/entry/front/card/index.html deleted file mode 100644 index d386a9ebf..000000000 --- a/modules/entry/front/card/index.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/modules/entry/front/card/index.js b/modules/entry/front/card/index.js deleted file mode 100644 index 96f4702e2..000000000 --- a/modules/entry/front/card/index.js +++ /dev/null @@ -1,59 +0,0 @@ -import ngModule from '../module'; -import ModuleCard from 'salix/components/module-card'; - -class Controller extends ModuleCard { - reload() { - let filter = { - include: [ - { - relation: 'company', - scope: { - fields: ['id', 'code'] - } - }, - { - relation: 'travel', - scope: { - fields: ['id', 'landed', 'agencyModeFk', 'warehouseOutFk'], - include: [ - { - relation: 'agency', - scope: { - fields: ['name'] - } - }, - { - relation: 'warehouseOut', - scope: { - fields: ['name'] - } - }, - { - relation: 'warehouseIn', - scope: { - fields: ['name'] - } - } - ] - } - }, - { - relation: 'supplier', - scope: { - fields: ['id', 'nickname'] - } - }, - { - relation: 'currency' - } - ] - }; - this.$http.get(`Entries/${this.$params.id}`, {filter}) - .then(response => this.entry = response.data); - } -} - -ngModule.vnComponent('vnEntryCard', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/entry/front/create/index.html b/modules/entry/front/create/index.html deleted file mode 100644 index e1e4dc064..000000000 --- a/modules/entry/front/create/index.html +++ /dev/null @@ -1,69 +0,0 @@ - - -
- - - - - - -
{{::nickname}}
-
#{{::id}}
-
-
-
- - - -
- {{::agencyModeName}} - - {{::warehouseInName}} ({{::shipped | date: 'dd/MM/yyyy'}}) - → {{::warehouseOutName}} ({{::landed | date: 'dd/MM/yyyy'}}) -
-
#{{::id}}
-
-
-
- - - - -
- - - - - - -
diff --git a/modules/entry/front/create/index.js b/modules/entry/front/create/index.js deleted file mode 100644 index 5c61730f9..000000000 --- a/modules/entry/front/create/index.js +++ /dev/null @@ -1,43 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -export default class Controller extends Section { - constructor($element, $) { - super($element, $); - - this.entry = { - companyFk: this.vnConfig.companyFk - }; - - if (this.$params && this.$params.supplierFk) - this.entry.supplierFk = parseInt(this.$params.supplierFk); - if (this.$params && this.$params.travelFk) - this.entry.travelFk = parseInt(this.$params.travelFk); - if (this.$params && this.$params.companyFk) - this.entry.companyFk = parseInt(this.$params.companyFk); - } - - onSubmit() { - this.$.watcher.submit().then( - res => this.$state.go('entry.card.basicData', {id: res.data.id}) - ); - } - - searchFunction($search) { - return {or: [ - {'agencyModeName': {like: `%${$search}%`}}, - {'warehouseInName': {like: `%${$search}%`}}, - {'warehouseOutName': {like: `%${$search}%`}}, - {'shipped': new Date($search)}, - {'landed': new Date($search)} - ]}; - } -} - -Controller.$inject = ['$element', '$scope']; - -ngModule.vnComponent('vnEntryCreate', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/entry/front/create/locale/es.yml b/modules/entry/front/create/locale/es.yml deleted file mode 100644 index aa269ed15..000000000 --- a/modules/entry/front/create/locale/es.yml +++ /dev/null @@ -1,2 +0,0 @@ -New entry: Nueva entrada -Required fields (*): Campos requeridos (*) \ No newline at end of file diff --git a/modules/entry/front/create/style.scss b/modules/entry/front/create/style.scss deleted file mode 100644 index 2dc52b1ff..000000000 --- a/modules/entry/front/create/style.scss +++ /dev/null @@ -1,10 +0,0 @@ -vn-entry-create { - vn-card { - position: relative - } - vn-icon[icon="info"] { - position: absolute; - top: 16px; - right: 16px - } -} \ No newline at end of file diff --git a/modules/entry/front/descriptor-popover/index.html b/modules/entry/front/descriptor-popover/index.html deleted file mode 100644 index 465a9bf51..000000000 --- a/modules/entry/front/descriptor-popover/index.html +++ /dev/null @@ -1,3 +0,0 @@ - - - \ No newline at end of file diff --git a/modules/entry/front/descriptor-popover/index.js b/modules/entry/front/descriptor-popover/index.js deleted file mode 100644 index d79aed03e..000000000 --- a/modules/entry/front/descriptor-popover/index.js +++ /dev/null @@ -1,9 +0,0 @@ -import ngModule from '../module'; -import DescriptorPopover from 'salix/components/descriptor-popover'; - -class Controller extends DescriptorPopover {} - -ngModule.vnComponent('vnEntryDescriptorPopover', { - slotTemplate: require('./index.html'), - controller: Controller -}); diff --git a/modules/entry/front/descriptor/index.html b/modules/entry/front/descriptor/index.html deleted file mode 100644 index 7b61a0cf5..000000000 --- a/modules/entry/front/descriptor/index.html +++ /dev/null @@ -1,65 +0,0 @@ - - - - Show entry report - - - -
- - - - - - -
-
- - - - -
- -
-
- - - \ No newline at end of file diff --git a/modules/entry/front/descriptor/index.js b/modules/entry/front/descriptor/index.js deleted file mode 100644 index 3452a6d34..000000000 --- a/modules/entry/front/descriptor/index.js +++ /dev/null @@ -1,99 +0,0 @@ -import ngModule from '../module'; -import Descriptor from 'salix/components/descriptor'; - -class Controller extends Descriptor { - get entry() { - return this.entity; - } - - set entry(value) { - this.entity = value; - } - - get travelFilter() { - let travelFilter; - const entryTravel = this.entry && this.entry.travel; - - if (entryTravel && entryTravel.agencyModeFk) { - travelFilter = this.entry && JSON.stringify({ - agencyModeFk: entryTravel.agencyModeFk - }); - } - return travelFilter; - } - - get entryFilter() { - let entryTravel = this.entry && this.entry.travel; - - if (!entryTravel || !entryTravel.landed) return null; - - const date = new Date(entryTravel.landed); - date.setHours(0, 0, 0, 0); - - const from = new Date(date.getTime()); - from.setDate(from.getDate() - 10); - - const to = new Date(date.getTime()); - to.setDate(to.getDate() + 10); - - return JSON.stringify({ - supplierFk: this.entry.supplierFk, - from, - to - }); - } - - loadData() { - const filter = { - include: [ - { - relation: 'travel', - scope: { - fields: ['id', 'landed', 'agencyModeFk', 'warehouseOutFk'], - include: [ - { - relation: 'agency', - scope: { - fields: ['name'] - } - }, - { - relation: 'warehouseOut', - scope: { - fields: ['name'] - } - }, - { - relation: 'warehouseIn', - scope: { - fields: ['name'] - } - } - ] - } - }, - { - relation: 'supplier', - scope: { - fields: ['id', 'nickname'] - } - } - ] - }; - - return this.getData(`Entries/${this.id}`, {filter}) - .then(res => this.entity = res.data); - } - - showEntryReport() { - this.vnReport.show(`Entries/${this.id}/entry-order-pdf`); - } -} - -ngModule.vnComponent('vnEntryDescriptor', { - template: require('./index.html'), - controller: Controller, - bindings: { - entry: '<' - } -}); diff --git a/modules/entry/front/descriptor/index.spec.js b/modules/entry/front/descriptor/index.spec.js deleted file mode 100644 index 714bb9f3c..000000000 --- a/modules/entry/front/descriptor/index.spec.js +++ /dev/null @@ -1,40 +0,0 @@ -import './index.js'; - -describe('Entry Component vnEntryDescriptor', () => { - let $httpBackend; - let controller; - const entry = {id: 2}; - - beforeEach(ngModule('entry')); - - beforeEach(inject(($componentController, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - controller = $componentController('vnEntryDescriptor', {$element: null}, {entry}); - })); - - describe('showEntryReport()', () => { - it('should open a new window showing a delivery note PDF document', () => { - jest.spyOn(controller.vnReport, 'show'); - - window.open = jasmine.createSpy('open'); - controller.showEntryReport(); - const expectedPath = `Entries/${entry.id}/entry-order-pdf`; - - expect(controller.vnReport.show).toHaveBeenCalledWith(expectedPath); - }); - }); - - describe('loadData()', () => { - it('should perform ask for the entry', () => { - let query = `Entries/${entry.id}`; - jest.spyOn(controller, 'getData'); - - $httpBackend.expectGET(query).respond(); - controller.loadData(); - $httpBackend.flush(); - - expect(controller.getData).toHaveBeenCalledTimes(1); - expect(controller.getData).toHaveBeenCalledWith(query, jasmine.any(Object)); - }); - }); -}); diff --git a/modules/entry/front/descriptor/locale/es.yml b/modules/entry/front/descriptor/locale/es.yml deleted file mode 100644 index ad2fef6f3..000000000 --- a/modules/entry/front/descriptor/locale/es.yml +++ /dev/null @@ -1,7 +0,0 @@ -Reference: Referencia -Supplier card: Ficha del proveedor -All travels with current agency: Todos los envios con la agencia actual -All entries with current supplier: Todas las entradas con el proveedor actual -Show entry report: Ver informe del pedido -Is inventory entry: Es una entrada de inventario -Is virtual entry: Es una redada \ No newline at end of file diff --git a/modules/entry/front/index.js b/modules/entry/front/index.js index 88700b166..f4cae889c 100644 --- a/modules/entry/front/index.js +++ b/modules/entry/front/index.js @@ -1,18 +1,4 @@ export * from './module'; -import './main'; import './index/'; -import './create'; -import './basic-data'; -import './latest-buys'; -import './search-panel'; -import './latest-buys-search-panel'; -import './descriptor'; -import './descriptor-popover'; -import './card'; -import './note'; -import './summary'; -import './log'; -import './buy/index'; -import './buy/import'; diff --git a/modules/entry/front/index/locale/es.yml b/modules/entry/front/index/locale/es.yml deleted file mode 100644 index cebe57a42..000000000 --- a/modules/entry/front/index/locale/es.yml +++ /dev/null @@ -1,17 +0,0 @@ -Inventory entry: Es inventario -Virtual entry: Es una redada -Supplier: Proveedor -Currency: Moneda -Company: Empresa -Confirmed: Confirmada -Ordered: Pedida -Is raid: Redada -Commission: Comisión -Landed: F. entrega -Reference: Referencia -Created: Creado -Booked: Contabilizada -Is inventory: Inventario -Status: Estado -Selection: Selección -Invoice number: Núm. factura \ No newline at end of file diff --git a/modules/entry/front/latest-buys-search-panel/index.html b/modules/entry/front/latest-buys-search-panel/index.html deleted file mode 100644 index c73bf7365..000000000 --- a/modules/entry/front/latest-buys-search-panel/index.html +++ /dev/null @@ -1,242 +0,0 @@ - - - - - - - - - - - - - - - - - - -
{{name}}
-
- {{category.name}} -
> -
-
- - - - - {{name}}: {{nickname}} - - - - - - - - - - - - - - - - - - Tags - - - - - - - - - - - - - -
- - Id/Name: {{$ctrl.filter.search}} - - - {{category.selection.name}} - - - {{type.selection.name}} - - - Sales person: {{salesPerson.selection.nickname}} - - - Supplier: {{supplier.selection.name}} - - - From: {{$ctrl.filter.from | date:'dd/MM/yyyy'}} - - - To: {{$ctrl.filter.to | date:'dd/MM/yyyy'}} - - - Active: {{$ctrl.filter.active ? '✓' : '✗'}} - - - Floramondo: {{$ctrl.filter.floramondo ? '✓' : '✗'}} - - - Visible: {{$ctrl.filter.visible ? '✓' : '✗'}} - - - {{$ctrl.showTagInfo(chipTag)}} - - -
-
diff --git a/modules/entry/front/latest-buys-search-panel/index.js b/modules/entry/front/latest-buys-search-panel/index.js deleted file mode 100644 index 4078580ea..000000000 --- a/modules/entry/front/latest-buys-search-panel/index.js +++ /dev/null @@ -1,61 +0,0 @@ -import ngModule from '../module'; -import SearchPanel from 'core/components/searchbar/search-panel'; -import './style.scss'; - -class Controller extends SearchPanel { - constructor($element, $) { - super($element, $); - } - - $onInit() { - this.filter = { - isActive: true, - tags: [] - }; - } - - changeCategory(id) { - if (this.filter.categoryFk != id) { - this.filter.categoryFk = id; - this.addFilters(); - } - } - - removeItemFilter(param) { - this.filter[param] = null; - if (param == 'categoryFk') this.filter['typeFk'] = null; - this.addFilters(); - } - - removeTag(tag) { - const index = this.filter.tags.indexOf(tag); - if (index > -1) this.filter.tags.splice(index, 1); - this.addFilters(); - } - - onKeyPress($event) { - if ($event.key === 'Enter') - this.addFilters(); - } - - addFilters() { - for (let i = 0; i < this.filter.tags.length; i++) { - if (!this.filter.tags[i].value) - this.filter.tags.splice(i, 1); - } - return this.model.addFilter({}, this.filter); - } - - showTagInfo(itemTag) { - if (!itemTag.tagFk) return itemTag.value; - return `${this.tags.find(tag => tag.id == itemTag.tagFk).name}: ${itemTag.value}`; - } -} - -ngModule.component('vnLatestBuysSearchPanel', { - template: require('./index.html'), - controller: Controller, - bindings: { - model: '<' - } -}); diff --git a/modules/entry/front/latest-buys-search-panel/index.spec.js b/modules/entry/front/latest-buys-search-panel/index.spec.js deleted file mode 100644 index c3c5acbfb..000000000 --- a/modules/entry/front/latest-buys-search-panel/index.spec.js +++ /dev/null @@ -1,56 +0,0 @@ -import './index.js'; - -describe('Entry', () => { - describe('Component vnLatestBuysSearchPanel', () => { - let $element; - let controller; - - beforeEach(ngModule('entry')); - - beforeEach(angular.mock.inject($componentController => { - $element = angular.element(``); - controller = $componentController('vnLatestBuysSearchPanel', {$element}); - controller.model = {addFilter: () => {}}; - })); - - describe('removeItemFilter()', () => { - it(`should remove param from filter`, () => { - controller.filter = {tags: [], categoryFk: 1, typeFk: 1}; - const expectFilter = {tags: [], categoryFk: null, typeFk: null}; - - controller.removeItemFilter('categoryFk'); - - expect(controller.filter).toEqual(expectFilter); - }); - }); - - describe('removeTag()', () => { - it(`should remove tag from filter`, () => { - const tag = {tagFk: 1, value: 'Value'}; - controller.filter = {tags: [tag]}; - const expectFilter = {tags: []}; - - controller.removeTag(tag); - - expect(controller.filter).toEqual(expectFilter); - }); - }); - - describe('showTagInfo()', () => { - it(`should show tag value`, () => { - const tag = {value: 'Value'}; - const result = controller.showTagInfo(tag); - - expect(result).toEqual('Value'); - }); - - it(`should show tag name and value`, () => { - const tag = {tagFk: 1, value: 'Value'}; - controller.tags = [{id: 1, name: 'tagName'}]; - const result = controller.showTagInfo(tag); - - expect(result).toEqual('tagName: Value'); - }); - }); - }); -}); diff --git a/modules/entry/front/latest-buys-search-panel/style.scss b/modules/entry/front/latest-buys-search-panel/style.scss deleted file mode 100644 index ec189c7e4..000000000 --- a/modules/entry/front/latest-buys-search-panel/style.scss +++ /dev/null @@ -1,70 +0,0 @@ -@import "variables"; - -vn-latest-buys-search-panel vn-side-menu div { - & > .input { - padding-left: $spacing-md; - padding-right: $spacing-md; - border-color: $color-spacer; - border-bottom: $border-thin; - } - & > .horizontal { - grid-auto-flow: column; - grid-column-gap: $spacing-sm; - align-items: center; - } - & > .checks { - padding: $spacing-md; - flex-wrap: wrap; - border-color: $color-spacer; - border-bottom: $border-thin; - } - & > .tags { - padding: $spacing-md; - padding-bottom: 0%; - padding-top: 0%; - align-items: center; - } - & > .chips { - display: flex; - flex-wrap: wrap; - padding: $spacing-md; - overflow: hidden; - max-width: 100%; - border-color: $color-spacer; - border-top: $border-thin; - } - & > .item-category { - padding: $spacing-sm; - justify-content: flex-start; - align-items: flex-start; - flex-wrap: wrap; - - vn-autocomplete[vn-id="category"] { - display: none; - } - - & > vn-one { - padding: $spacing-sm; - min-width: 33.33%; - text-align: center; - box-sizing: border-box; - - & > vn-icon { - padding: $spacing-sm; - background-color: $color-font-secondary; - border-radius: 50%; - cursor: pointer; - - &.active { - background-color: $color-main; - color: #fff; - } - & > i:before { - font-size: 2.6rem; - width: 16px; - height: 16px; - } - } - } - } -} diff --git a/modules/entry/front/latest-buys/index.html b/modules/entry/front/latest-buys/index.html deleted file mode 100644 index 2e6de83b9..000000000 --- a/modules/entry/front/latest-buys/index.html +++ /dev/null @@ -1,267 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - Picture - Item ID - - Packing - - Grouping - - Quantity - - Description - - Size - - Tags - - Type - - Intrastat - - Origin - - Weight/Piece - - Active - - Family - - Entry - - Buying value - - Freight value - - Commission value - - Package value - - Is ignored - - Grouping - - Packing - - Min - - Ekt - - Weight - - Package - - Package out - - Landing -
- - - - - - - {{::buy.itemFk}} - - - - {{::buy.packing | dashIfEmpty}} - - - - {{::buy.grouping | dashIfEmpty}} - - {{::buy.quantity}} - {{::buy.description | dashIfEmpty}} - {{::buy.size}} -
- {{::buy.name}} - -

{{::buy.subName}}

-
-
- - -
- {{::buy.code}} - - {{::buy.intrastat}} - {{::buy.origin}}{{::buy.weightByPiece}} - - - {{::buy.family}} - - {{::buy.entryFk}} - - {{::buy.buyingValue | currency: 'EUR':3}}{{::buy.freightValue | currency: 'EUR':3}}{{::buy.comissionValue | currency: 'EUR':3}}{{::buy.packageValue | currency: 'EUR':3}} - - - {{::buy.price2 | currency: 'EUR':3}}{{::buy.price3 | currency: 'EUR':3}}{{::buy.minPrice | currency: 'EUR':3}}{{::buy.ektFk | dashIfEmpty}}{{::buy.weight}}{{::buy.packagingFk}}{{::buy.packingOut}}{{::buy.landing | date: 'dd/MM/yyyy'}}
-
-
-
-
- - - - -
- - - Edit - - {{::$ctrl.totalChecked}} - - buy(s) - - - - - - - - - - - - - - - - diff --git a/modules/entry/front/latest-buys/index.js b/modules/entry/front/latest-buys/index.js deleted file mode 100644 index 292c5b805..000000000 --- a/modules/entry/front/latest-buys/index.js +++ /dev/null @@ -1,209 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; -import './style.scss'; - -export default class Controller extends Section { - constructor($element, $) { - super($element, $); - this.editedColumn; - this.checkAll = false; - this.checkedBuys = []; - - this.smartTableOptions = { - activeButtons: { - search: true, - shownColumns: true, - }, - columns: [ - { - field: 'code', - autocomplete: { - url: 'ItemTypes', - showField: 'code', - valueField: 'code', - } - }, - { - field: 'origin', - autocomplete: { - url: 'Origins', - showField: 'code', - valueField: 'code' - } - }, - { - field: 'family', - autocomplete: { - url: 'ItemFamilies', - valueField: 'code', - showField: 'code' - } - }, - { - field: 'intrastat', - autocomplete: { - url: 'Intrastats', - showField: 'description', - valueField: 'description' - } - }, - { - field: 'packagingFk', - autocomplete: { - url: 'Packagings', - showField: 'id' - } - }, - { - field: 'isActive', - searchable: false - }, - { - field: 'isIgnored', - searchable: false - }, - { - field: 'landing', - searchable: false - } - ] - }; - } - - get columns() { - if (this._columns) return this._columns; - - this._columns = [ - {field: 'packing', displayName: this.$t('Packing')}, - {field: 'grouping', displayName: this.$t('Grouping')}, - {field: 'packageValue', displayName: this.$t('Package value')}, - {field: 'weight', displayName: this.$t('Weight')}, - {field: 'description', displayName: this.$t('Description')}, - {field: 'size', displayName: this.$t('Size')}, - {field: 'weightByPiece', displayName: this.$t('weight/Piece')}, - {field: 'packingOut', displayName: this.$t('PackingOut')}, - {field: 'landing', displayName: this.$t('Landing')} - ]; - - return this._columns; - } - - get checked() { - const buys = this.$.model.data || []; - const checkedBuys = []; - for (let buy of buys) { - if (buy.checked) - checkedBuys.push(buy); - } - - return checkedBuys; - } - - exprBuilder(param, value) { - switch (param) { - case 'id': - case 'size': - case 'weightByPiece': - case 'isActive': - case 'family': - case 'minPrice': - case 'packingOut': - return {[`i.${param}`]: value}; - case 'name': - case 'description': - return {[`i.${param}`]: {like: `%${value}%`}}; - case 'code': - return {'it.code': value}; - case 'intrastat': - return {'intr.description': value}; - case 'origin': - return {'ori.code': value}; - case 'landing': - return {[`lb.${param}`]: value}; - case 'packing': - case 'grouping': - case 'quantity': - case 'entryFk': - case 'buyingValue': - case 'freightValue': - case 'comissionValue': - case 'packageValue': - case 'isIgnored': - case 'price2': - case 'price3': - case 'ektFk': - case 'weight': - case 'packagingFk': - return {[`b.${param}`]: value}; - } - } - - uncheck() { - this.checkAll = false; - this.checkedBuys = []; - } - - get totalChecked() { - if (this.checkedDummyCount) - return this.checkedDummyCount; - - return this.checked.length; - } - - saveChecked(buyId) { - const index = this.checkedBuys.indexOf(buyId); - if (index !== -1) - return this.checkedBuys.splice(index, 1); - return this.checkedBuys.push(buyId); - } - - reCheck() { - if (!this.$.model.data) return; - if (!this.checkedBuys.length) return; - - this.$.model.data.forEach(buy => { - if (this.checkedBuys.includes(buy.id)) - buy.checked = true; - }); - } - - onEditAccept() { - const rowsToEdit = []; - for (let row of this.checked) - rowsToEdit.push({id: row.id, itemFk: row.itemFk}); - - const data = { - field: this.editedColumn.field, - newValue: this.editedColumn.newValue, - lines: rowsToEdit - }; - - if (this.checkedDummyCount && this.checkedDummyCount > 0) { - const params = {}; - if (this.$.model.userParams) { - const userParams = this.$.model.userParams; - for (let param in userParams) { - let newParam = this.exprBuilder(param, userParams[param]); - if (!newParam) - newParam = {[param]: userParams[param]}; - Object.assign(params, newParam); - } - } - if (this.$.model.userFilter) - Object.assign(params, this.$.model.userFilter.where); - - data.filter = params; - } - - return this.$http.post('Buys/editLatestBuys', data) - .then(() => { - this.uncheck(); - this.$.model.refresh(); - }); - } -} - -ngModule.component('vnEntryLatestBuys', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/entry/front/latest-buys/index.spec.js b/modules/entry/front/latest-buys/index.spec.js deleted file mode 100644 index 6574303fc..000000000 --- a/modules/entry/front/latest-buys/index.spec.js +++ /dev/null @@ -1,100 +0,0 @@ -import './index.js'; - -describe('Entry', () => { - describe('Component vnEntryLatestBuys', () => { - let controller; - let $httpBackend; - - beforeEach(ngModule('entry')); - - beforeEach(angular.mock.inject(($componentController, $rootScope, _$httpBackend_) => { - $httpBackend = _$httpBackend_; - const $element = angular.element(' {}}, - edit: {hide: () => {}} - }; - })); - - describe('get columns', () => { - it(`should return a set of columns`, () => { - let result = controller.columns; - - let length = result.length; - let anyColumn = Object.keys(result[Math.floor(Math.random() * Math.floor(length))]); - - expect(anyColumn).toContain('field', 'displayName'); - }); - }); - - describe('get checked', () => { - it(`should return a set of checked lines`, () => { - controller.$.model.data = [ - {checked: true, id: 1}, - {checked: true, id: 2}, - {checked: true, id: 3}, - {checked: false, id: 4}, - ]; - - let result = controller.checked; - - expect(result.length).toEqual(3); - }); - }); - - describe('onEditAccept()', () => { - it(`should perform a query to update columns`, () => { - controller.editedColumn = {field: 'my field', newValue: 'the new value'}; - const query = 'Buys/editLatestBuys'; - - $httpBackend.expectPOST(query).respond(); - controller.onEditAccept(); - $httpBackend.flush(); - - const result = controller.checked; - - expect(result.length).toEqual(0); - }); - }); - - describe('reCheck()', () => { - it(`should recheck buys`, () => { - controller.$.model.data = [ - {checked: false, id: 1}, - {checked: false, id: 2}, - {checked: false, id: 3}, - {checked: false, id: 4}, - ]; - controller.checkedBuys = [1, 2]; - - controller.reCheck(); - - expect(controller.$.model.data[0].checked).toEqual(true); - expect(controller.$.model.data[1].checked).toEqual(true); - expect(controller.$.model.data[2].checked).toEqual(false); - expect(controller.$.model.data[3].checked).toEqual(false); - }); - }); - - describe('saveChecked()', () => { - it(`should check buy`, () => { - const buyCheck = 3; - controller.checkedBuys = [1, 2]; - - controller.saveChecked(buyCheck); - - expect(controller.checkedBuys[2]).toEqual(buyCheck); - }); - - it(`should uncheck buy`, () => { - const buyUncheck = 3; - controller.checkedBuys = [1, 2, 3]; - - controller.saveChecked(buyUncheck); - - expect(controller.checkedBuys[2]).toEqual(undefined); - }); - }); - }); -}); diff --git a/modules/entry/front/latest-buys/locale/en.yml b/modules/entry/front/latest-buys/locale/en.yml deleted file mode 100644 index 48dda861b..000000000 --- a/modules/entry/front/latest-buys/locale/en.yml +++ /dev/null @@ -1,2 +0,0 @@ -Minimun amount: Minimun purchase quantity -PackageName: Package \ No newline at end of file diff --git a/modules/entry/front/latest-buys/locale/es.yml b/modules/entry/front/latest-buys/locale/es.yml deleted file mode 100644 index 795e3f5f4..000000000 --- a/modules/entry/front/latest-buys/locale/es.yml +++ /dev/null @@ -1,19 +0,0 @@ -Edit buy(s): Editar compra(s) -Buying value: Coste -Freight value: Porte -Commission value: Comisión -Package value: Embalaje -Is ignored: Ignorado -Is visible: Visible -Is floramondo: Floramondo -Grouping price: Precio grouping -Packing price: Precio packing -Min price: Precio min -Ekt: Ekt -Weight: Peso -Minimun amount: Cantidad mínima de compra -Field to edit: Campo a editar -PackageName: Cubo -Edit: Editar -buy(s): compra(s) -Package out: Embalaje envíos diff --git a/modules/entry/front/latest-buys/style.scss b/modules/entry/front/latest-buys/style.scss deleted file mode 100644 index a3c399edc..000000000 --- a/modules/entry/front/latest-buys/style.scss +++ /dev/null @@ -1,7 +0,0 @@ -.countLines { - flex: 0.15; - font-size: 24px; - color: orangered; - font-weight: bold; - max-width: 30px; -} diff --git a/modules/entry/front/locale/es.yml b/modules/entry/front/locale/es.yml deleted file mode 100644 index b28cbe735..000000000 --- a/modules/entry/front/locale/es.yml +++ /dev/null @@ -1,6 +0,0 @@ -#Ordenar alfabeticamente - -entry: entrada -Latest buys: Últimas compras - -# Sections diff --git a/modules/entry/front/log/index.html b/modules/entry/front/log/index.html deleted file mode 100644 index fd8ae7c2a..000000000 --- a/modules/entry/front/log/index.html +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/modules/entry/front/log/index.js b/modules/entry/front/log/index.js deleted file mode 100644 index 73218f4de..000000000 --- a/modules/entry/front/log/index.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -ngModule.vnComponent('vnEntryLog', { - template: require('./index.html'), - controller: Section, -}); diff --git a/modules/entry/front/log/locale/es.yml b/modules/entry/front/log/locale/es.yml deleted file mode 100644 index 094615b47..000000000 --- a/modules/entry/front/log/locale/es.yml +++ /dev/null @@ -1 +0,0 @@ -Date: Fecha \ No newline at end of file diff --git a/modules/entry/front/main/index.html b/modules/entry/front/main/index.html deleted file mode 100644 index d55fbd60b..000000000 --- a/modules/entry/front/main/index.html +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/modules/entry/front/main/index.js b/modules/entry/front/main/index.js deleted file mode 100644 index 69bddc7fc..000000000 --- a/modules/entry/front/main/index.js +++ /dev/null @@ -1,11 +0,0 @@ -import ngModule from '../module'; -import ModuleMain from 'salix/components/module-main'; - -export default class Entry extends ModuleMain { - -} - -ngModule.vnComponent('vnEntry', { - controller: Entry, - template: require('./index.html') -}); diff --git a/modules/entry/front/note/index.html b/modules/entry/front/note/index.html deleted file mode 100644 index 5f3c7f77e..000000000 --- a/modules/entry/front/note/index.html +++ /dev/null @@ -1,72 +0,0 @@ - - - - - - -
- - - - - - - - - - - - - - - - - - - - - - - - -
\ No newline at end of file diff --git a/modules/entry/front/note/index.js b/modules/entry/front/note/index.js deleted file mode 100644 index fccd60913..000000000 --- a/modules/entry/front/note/index.js +++ /dev/null @@ -1,20 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -class Controller extends Section { - onSubmit() { - this.$.watcher.check(); - this.$.model.save().then(() => { - this.$.watcher.notifySaved(); - this.$.watcher.updateOriginalData(); - }); - } -} - -ngModule.vnComponent('vnEntryObservation', { - template: require('./index.html'), - controller: Controller, - bindings: { - entry: '<' - } -}); diff --git a/modules/entry/front/routes.json b/modules/entry/front/routes.json index 3934a96ee..53c599cf1 100644 --- a/modules/entry/front/routes.json +++ b/modules/entry/front/routes.json @@ -8,12 +8,6 @@ "main": [ {"state": "entry.index", "icon": "icon-entry"}, {"state": "entry.latestBuys", "icon": "contact_support"} - ], - "card": [ - {"state": "entry.card.basicData", "icon": "settings"}, - {"state": "entry.card.buy.index", "icon": "icon-lines"}, - {"state": "entry.card.observation", "icon": "insert_drive_file"}, - {"state": "entry.card.log", "icon": "history"} ] }, "keybindings": [ @@ -33,90 +27,6 @@ "component": "vn-entry-index", "description": "Entries", "acl": ["buyer", "administrative"] - }, - { - "url": "/latest-buys?q", - "state": "entry.latestBuys", - "component": "vn-entry-latest-buys", - "description": "Latest buys", - "acl": ["buyer", "administrative"] - }, - { - "url": "/create?supplierFk&travelFk&companyFk", - "state": "entry.create", - "component": "vn-entry-create", - "description": "New entry", - "acl": ["buyer", "administrative"] - }, - { - "url": "/:id", - "state": "entry.card", - "abstract": true, - "component": "vn-entry-card" - }, - { - "url": "/summary", - "state": "entry.card.summary", - "component": "vn-entry-summary", - "description": "Summary", - "params": { - "entry": "$ctrl.entry" - }, - "acl": ["buyer", "administrative"] - }, - { - "url": "/basic-data", - "state": "entry.card.basicData", - "component": "vn-entry-basic-data", - "description": "Basic data", - "params": { - "entry": "$ctrl.entry" - }, - "acl": ["buyer", "administrative"] - }, - { - "url": "/observation", - "state": "entry.card.observation", - "component": "vn-entry-observation", - "description": "Notes", - "params": { - "entry": "$ctrl.entry" - }, - "acl": ["buyer", "administrative"] - }, - { - "url" : "/log", - "state": "entry.card.log", - "component": "vn-entry-log", - "description": "Log", - "acl": ["buyer", "administrative"] - }, - { - "url": "/buy", - "state": "entry.card.buy", - "abstract": true, - "component": "ui-view", - "acl": ["buyer"] - }, - { - "url" : "/index", - "state": "entry.card.buy.index", - "component": "vn-entry-buy-index", - "description": "Buys", - "params": { - "entry": "$ctrl.entry" - }, - "acl": ["buyer", "administrative"] - }, - { - "url" : "/import", - "state": "entry.card.buy.import", - "component": "vn-entry-buy-import", - "description": "Import buys", - "params": { - "entry": "$ctrl.entry" - }, - "acl": ["buyer"] } ] -} \ No newline at end of file +} diff --git a/modules/entry/front/search-panel/index.html b/modules/entry/front/search-panel/index.html deleted file mode 100644 index adcb9d6d4..000000000 --- a/modules/entry/front/search-panel/index.html +++ /dev/null @@ -1,100 +0,0 @@ -
-
- - - - - - - - - - - - - - - - - - - - - - - {{name}}: {{nickname}} - - - - - - - - - - - - - - - - - - - - - -
-
\ No newline at end of file diff --git a/modules/entry/front/search-panel/index.js b/modules/entry/front/search-panel/index.js deleted file mode 100644 index e87f31056..000000000 --- a/modules/entry/front/search-panel/index.js +++ /dev/null @@ -1,7 +0,0 @@ -import ngModule from '../module'; -import SearchPanel from 'core/components/searchbar/search-panel'; - -ngModule.vnComponent('vnEntrySearchPanel', { - template: require('./index.html'), - controller: SearchPanel -}); diff --git a/modules/entry/front/search-panel/locale/es.yml b/modules/entry/front/search-panel/locale/es.yml deleted file mode 100644 index 05b71da99..000000000 --- a/modules/entry/front/search-panel/locale/es.yml +++ /dev/null @@ -1,9 +0,0 @@ -Ticket id: Id ticket -Client id: Id cliente -Nickname: Alias -From: Desde -To: Hasta -Agency: Agencia -Warehouse: Almacén -Search entry by id or a suppliers by name or alias: Buscar entrada por id o proveedores por nombre y alias -Invoice number: Núm. factura \ No newline at end of file diff --git a/modules/entry/front/summary/index.html b/modules/entry/front/summary/index.html deleted file mode 100644 index baa310bb6..000000000 --- a/modules/entry/front/summary/index.html +++ /dev/null @@ -1,196 +0,0 @@ - - - -
- - - - #{{$ctrl.entryData.id}} - {{$ctrl.entryData.supplier.nickname}} -
- - - - - - - - - - - - - - - - - {{$ctrl.entryData.travel.ref}} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Buys

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
QuantityStickersPackageWeightPackingGroupingBuying valueImportPVP
{{::line.quantity}}{{::line.stickers | dashIfEmpty}}{{::line.packagingFk | dashIfEmpty}}{{::line.weight}} - - {{::line.packing | dashIfEmpty}} - - - - {{::line.grouping | dashIfEmpty}} - - - {{::line.buyingValue | currency: 'EUR':2}}{{::line.quantity * line.buyingValue | currency: 'EUR':2}}{{::line.price2 | currency: 'EUR':2 | dashIfEmpty}} / {{::line.price3 | currency: 'EUR':2 | dashIfEmpty}}
- - {{::line.item.itemType.code}} - - - - {{::line.item.id}} - - - - {{::line.item.size}} - - - - {{::line.item.minPrice | currency: 'EUR':2}} - - -
- {{::line.item.name}} - -

{{::line.item.subName}}

-
-
- - -
- - -
-
-
- - - - - diff --git a/modules/entry/front/summary/index.js b/modules/entry/front/summary/index.js deleted file mode 100644 index 6e18bc959..000000000 --- a/modules/entry/front/summary/index.js +++ /dev/null @@ -1,33 +0,0 @@ -import ngModule from '../module'; -import './style.scss'; -import Summary from 'salix/components/summary'; - -class Controller extends Summary { - get entry() { - if (!this._entry) - return this.$params; - - return this._entry; - } - - set entry(value) { - this._entry = value; - - if (value && value.id) - this.getEntryData(); - } - - getEntryData() { - return this.$http.get(`Entries/${this.entry.id}/getEntry`).then(response => { - this.entryData = response.data; - }); - } -} - -ngModule.vnComponent('vnEntrySummary', { - template: require('./index.html'), - controller: Controller, - bindings: { - entry: '<' - } -}); diff --git a/modules/entry/front/summary/index.spec.js b/modules/entry/front/summary/index.spec.js deleted file mode 100644 index baeb43ac8..000000000 --- a/modules/entry/front/summary/index.spec.js +++ /dev/null @@ -1,49 +0,0 @@ -import './index'; - -describe('component vnEntrySummary', () => { - let controller; - let $httpBackend; - let $scope; - - beforeEach(angular.mock.module('entry', $translateProvider => { - $translateProvider.translations('en', {}); - })); - - beforeEach(inject(($componentController, $rootScope, _$httpBackend_, _$httpParamSerializer_) => { - $httpBackend = _$httpBackend_; - $scope = $rootScope.$new(); - const $element = angular.element(``); - controller = $componentController('vnEntrySummary', {$element, $scope}); - })); - - describe('entry setter/getter', () => { - it('should check if value.id is defined', () => { - jest.spyOn(controller, 'getEntryData'); - - controller.entry = {id: 1}; - - expect(controller.getEntryData).toHaveBeenCalledWith(); - }); - - it('should return the entry and then call getEntryData()', () => { - jest.spyOn(controller, 'getEntryData'); - controller.entry = {id: 99}; - - expect(controller._entry.id).toEqual(99); - expect(controller.getEntryData).toHaveBeenCalledWith(); - }); - }); - - describe('getEntryData()', () => { - it('should perform a get and then store data on the controller', () => { - controller._entry = {id: 999}; - - const query = `Entries/${controller._entry.id}/getEntry`; - $httpBackend.expectGET(query).respond('I am the entryData'); - controller.getEntryData(); - $httpBackend.flush(); - - expect(controller.entryData).toEqual('I am the entryData'); - }); - }); -}); diff --git a/modules/entry/front/summary/locale/es.yml b/modules/entry/front/summary/locale/es.yml deleted file mode 100644 index 1761561ed..000000000 --- a/modules/entry/front/summary/locale/es.yml +++ /dev/null @@ -1,11 +0,0 @@ -Inventory: Inventario -Raid: Redada -Entry: Entrada -Stickers: Etiquetas -Item size: Tamaño -Item type: Tipo -Minimum price: Precio mínimo -Buys: Compras -Travel: Envio -Go to the entry: Ir a la entrada -Invoice number: Núm. factura diff --git a/modules/entry/front/summary/style.scss b/modules/entry/front/summary/style.scss deleted file mode 100644 index 1d5b22e30..000000000 --- a/modules/entry/front/summary/style.scss +++ /dev/null @@ -1,30 +0,0 @@ -@import "variables"; - - -vn-entry-summary .summary { - max-width: $width-lg; - - .dark-row { - background-color: lighten($color-marginal, 10%); - } - - tbody tr:nth-child(1) { - border-top: $border-thin; - } - - tbody tr:nth-child(1), - tbody tr:nth-child(2) { - border-left: $border-thin; - border-right: $border-thin - } - - tbody tr:nth-child(3) { - height: inherit - } - - tr { - margin-bottom: 10px; - } -} - -$color-font-link-medium: lighten($color-font-link, 20%) \ No newline at end of file diff --git a/modules/item/front/routes.json b/modules/item/front/routes.json index 3dea69ba1..4b7cd1490 100644 --- a/modules/item/front/routes.json +++ b/modules/item/front/routes.json @@ -3,7 +3,7 @@ "name": "Items", "icon": "icon-item", "validations" : true, - "dependencies": ["worker", "client", "ticket", "entry"], + "dependencies": ["worker", "client", "ticket"], "menus": { "main": [ {"state": "item.index", "icon": "icon-item"}, @@ -19,8 +19,8 @@ {"state": "item.card.tax", "icon": "icon-tax"}, {"state": "item.card.botanical", "icon": "local_florist"}, {"state": "item.card.shelving", "icon": "icon-inventory"}, - {"state": "item.card.itemBarcode", "icon": "icon-barcode"}, - {"state": "item.card.diary", "icon": "icon-transaction"}, + {"state": "item.card.itemBarcode", "icon": "icon-barcode"}, + {"state": "item.card.diary", "icon": "icon-transaction"}, {"state": "item.card.log", "icon": "history"} ], "itemType": [ @@ -227,4 +227,4 @@ "acl": ["buyer"] } ] -} \ No newline at end of file +} diff --git a/modules/travel/front/routes.json b/modules/travel/front/routes.json index b2e438c6d..5a63620d4 100644 --- a/modules/travel/front/routes.json +++ b/modules/travel/front/routes.json @@ -3,7 +3,7 @@ "name": "Travels", "icon": "local_airport", "validations": true, - "dependencies": ["worker", "entry"], + "dependencies": ["worker"], "menus": { "main": [ {"state": "travel.index", "icon": "local_airport"}, @@ -45,7 +45,7 @@ "state": "travel.card.basicData", "component": "vn-travel-basic-data", "description": "Basic data", - "acl": ["buyer","logistic"], + "acl": ["buyer","logistic"], "params": { "travel": "$ctrl.travel" } @@ -97,10 +97,10 @@ "state": "travel.extraCommunity", "component": "vn-travel-extra-community", "description": "Extra community", - "acl": ["buyer"], + "acl": ["buyer"], "params": { "travel": "$ctrl.travel" } } ] -} \ No newline at end of file +} -- 2.40.1 From 96a3a2e69b2349ba13cd96d57af6df75c92b45a0 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 7 Jun 2024 11:50:16 +0200 Subject: [PATCH 146/413] fix: refs #6243 rollback --- db/dump/.dump/data.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index 778f6f23b..3be9dd4f5 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -1842,7 +1842,7 @@ INSERT INTO `ACL` VALUES (761,'Route','downloadZip','READ','ALLOW','ROLE','emplo INSERT INTO `ACL` VALUES (762,'Route','filter','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (763,'Route','getByWorker','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (764,'Route','getDeliveryPoint','READ','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (765,'Route','cmrs','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (765,'Route','getExternalCmrs','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (766,'Route','getSuggestedTickets','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (767,'Route','getTickets','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (768,'Route','guessPriority','WRITE','ALLOW','ROLE','employee'); -- 2.40.1 From 521f3f14469ce825c2026c213675d2ff66b65ea6 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 7 Jun 2024 11:52:24 +0200 Subject: [PATCH 147/413] feat: refs #6243 update ACL --- db/versions/11093-purpleGerbera/00-firstScript.sql | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 db/versions/11093-purpleGerbera/00-firstScript.sql diff --git a/db/versions/11093-purpleGerbera/00-firstScript.sql b/db/versions/11093-purpleGerbera/00-firstScript.sql new file mode 100644 index 000000000..024b0bb59 --- /dev/null +++ b/db/versions/11093-purpleGerbera/00-firstScript.sql @@ -0,0 +1,4 @@ +UPDATE salix.ACL + SET property = 'cmrs' + WHERE property = 'getExternalCmrs' + AND model = 'Route'; \ No newline at end of file -- 2.40.1 From 479e4f3f8a27e2974626199a4564a5a2739299a5 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 7 Jun 2024 13:55:56 +0200 Subject: [PATCH 148/413] feat: refs #6273 required payMethod for internals --- loopback/locale/es.json | 7 ++++--- modules/worker/back/methods/worker/new.js | 3 +-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index e876c1bbb..714475374 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -359,10 +359,11 @@ "Select ticket or client": "Elija un ticket o un client", "It was not able to create the invoice": "No se pudo crear la factura", "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)", - "Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE", + "Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE", "You can not use the same password": "No puedes usar la misma contraseña", "This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario", "You can only have one PDA": "Solo puedes tener un PDA", "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", - "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono" -} + "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", + "Payment method is required": "El método de pago es obligatorio" +} \ No newline at end of file diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 4a4bd9449..ba9dc3853 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -129,8 +129,7 @@ module.exports = Self => { const nickname = firstName.concat(' ', lastNames); const {roleFk, businessTypeFk} = await models.WorkerConfig.findOne({fields: ['roleFk', 'businessTypeFk']}); - if (!isFreelance) - if (!payMethodFk) throw new UserError('Payment method is required'); + if (!isFreelance && !payMethodFk) throw new UserError('Payment method is required'); if (isFreelance || !client) { const [{password}] = await models.Worker.rawSql('SELECT account.passwordGenerate() as password;'); -- 2.40.1 From cac1278c080451d9760d4f48f7dadd0a9e066945 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 7 Jun 2024 16:29:51 +0200 Subject: [PATCH 149/413] feat hsItemOlder refs $6964 --- .../11064-grayMedeola/00-firstScript.sql | 3 +- loopback/locale/es.json | 3 +- .../methods/item-shelving/getListItemNewer.js | 68 +++++++++++++++++++ .../methods/item-shelving/hasItemOlder.js | 68 ------------------- .../specs/getListItemNewer.spec.js | 40 +++++++++++ .../item-shelving/specs/hasItemOlder.spec.js | 45 ------------ modules/item/back/models/item-shelving.js | 2 +- 7 files changed, 112 insertions(+), 117 deletions(-) create mode 100644 modules/item/back/methods/item-shelving/getListItemNewer.js delete mode 100644 modules/item/back/methods/item-shelving/hasItemOlder.js create mode 100644 modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js delete mode 100644 modules/item/back/methods/item-shelving/specs/hasItemOlder.spec.js diff --git a/db/versions/11064-grayMedeola/00-firstScript.sql b/db/versions/11064-grayMedeola/00-firstScript.sql index 301c0fef1..b5af3599b 100644 --- a/db/versions/11064-grayMedeola/00-firstScript.sql +++ b/db/versions/11064-grayMedeola/00-firstScript.sql @@ -2,5 +2,4 @@ USE vn; -ALTER TABLE vn.sector ADD hasItemOlderReview BIGINT DEFAULT false NULL COMMENT 'Indica si el sector se revisa para comprobar si tiene ítems más viejos'; -ALTER TABLE vn.productionConfig ADD itemOlderReviewHours int(11) NULL COMMENT 'Horas que se tienen en cuenta para comprobar si un ítem es más viejo.'; +ALTER TABLE vn.productionConfig ADD itemOlderReviewHours int(11) DEFAULT 0 NOT NULL COMMENT 'Horas que se tienen en cuenta para comprobar si un ítem es más viejo.'; diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 77e707590..8244deb8a 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -358,5 +358,6 @@ "Select ticket or client": "Elija un ticket o un client", "It was not able to create the invoice": "No se pudo crear la factura", "This PDA is already assigned to another user": "This PDA is already assigned to another user", - "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)" + "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)", + "parkingNotExist": "parkingNotExist" } \ No newline at end of file diff --git a/modules/item/back/methods/item-shelving/getListItemNewer.js b/modules/item/back/methods/item-shelving/getListItemNewer.js new file mode 100644 index 000000000..a6ab0e5f1 --- /dev/null +++ b/modules/item/back/methods/item-shelving/getListItemNewer.js @@ -0,0 +1,68 @@ +module.exports = Self => { + Self.remoteMethod('getListItemNewer', { + description: + 'Get boolean if any or specific item of the shelving has older created in another shelving or parking', + accessType: 'READ', + accepts: [{ + arg: 'shelvingFk', + type: 'string', + required: true, + description: 'Shelving code' + }, + { + arg: 'parking', + type: 'string', + required: true, + description: 'Parking code' + }, + ], + returns: { + type: 'Object', + root: true + }, + http: { + path: `/getListItemNewer`, + verb: 'GET' + } + }); + + Self.getListItemNewer = async(shelvingFk, parking, options) => { + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const isParkingToReview = await Self.rawSql(` + SELECT COUNT(p.id) parkingToReview + FROM vn.parking p + JOIN vn.sector s ON s.id = p.sectorFk + WHERE p.code = ? AND s.code = "CAMARA SECTOR D";`, + [parking], myOptions); + + if (isParkingToReview[0]['parkingToReview'] > 0) { + const result = await Self.rawSql(` + WITH tItemShelving AS( + SELECT is2.itemFk, is2.created, p.sectorFK, is2.id + FROM vn.itemShelving is2 + JOIN vn.shelving sh ON sh.code = is2.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + WHERE is2.shelvingFk = ? AND s.code = "NAVE ALGEMESI" + ), tItemInSector AS ( + SELECT is2.itemFk, is2.created, is2.shelvingFk + FROM vn.itemShelving is2 + JOIN vn.shelving sh ON sh.code = is2.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk + WHERE is2.shelvingFk <> ? + AND s.code = "NAVE ALGEMESI") + SELECT ti.itemFK, tis.shelvingFk + FROM tItemShelving ti + JOIN tItemInSector tis ON tis.itemFk = ti.itemFk + JOIN vn.productionConfig pc + WHERE ti.created > tis.created + INTERVAL pc.itemOlderReviewHours HOUR;`, + [shelvingFk, shelvingFk], myOptions); + return result; + } else + return []; + }; +}; diff --git a/modules/item/back/methods/item-shelving/hasItemOlder.js b/modules/item/back/methods/item-shelving/hasItemOlder.js deleted file mode 100644 index 9bea6fbe9..000000000 --- a/modules/item/back/methods/item-shelving/hasItemOlder.js +++ /dev/null @@ -1,68 +0,0 @@ -const UserError = require('vn-loopback/util/user-error'); -module.exports = Self => { - Self.remoteMethod('hasItemOlder', { - description: - 'Get boolean if any or specific item of the shelving has older created in another shelving or parking', - accessType: 'READ', - accepts: [{ - arg: 'shelvingFkIn', - type: 'string', - required: true, - description: 'Shelving code' - }, - { - arg: 'parking', - type: 'string', - description: 'Parking code' - }, - { - arg: 'shelvingFkOut', - type: 'string', - description: 'Shelving code' - }, - { - arg: 'itemFk', - type: 'integer', - description: 'Item id' - }], - returns: { - type: 'boolean', - root: true - }, - http: { - path: `/hasItemOlder`, - verb: 'GET' - } - }); - - Self.hasItemOlder = async(shelvingFkIn, parking, shelvingFkOut, itemFk, options) => { - if (!parking && !shelvingFkOut) throw new UserError('Missing data: parking or shelving'); - - const myOptions = {}; - if (typeof options == 'object') - Object.assign(myOptions, options); - - const result = await Self.rawSql(` - SELECT COUNT(ish.id) countItemOlder - FROM vn.itemShelving ish - JOIN ( - SELECT ish.itemFk, created, shelvingFk, pickingOrder - FROM vn.itemShelving ish - JOIN vn.shelving s ON ish.shelvingFk = s.code - LEFT JOIN vn.parking p2 ON p2.id = s.parkingFk - WHERE ish.shelvingFk = ? - )sub ON sub.itemFK = ish.itemFk - JOIN vn.shelving s ON s.code = ish.shelvingFk - JOIN vn.parking p ON p.id = s.parkingFk - JOIN vn.sector s2 ON s2.id = p.sectorFk - JOIN vn.productionConfig pc ON pc.itemOlderReviewHours - WHERE ish.created + INTERVAL pc.itemOlderReviewHours HOUR < sub.created - AND (p.code <> ? OR ? IS NULL) - AND (ish.shelvingFk <> ? OR ? IS NULL) - AND (ish.itemFk = ? OR ? IS NULL) - AND (p.pickingOrder < sub.pickingOrder OR sub.pickingOrder IS NULL) - AND (s2.hasItemOlderReview)`, - [shelvingFkIn, parking, parking, shelvingFkOut, shelvingFkOut, itemFk, itemFk], myOptions); - return result[0]['countItemOlder'] > 0; - }; -}; diff --git a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js new file mode 100644 index 000000000..5f0f7d826 --- /dev/null +++ b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js @@ -0,0 +1,40 @@ + +const {models} = require('vn-loopback/server/server'); + +describe('itemShelving getListItemNewer()', () => { + fit('should return true because there is an older item', async() => { + const shelving = 'NCC'; + const parking = 'A-47-1'; + const sectorCam = 1; + const sectorCamCode = 'CAMARA SECTOR D'; + const sectorCamHigh = 9991; + const sectorCamHighCode = 'NAVE ALGEMESI'; + + const tx = await models.Sector.beginTransaction({}); + const myOptions = {transaction: tx}; + + const filter = {where: {id: sectorCam}}; + const filterHigh = {where: {id: sectorCamHigh}}; + + try { + const sectorCamBefore = await models.Sector.findOne(filter, myOptions); + + await sectorCamBefore.updateAttributes({ + code: sectorCamCode + }, myOptions); + + const sectorCamHighBefore = await models.Sector.findOne(filterHigh, myOptions); + await sectorCamHighBefore.updateAttributes({ + code: sectorCamHighCode + }, myOptions); + + const result = await models.ItemShelving.getListItemNewer(shelving, parking, myOptions); + + expect(result.length).toEqual(2); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/modules/item/back/methods/item-shelving/specs/hasItemOlder.spec.js b/modules/item/back/methods/item-shelving/specs/hasItemOlder.spec.js deleted file mode 100644 index abffead53..000000000 --- a/modules/item/back/methods/item-shelving/specs/hasItemOlder.spec.js +++ /dev/null @@ -1,45 +0,0 @@ - -const {models} = require('vn-loopback/server/server'); - -describe('itemShelving hasOlder()', () => { - it('should return false because there are not older items', async() => { - const shelvingFkIn = 'GVC'; - const shelvingFkOut = 'HEJ'; - const result = await models.ItemShelving.hasItemOlder(shelvingFkIn, null, shelvingFkOut); - - expect(result).toBe(false); - }); - - it('should return false because there are not older items in parking', async() => { - const shelvingFkIn = 'HEJ'; - const parking = '700-01'; - const result = await models.ItemShelving.hasItemOlder(shelvingFkIn, parking); - - expect(result).toBe(false); - }); - - it('should return true because there is an older item', async() => { - const shelvingFkIn = 'UXN'; - const shelvingFkOut = 'PCC'; - const parking = 'A-01-1'; - const itemFk = 1; - - const tx = await models.ItemShelving.beginTransaction({}); - const myOptions = {transaction: tx}; - const filter = {where: {shelvingFk: shelvingFkOut} - }; - try { - const itemShelvingBefore = await models.ItemShelving.findOne(filter, myOptions); - await itemShelvingBefore.updateAttributes({ - itemFk: itemFk - }, myOptions); - const result = await models.ItemShelving.hasItemOlder(shelvingFkIn, parking, null, null, myOptions); - - expect(result).toBe(true); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -}); diff --git a/modules/item/back/models/item-shelving.js b/modules/item/back/models/item-shelving.js index d48ee10d5..be72dac37 100644 --- a/modules/item/back/models/item-shelving.js +++ b/modules/item/back/models/item-shelving.js @@ -4,5 +4,5 @@ module.exports = Self => { require('../methods/item-shelving/getInventory')(Self); require('../methods/item-shelving/getAlternative')(Self); require('../methods/item-shelving/updateFromSale')(Self); - require('../methods/item-shelving/hasItemOlder')(Self); + require('../methods/item-shelving/getListItemNewer')(Self); }; -- 2.40.1 From 4cf5c0775c672439c9584391cbfe2d3e04e6962e Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 10 Jun 2024 07:30:33 +0200 Subject: [PATCH 150/413] feat isScannedExpedition refs #7276 --- db/routines/vn/procedures/expedition_getFromRoute.sql | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/expedition_getFromRoute.sql b/db/routines/vn/procedures/expedition_getFromRoute.sql index 3742ef4fb..2b726fa7d 100644 --- a/db/routines/vn/procedures/expedition_getFromRoute.sql +++ b/db/routines/vn/procedures/expedition_getFromRoute.sql @@ -16,7 +16,7 @@ BEGIN a.nickname, sub2.itemPackingTypeConcat, est.code, - sub5.isScanned + es.isScanned FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = e.ticketFk @@ -34,11 +34,10 @@ BEGIN GROUP BY sub.ticketFk ) sub2 ON sub2.ticketFk = t.id LEFT JOIN expeditionStateType est ON est.id = e.stateTypeFk - LEFT JOIN (SELECT es.expeditionFk, isScanned - FROM expeditionState es - JOIN (SELECT expeditionFk, MAX(id) maxId - FROM expeditionState es - GROUP BY expeditionFk)sub4 ON sub4.maxId = es.id)sub5 ON sub5.expeditionFk = e.id + LEFT JOIN expeditionState es ON es.id = ( + SELECT MAX(id) + FROM expeditionState es + WHERE expeditionFk = e.id) WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE ORDER BY r.created, t.priority DESC; END$$ -- 2.40.1 From 9b21cd5eb1e52712e34d0a7ae3941ff3c8dad612 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 10 Jun 2024 08:38:58 +0200 Subject: [PATCH 151/413] refactor: refs #7490 Deleted update duaInvoiceInBooking --- .../vn/procedures/duaInvoiceInBooking.sql | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index 8b4df6a73..018c72e0e 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -1,5 +1,7 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaInvoiceInBooking`(vDuaFk INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaInvoiceInBooking`( + vDuaFk INT +) BEGIN /** * Genera el asiento de un DUA y marca las entradas como confirmadas @@ -22,18 +24,6 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - UPDATE invoiceIn ii - JOIN entry e ON e.invoiceInFk = ii.id - JOIN duaEntry de ON de.entryFk = e.id - JOIN dua d ON d.id = de.duaFk - SET ii.booked = IFNULL(ii.booked, d.booked), - ii.operated = IFNULL(ii.operated, d.operated), - ii.issued = IFNULL(ii.issued, d.issued), - ii.bookEntried = IFNULL(ii.bookEntried, d.bookEntried), - e.isBooked = TRUE, - e.isConfirmed = TRUE - WHERE d.id = vDuaFk; - SELECT ASIEN INTO vBookEntry FROM dua WHERE id = vDuaFk; IF vBookEntry IS NULL THEN -- 2.40.1 From fb4be69cf12737ef71bc29a2ee24a20f9e3b32ee Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 10 Jun 2024 08:47:02 +0200 Subject: [PATCH 152/413] refactor: refs #7490 Added final update --- .../vn/procedures/duaInvoiceInBooking.sql | 33 ++++++++++++++++--- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index 018c72e0e..9cbf54b4a 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -4,10 +4,10 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaInvoiceInBooking ) BEGIN /** - * Genera el asiento de un DUA y marca las entradas como confirmadas - * - * @param vDuaFk Id del dua a recalcular - */ +* Genera el asiento de un DUA y marca las entradas como confirmadas +* +* @param vDuaFk Id del dua a recalcular +*/ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; DECLARE vBookEntry INT; @@ -29,7 +29,7 @@ BEGIN IF vBookEntry IS NULL THEN SELECT YEAR(IFNULL(ii.bookEntried, d.bookEntried)) INTO vFiscalYear FROM invoiceIn ii - JOIN entry e ON e.invoiceInFk = ii.id + JOIN `entry` e ON e.invoiceInFk = ii.id JOIN duaEntry de ON de.entryFk = e.id JOIN dua d ON d.id = de.duaFk WHERE d.id = vDuaFk @@ -60,5 +60,28 @@ l: LOOP JOIN duaInvoiceIn dii ON dii.invoiceInFk = ii.id SET ii.isBooked = TRUE WHERE dii.duaFk = vDuaFk; + + UPDATE `entry` e + JOIN ( + WITH entries AS ( + SELECT e.id, de.duaFk + FROM `entry` e + JOIN duaEntry de ON de.entryFk = e.id + WHERE de.duaFk = vDuaFk + AND (NOT e.isBooked OR NOT e.isConfirmed) + ), + notBookedEntries AS ( + SELECT e.id + FROM entries e + JOIN duaEntry de ON de.entryFk = e.id + JOIN dua d ON d.id = de.duaFk + WHERE d.ASIEN IS NULL) + SELECT e.id + FROM entries e + LEFT JOIN notBookedEntries nbe ON nbe.id = e.id + WHERE nbe.id IS NULL + ) sub ON sub.id = e.id + SET e.isBooked = TRUE, + e.isConfirmed = TRUE; END$$ DELIMITER ; -- 2.40.1 From 317f898c2eb1a63fea6bd0f024c1b136251b92ca Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 10 Jun 2024 08:48:56 +0200 Subject: [PATCH 153/413] refactor: refs #7490 Minor changes --- db/routines/vn/procedures/duaInvoiceInBooking.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index 9cbf54b4a..efaf29b41 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -4,10 +4,10 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`duaInvoiceInBooking ) BEGIN /** -* Genera el asiento de un DUA y marca las entradas como confirmadas -* -* @param vDuaFk Id del dua a recalcular -*/ + * Genera el asiento de un DUA y marca las entradas como confirmadas + * + * @param vDuaFk Id del dua a recalcular + */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; DECLARE vBookEntry INT; @@ -39,7 +39,7 @@ BEGIN OPEN vInvoicesIn; -l: LOOP + l: LOOP SET vDone = FALSE; FETCH vInvoicesIn INTO vInvoiceFk; -- 2.40.1 From 2e8d28d7959d0bdab9386813812700f36964e4d5 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 10 Jun 2024 09:08:26 +0200 Subject: [PATCH 154/413] refactor: refs #7517 Added throw --- db/routines/vn/procedures/buy_afterUpsert.sql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/db/routines/vn/procedures/buy_afterUpsert.sql b/db/routines/vn/procedures/buy_afterUpsert.sql index 17e84177c..8af53ddfb 100644 --- a/db/routines/vn/procedures/buy_afterUpsert.sql +++ b/db/routines/vn/procedures/buy_afterUpsert.sql @@ -47,6 +47,9 @@ BEGIN WHERE e.id = vEntryFk; IF vIsMerchandise THEN + IF vWarehouse IS NULL THEN + CALL util.throw('The entry does not have travel'); + END IF; REPLACE itemCost SET itemFk = vItemFk, -- 2.40.1 From ca7d67451b23bc95a586103e0e6f9b5310c5e97d Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 10 Jun 2024 09:09:11 +0200 Subject: [PATCH 155/413] refactor: refs #7517 Minor changes --- db/routines/vn/procedures/buy_afterUpsert.sql | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/db/routines/vn/procedures/buy_afterUpsert.sql b/db/routines/vn/procedures/buy_afterUpsert.sql index 8af53ddfb..76f60d1e5 100644 --- a/db/routines/vn/procedures/buy_afterUpsert.sql +++ b/db/routines/vn/procedures/buy_afterUpsert.sql @@ -1,5 +1,7 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_afterUpsert`(vSelf INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_afterUpsert`( + vSelf INT +) BEGIN /** * Triggered actions when a buy is updated or inserted. @@ -16,7 +18,7 @@ BEGIN DECLARE vIsFeedStock BOOL; DECLARE vWeight DECIMAL(10,2); DECLARE vPacking INT; - + SELECT b.entryFk, b.itemFk, i.packingOut, @@ -51,7 +53,7 @@ BEGIN CALL util.throw('The entry does not have travel'); END IF; - REPLACE itemCost SET + REPLACE itemCost SET itemFk = vItemFk, warehouseFk = vWarehouse, cm3 = buy_getUnitVolume(vSelf), @@ -77,7 +79,7 @@ BEGIN WHERE b.id = vSelf; END IF; - CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck + CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck SELECT vSelf id; CALL buy_checkItem(); END$$ -- 2.40.1 From b4820858c9bc6efc5dd547694b44889ddc40cae9 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 10 Jun 2024 11:32:44 +0200 Subject: [PATCH 156/413] hotfix: ticket 192672 ticketPreviousPreparingList --- db/routines/vn/views/ticketPreviousPreparingList.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/views/ticketPreviousPreparingList.sql b/db/routines/vn/views/ticketPreviousPreparingList.sql index 9c84b8af3..cd18b3a7c 100644 --- a/db/routines/vn/views/ticketPreviousPreparingList.sql +++ b/db/routines/vn/views/ticketPreviousPreparingList.sql @@ -20,7 +20,7 @@ FROM ( `vn`.`saleGroup` `sg` JOIN `vn`.`saleGroupDetail` `sgd` ON(`sgd`.`saleGroupFk` = `sg`.`id`) ) - JOIN `vn`.`sale` `s` ON(`s`.`id` = `sgd`.`saleFk`) + JOIN `vn`.`sale` `s` FORCE INDEX (PRIMARY) ON(`s`.`id` = `sgd`.`saleFk`) ) JOIN `vn`.`ticketState` `tls` ON(`tls`.`ticketFk` = `s`.`ticketFk`) ) -- 2.40.1 From 7579e15fcc483787885911b3a51b5133adfdb19f Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 10 Jun 2024 11:55:40 +0200 Subject: [PATCH 157/413] refactor: refs #7486 Optimized procs --- .../vn/procedures/productionControl.sql | 22 +++++++++++++------ .../vn/procedures/sale_getProblems.sql | 21 +++++++++++------- 2 files changed, 28 insertions(+), 15 deletions(-) diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index b42645d1e..423c06892 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -145,13 +145,19 @@ proc: BEGIN -- Líneas y volumen por ticket UPDATE tmp.productionBuffer pb JOIN ( - SELECT tt.ticketFk, - COUNT(*) `lines`, - SUM(sv.volume) m3, - IFNULL(SUM(IF(sv.isPicked, sv.volume, 0)) / SUM(sv.volume), 0) rate - FROM tmp.productionTicket tt - JOIN saleVolume sv ON sv.ticketFk = tt.ticketFk - GROUP BY tt.ticketFk + SELECT tt.ticketFk, + COUNT(*) `lines`, + SUM(s.quantity * ic.cm3delivery / 1000000) m3, + IFNULL(SUM(IF(s.isPicked, + (s.quantity * ic.cm3delivery / 1000000), + 0)) / SUM(s.quantity * ic.cm3delivery / 1000000), + 0) rate + FROM tmp.productionTicket tt + JOIN sale s ON s.ticketFk = tt.ticketFk + AND s.quantity > 0 + JOIN itemCost ic ON ic.itemFk = s.itemFk + AND ic.warehouseFk = vWarehouseFk + GROUP BY tt.ticketFk ) m ON m.ticketFk = pb.ticketFk SET pb.`lines` = m.`lines`, pb.m3 = m.m3, @@ -218,6 +224,8 @@ proc: BEGIN AND ish.visible GROUP BY ish.itemFk, p.sectorFk; + CREATE INDEX idxItem ON tItemShelvingStock (itemFk); + INSERT INTO tmp.ticketWithPrevia(ticketFk, salesCount) SELECT pb.ticketFk, COUNT(DISTINCT s.id) FROM tmp.productionBuffer pb diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index 98926b28b..9944ab0c2 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -64,10 +64,15 @@ BEGIN FROM tmp.sale_getProblems tp JOIN ticket t ON t.id = tp.ticketFk JOIN ( - SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat + SELECT t.addressFk, + SUM(ROUND(`ic`.`cm3delivery` * `s`.`quantity` / 1000, 0)) litros, + t.totalWithoutVat FROM tmp.ticket_list tl - JOIN saleVolume sv ON sv.ticketFk = tl.ticketFk JOIN ticket t ON t.id = tl.ticketFk + JOIN sale s ON s.ticketFk = t.id + AND s.quantity > 0 + JOIN itemCost ic ON ic.itemFk = s.itemFk + AND ic.warehouseFk = t.warehouseFk JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = util.VN_CURDATE() JOIN agencyMode am ON am.id = t.agencyModeFk @@ -95,12 +100,12 @@ BEGIN FROM ( SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk FROM tmp.ticket_list tl - JOIN vn.sale s ON s.ticketFk = tl.ticketFk - LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id - LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN sale s ON s.ticketFk = tl.ticketFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN component c ON c.id = sc.componentFk AND c.isRequired + JOIN ticket t ON t.id = tl.ticketFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP') AND s.quantity > 0 GROUP BY s.id -- 2.40.1 From c5227d6cf652515eb53c708d43862aadfd3fe9e3 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 10 Jun 2024 12:24:23 +0200 Subject: [PATCH 158/413] feat: refs #6404 add mail notification --- back/methods/mrw-config/createShipment.js | 73 ++++------ back/methods/mrw-config/getLabel.js | 27 ++++ .../mrw-config/specs/createShipment.spec.js | 133 ++++++++++++------ back/models/mrw-config.js | 31 ++++ back/models/mrw-config.json | 6 + .../11086-grayCataractarum/00-firstScript.sql | 3 + loopback/locale/es.json | 4 +- .../components/email-footer/email-footer.html | 8 +- .../assets/css/import.js | 11 ++ .../mrw-webService-deadline/locale/en.yml | 5 + .../mrw-webService-deadline/locale/es.yml | 5 + .../mrw-webService-deadline.html | 10 ++ .../mrw-webService-deadline.js | 9 ++ 13 files changed, 228 insertions(+), 97 deletions(-) create mode 100644 back/methods/mrw-config/getLabel.js create mode 100644 db/versions/11086-grayCataractarum/00-firstScript.sql create mode 100644 print/templates/email/mrw-webService-deadline/assets/css/import.js create mode 100644 print/templates/email/mrw-webService-deadline/locale/en.yml create mode 100644 print/templates/email/mrw-webService-deadline/locale/es.yml create mode 100644 print/templates/email/mrw-webService-deadline/mrw-webService-deadline.html create mode 100755 print/templates/email/mrw-webService-deadline/mrw-webService-deadline.js diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index b5bea648d..ca155919f 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -1,7 +1,4 @@ -const axios = require('axios'); -const {DOMParser} = require('xmldom'); -const fs = require('fs'); -const ejs = require('ejs'); +const {Email} = require('vn-print'); const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { @@ -23,24 +20,23 @@ module.exports = Self => { } }); - Self.createShipment = async(expeditionFk, options) => { - const myOptions = {}; - let tx; + Self.createShipment = async expeditionFk => { + const mrwConfig = Self.app.models.MrwConfig; + const mrw = await Self.getConfig(); - if (typeof options == 'object') - Object.assign(myOptions, options); + const today = Date.vnNew(); - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; + const [hours, minutes] = mrw?.expeditionDeadLine ? mrw.expeditionDeadLine.split(':').map(Number) : [0, 0]; + + const deadLine = Date.vnNew(); + deadLine.setHours(hours, minutes, 0); + + if (today > deadLine && (!mrw.notified || mrw.notified.setHours(0, 0, 0, 0) !== today.setHours(0, 0, 0, 0))) { + const email = new Email('mrw-webService-deadline', {recipient: 'agencias@verdnatura.es', lang: 'es'}); + await email.send(); + await mrw.updateAttributes({notified: Date.vnNow()}); } - const models = Self.app.models; - const mrw = await models.MrwConfig.findOne(null, myOptions); - - if (!mrw) - throw new UserError(`Some mrwConfig parameters are not set`); - const query = `SELECT CASE co.code @@ -64,7 +60,8 @@ module.exports = Self => { JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk JOIN mrwService ms ON ms.agencyModeCodeFk = am.code - LEFT JOIN mrwServiceWeekday mw ON mw.weekdays | 1 << WEEKDAY(t.landed) + LEFT JOIN mrwServiceWeekday mw ON mw.agencyModeCodeFk = am.code + AND mw.weekDays & (1 << WEEKDAY(t.landed)) JOIN client c ON t.clientFk = c.id JOIN address a ON t.addressFk = a.id LEFT JOIN addressObservation oa ON oa.addressFk = a.id @@ -76,44 +73,26 @@ module.exports = Self => { WHERE e.id = ? LIMIT 1`; - const [expeditionData] = await Self.rawSql(query, [expeditionFk], myOptions); + const [expeditionData] = await Self.rawSql(query, [expeditionFk]); if (!expeditionData) throw new UserError(`This expedition is not a MRW shipment`); - const today = Date.vnNew(); - today.setHours(0, 0, 0, 0); - if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today) + if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today.setHours(0, 0, 0, 0)) throw new UserError(`This ticket has a shipped date earlier than today`); - const shipmentResponse = await sendXmlDoc('createShipment', {mrw, expeditionData}, 'application/soap+xml'); - const shipmentId = getTextByTag(shipmentResponse, 'NumeroEnvio'); + const shipmentResponse = await Self.sendXmlDoc( + __dirname + `/createShipment.ejs`, + {mrw, expeditionData}, + 'application/soap+xml' + ); + const shipmentId = Self.getTextByTag(shipmentResponse, 'NumeroEnvio'); if (!shipmentId) - throw new UserError(getTextByTag(shipmentResponse, 'Mensaje')); + throw new UserError(Self.getTextByTag(shipmentResponse, 'Mensaje')); - const getLabelResponse = await sendXmlDoc('getLabel', {mrw, shipmentId}, 'text/xml'); - const file = getTextByTag(getLabelResponse, 'EtiquetaFile'); - - if (tx) await tx.commit(); + const file = await mrwConfig.getLabel(shipmentId); return {shipmentId, file}; }; - - function getTextByTag(xmlDoc, tag) { - return xmlDoc?.getElementsByTagName(tag)[0]?.textContent; - } - - async function sendXmlDoc(xmlDock, params, contentType) { - const parser = new DOMParser(); - - const xmlTemplate = fs.readFileSync(__dirname + `/${xmlDock}.ejs`, 'utf-8'); - const renderedTemplate = ejs.render(xmlTemplate, params); - const data = await axios.post(params.mrw.url, renderedTemplate, { - headers: { - 'Content-Type': `${contentType}; charset=utf-8` - } - }); - return parser.parseFromString(data.data, 'text/xml'); - } }; diff --git a/back/methods/mrw-config/getLabel.js b/back/methods/mrw-config/getLabel.js new file mode 100644 index 000000000..ae6bc8f21 --- /dev/null +++ b/back/methods/mrw-config/getLabel.js @@ -0,0 +1,27 @@ +module.exports = Self => { + Self.remoteMethod('getLabel', { + description: 'Return a base64Binary label from de MRW WebService', + accessType: 'READ', + accepts: [{ + arg: 'shipmentId', + type: 'number', + required: true + }], + returns: { + type: 'string', + root: true + }, + http: { + path: `/getLabel`, + verb: 'GET' + } + }); + + Self.getLabel = async shipmentId => { + const mrw = await Self.getConfig(); + + const getLabelResponse = await Self.sendXmlDoc(__dirname + `/getLabel.ejs`, {mrw, shipmentId}, 'text/xml'); + + return Self.getTextByTag(getLabelResponse, 'EtiquetaFile'); + }; +}; diff --git a/back/methods/mrw-config/specs/createShipment.spec.js b/back/methods/mrw-config/specs/createShipment.spec.js index f05f9a81d..a73331971 100644 --- a/back/methods/mrw-config/specs/createShipment.spec.js +++ b/back/methods/mrw-config/specs/createShipment.spec.js @@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models; const axios = require('axios'); const fs = require('fs'); +const filter = {subject: 'Superación de la Hora de Corte de MRW'}; const mockBase64Binary = 'base64BinaryString'; const ticket1 = { 'id': '44', @@ -28,25 +29,40 @@ const expedition1 = { 'editorFk': 100 }; -let tx; -let options; - -describe('MRWConfig createShipment()', () => { - beforeEach(async() => { - options = tx = undefined; - tx = await models.MrwConfig.beginTransaction({}); - options = {transaction: tx}; - +fdescribe('MRWConfig createShipment()', () => { + beforeAll(async() => { await models.Agency.create( - {'id': 999, 'name': 'mrw'}, - options + {'id': 999, 'name': 'mrw'} ); await models.AgencyMode.create( - {'id': 999, 'name': 'mrw', 'agencyFk': 999, 'code': 'mrw'}, - options + {'id': 999, 'name': 'mrw', 'agencyFk': 999, 'code': 'mrw'} + ); + await createMrwConfig(); + + await models.Application.rawSql( + `INSERT INTO vn.mrwService + SET agencyModeCodeFk = 'mrw', + clientType = 1, + serviceType = 1, + kg = 1`, null + ); + await models.Ticket.create(ticket1); + await models.Expedition.create(expedition1); + }); + + beforeEach(() => { + const mockPostResponses = [ + {data: fs.readFileSync(__dirname + '/mockGetLabel.xml', 'utf-8')}, + {data: fs.readFileSync(__dirname + '/mockCreateShipment.xml', 'utf-8')} + ]; + + spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop())); + }); + + async function createMrwConfig() { await models.MrwConfig.create( { 'id': 1, @@ -55,67 +71,100 @@ describe('MRWConfig createShipment()', () => { 'password': 'password', 'franchiseCode': 'franchiseCode', 'subscriberCode': 'subscriberCode' - }, options + } ); - - await models.Application.rawSql( - `INSERT INTO vn.mrwService - SET agencyModeCodeFk = 'mrw', - clientType = 1, - serviceType = 1, - kg = 1`, null, options - ); - await models.Ticket.create(ticket1, options); - await models.Expedition.create(expedition1, options); - }); - - afterEach(async() => { - await tx.rollback(); - }); + } it('should create a shipment and return a base64Binary label', async() => { - const mockPostResponses = [ - {data: fs.readFileSync(__dirname + '/mockGetLabel.xml', 'utf-8')}, - {data: fs.readFileSync(__dirname + '/mockCreateShipment.xml', 'utf-8')} - ]; - - spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop())); - - const {file} = await models.MrwConfig.createShipment(expedition1.id, options); + const {file} = await models.MrwConfig.createShipment(expedition1.id); expect(file).toEqual(mockBase64Binary); }); it('should fail if mrwConfig has no data', async() => { let error; + await models.MrwConfig.destroyAll(); await models.MrwConfig.createShipment(expedition1.id).catch(e => { error = e; }).finally(async() => { expect(error.message).toEqual(`Some mrwConfig parameters are not set`); }); + await createMrwConfig(); expect(error).toBeDefined(); }); it('should fail if expeditionFk is not a MrwExpedition', async() => { let error; - await models.MrwConfig.createShipment(undefined, options).catch(e => { + await models.MrwConfig.createShipment(undefined).catch(e => { error = e; }).finally(async() => { expect(error.message).toEqual(`This expedition is not a MRW shipment`); }); }); - it(' should fail if the creation date of this ticket is before the current date it', async() => { + it('should fail if the creation date of this ticket is before the current date', async() => { let error; const yesterday = Date.vnNew(); - yesterday.setDate(yesterday.getDate() - 1); - await models.Ticket.updateAll({id: ticket1.id}, {shipped: yesterday}, options); - await models.MrwConfig.createShipment(expedition1.id, options).catch(e => { + + await models.Ticket.updateAll({id: ticket1.id}, {shipped: yesterday}); + await models.MrwConfig.createShipment(expedition1.id).catch(e => { error = e; }).finally(async() => { expect(error.message).toEqual(`This ticket has a shipped date earlier than today`); }); + await models.Ticket.updateAll({id: ticket1.id}, {shipped: Date.vnNew()}); + }); + + it('should send mail if you are past the dead line and is not notified today', async() => { + await models.Mail.destroyAll(filter); + + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: null}); + + await models.MrwConfig.createShipment(expedition1.id); + + const mail = await models.Mail.findOne({ + order: 'id DESC', + where: filter + }); + + expect(mail.subject).toEqual(filter.subject); + + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: null, notified: null}); + }); + + it('should send mail if you are past the dead line and it is notified from another day', async() => { + await models.Mail.destroyAll(filter); + + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: new Date()}); + + await models.MrwConfig.createShipment(expedition1.id); + + const mail = await models.Mail.findOne({ + order: 'id DESC', + where: filter + }); + + expect(mail.subject).toEqual(filter.subject); + + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: null, notified: null}); + }); + + it('should not send mail if you are past the dead line and it is notified', async() => { + await models.Mail.destroyAll(filter); + + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: Date.vnNew()}); + + await models.MrwConfig.createShipment(expedition1.id); + + const mail = await models.Mail.findOne({ + order: 'id DESC', + where: filter + }); + + expect(mail).toEqual(null); + + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: null, notified: null}); }); }); diff --git a/back/models/mrw-config.js b/back/models/mrw-config.js index f764b91cc..4496a9a56 100644 --- a/back/models/mrw-config.js +++ b/back/models/mrw-config.js @@ -1,4 +1,35 @@ module.exports = Self => { require('../methods/mrw-config/createShipment')(Self); + require('../methods/mrw-config/getLabel')(Self); require('../methods/mrw-config/cancelShipment')(Self); + + const fs = require('fs'); + const ejs = require('ejs'); + const UserError = require('vn-loopback/util/user-error'); + const {DOMParser} = require('xmldom'); + const axios = require('axios'); + + Self.getConfig = async function() { + const mrw = await Self.app.models.MrwConfig.findOne(null); + if (!mrw) throw new UserError(`Some mrwConfig parameters are not set`); + return mrw; + }; + + Self.getTextByTag = function(xmlDoc, tag) { + return xmlDoc?.getElementsByTagName(tag)[0]?.textContent; + }; + + Self.sendXmlDoc = async function(path, params, contentType) { + const parser = new DOMParser(); + + const xmlTemplate = fs.readFileSync(path, 'utf-8'); + const renderedTemplate = ejs.render(xmlTemplate, params); + const data = await axios.post(params.mrw.url, renderedTemplate, { + headers: { + 'Content-Type': `${contentType}; charset=utf-8` + } + }); + return parser.parseFromString(data.data, 'text/xml'); + }; }; + diff --git a/back/models/mrw-config.json b/back/models/mrw-config.json index b0e9754bd..c96b68cf3 100644 --- a/back/models/mrw-config.json +++ b/back/models/mrw-config.json @@ -39,6 +39,12 @@ }, "defaultWeight": { "type": "number" + }, + "expeditionDeadLine": { + "type": "string" + }, + "notified":{ + "type": "date" } } } diff --git a/db/versions/11086-grayCataractarum/00-firstScript.sql b/db/versions/11086-grayCataractarum/00-firstScript.sql new file mode 100644 index 000000000..20ed9d8f2 --- /dev/null +++ b/db/versions/11086-grayCataractarum/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS notified TIMESTAMP NULL +COMMENT 'Date when it was notified that the web service deadline was exceeded'; diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 4a7e1505c..1324e21d3 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -359,5 +359,7 @@ "It was not able to create the invoice": "No se pudo crear la factura", "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)", "This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario", - "You can only have one PDA": "Solo puedes tener un PDA" + "You can only have one PDA": "Solo puedes tener un PDA", + "1) Fecha de recogida incorrecta (fecha cerrada).": "1) Fecha de recogida incorrecta (fecha cerrada).", + "This expedition is not a MRW shipment": "This expedition is not a MRW shipment" } \ No newline at end of file diff --git a/print/core/components/email-footer/email-footer.html b/print/core/components/email-footer/email-footer.html index 9c5df59a9..5cacdd129 100644 --- a/print/core/components/email-footer/email-footer.html +++ b/print/core/components/email-footer/email-footer.html @@ -1,19 +1,16 @@ \ No newline at end of file diff --git a/print/templates/email/mrw-webService-deadline/assets/css/import.js b/print/templates/email/mrw-webService-deadline/assets/css/import.js new file mode 100644 index 000000000..4b4bb7086 --- /dev/null +++ b/print/templates/email/mrw-webService-deadline/assets/css/import.js @@ -0,0 +1,11 @@ +const Stylesheet = require(`vn-print/core/stylesheet`); + +const path = require('path'); +const vnPrintPath = path.resolve('print'); + +module.exports = new Stylesheet([ + `${vnPrintPath}/common/css/spacing.css`, + `${vnPrintPath}/common/css/misc.css`, + `${vnPrintPath}/common/css/layout.css`, + `${vnPrintPath}/common/css/email.css`]) + .mergeStyles(); diff --git a/print/templates/email/mrw-webService-deadline/locale/en.yml b/print/templates/email/mrw-webService-deadline/locale/en.yml new file mode 100644 index 000000000..e10ec9e58 --- /dev/null +++ b/print/templates/email/mrw-webService-deadline/locale/en.yml @@ -0,0 +1,5 @@ +subject: Exceeding MRW Cut-off Time +title: Exceeding MRW Cut-off Time +greeting: Dear Team. +body: Please be informed that we have exceeded the cut-off time indicated by MRW. From this moment, all generated labels will have a delivery date for tomorrow.It is necessary to contact the MRW representatives to manage any urgencies or clarifications that may arise. +footer: Best regards. diff --git a/print/templates/email/mrw-webService-deadline/locale/es.yml b/print/templates/email/mrw-webService-deadline/locale/es.yml new file mode 100644 index 000000000..656639fc3 --- /dev/null +++ b/print/templates/email/mrw-webService-deadline/locale/es.yml @@ -0,0 +1,5 @@ +subject: Superación de la Hora de Corte de MRW +title: Superación de la Hora de Corte de MRW +greeting: Estimado equipo. +body: Les informo que hemos superado la hora de corte indicada por MRW. A partir de este momento, todas las etiquetas generadas tendrán fecha de entrega para mañana.Es necesario que se pongan en contacto con los responsables de MRW para gestionar cualquier urgencia o aclaración que puedan necesitar. +footer: Saludos cordiales. diff --git a/print/templates/email/mrw-webService-deadline/mrw-webService-deadline.html b/print/templates/email/mrw-webService-deadline/mrw-webService-deadline.html new file mode 100644 index 000000000..adcf0228c --- /dev/null +++ b/print/templates/email/mrw-webService-deadline/mrw-webService-deadline.html @@ -0,0 +1,10 @@ + +
+
+

{{ $t('title') }}

+

{{$t('greeting')}}

+

{{$t('body')}}

+

{{$t('footer')}}

+
+
+
diff --git a/print/templates/email/mrw-webService-deadline/mrw-webService-deadline.js b/print/templates/email/mrw-webService-deadline/mrw-webService-deadline.js new file mode 100755 index 000000000..f010a861f --- /dev/null +++ b/print/templates/email/mrw-webService-deadline/mrw-webService-deadline.js @@ -0,0 +1,9 @@ +const Component = require(`vn-print/core/component`); +const emailBody = new Component('email-body'); + +module.exports = { + name: 'mrw-webService-deadline', + components: { + 'email-body': emailBody.build(), + } +}; -- 2.40.1 From d41f1ff5612c07c5ac1fe25cc892a160d33c611c Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 10 Jun 2024 12:36:15 +0200 Subject: [PATCH 159/413] fix: refs #6404 remove focus from test --- back/methods/mrw-config/specs/createShipment.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/mrw-config/specs/createShipment.spec.js b/back/methods/mrw-config/specs/createShipment.spec.js index a73331971..b96efeac4 100644 --- a/back/methods/mrw-config/specs/createShipment.spec.js +++ b/back/methods/mrw-config/specs/createShipment.spec.js @@ -29,7 +29,7 @@ const expedition1 = { 'editorFk': 100 }; -fdescribe('MRWConfig createShipment()', () => { +describe('MRWConfig createShipment()', () => { beforeAll(async() => { await models.Agency.create( {'id': 999, 'name': 'mrw'} -- 2.40.1 From 272a34c5f92d59d528a37ca4f32b5b8831004881 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 10 Jun 2024 12:46:26 +0200 Subject: [PATCH 160/413] refactor: refs #7486 Added userFk debug --- db/routines/vn/procedures/collection_new.sql | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index 370b59ae5..fa947ddef 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -49,7 +49,10 @@ BEGIN BEGIN IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); - CALL util.debugAdd('releaseLock', vLockName); -- Tmp + CALL util.debugAdd(JSON_OBJECT( + 'type', 'releaseLock', + 'userFk', vUserFk + ), vLockName); -- Tmp END IF; RESIGNAL; -- 2.40.1 From e081c4504dadd3787ab4b7ed239992a48cc2d7c5 Mon Sep 17 00:00:00 2001 From: jgallego Date: Mon, 10 Jun 2024 14:51:48 +0200 Subject: [PATCH 161/413] feat: refs #7548 link a grafana --- modules/ticket/back/methods/ticket/summary.js | 1 + modules/ticket/back/models/ticket.json | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/modules/ticket/back/methods/ticket/summary.js b/modules/ticket/back/methods/ticket/summary.js index 1ce91e1b2..6bfa478ec 100644 --- a/modules/ticket/back/methods/ticket/summary.js +++ b/modules/ticket/back/methods/ticket/summary.js @@ -56,6 +56,7 @@ module.exports = Self => { const filter = { include: [ {relation: 'warehouse', scope: {fields: ['name']}}, + {relation: 'ticketCollections', scope: {fields: ['collectionFk']}}, {relation: 'agencyMode', scope: {fields: ['name']}}, {relation: 'zone', scope: {fields: ['name']}}, {relation: 'client', diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json index 248c0312f..2d14de808 100644 --- a/modules/ticket/back/models/ticket.json +++ b/modules/ticket/back/models/ticket.json @@ -147,6 +147,11 @@ "type": "belongsTo", "model": "Cmr", "foreignKey": "cmrFk" + }, + "ticketCollections": { + "type": "hasMany", + "model": "TicketCollection", + "foreignKey": "ticketFk" } } } -- 2.40.1 From 2061d08bacf0c53b158a7cd3fd594633bf8f780f Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 10 Jun 2024 15:54:53 +0200 Subject: [PATCH 162/413] feat: add changelog --- CHANGELOG.md | 79 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a2bb2e7e4..b322f9f25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,82 @@ +# Version 24.24 - 2024-06-11 + +### Added 🆕 + +- 6281 feat:buyFk in itemShekving by:sergiodt +- 6281 feat:buyFk in itemShelving by:sergiodt +- feat: #6408 tests by:jgallego +- feat: packaging refs #4021 (origin/4021_packaging) by:sergiodt +- feat: refs #6021 add new field by:pablone +- feat: refs #6281 change fixtures by:robert +- feat: refs # 6408 test ok (origin/6408-rocketChat) by:jgallego +- feat: refs #6477 productionConfig add column by:robert +- feat: refs #6600 add column (origin/6600-createItemPhotoComment) by:jorgep +- feat: refs #6600 Add photoMotivation column to item table and create itemPhotoComment table by:jorgep +- feat: refs #6889 add back tests by:jorgep +- feat: refs #6889 fixtures & models by:jorgep +- feat : refs #6889 wip: check if is productionReviewer or owner by:jorgep +- feat: refs #6942 set false isBooed & ledger by:jorgep +- feat: refs #6942 toUnbook by:jorgep +- feat: refs #6942 xdiario fixtures by:jorgep +- feat: refs #7398 Change by:guillermo +- feat: refs #7438 Added volume to item_valuateInventory by:guillermo +- feat: refs #7438 Requested changes and little changes by:guillermo +- refs #6281 feat:buyFk in itemShelving by:sergiodt + +### Changed 📦 + +- refactor: refs #6600 add space by:jorgep +- refactor: refs #6889 improve file loading logic by:jorgep +- refactor: refs #6889 sale tests e2e by:jorgep +- refactor: refs #6889 script sql (origin/6889-dropAddSaleByCode) by:jorgep +- refactor: refs #6889 use addSale by:jorgep +- refactor: refs #6942 toUnbook & drop buyer acls by:jorgep +- refactor: refs #7398 Refactor and change ekt_scan (origin/7398-ektScan) by:guillermo +- refactor: refs #7486 Optimized procs by:guillermo + +### Fixed 🛠️ + +- feat: refs #6281 change fixtures by:robert +- feat: refs #6889 fixtures & models by:jorgep +- feat: refs #6942 xdiario fixtures by:jorgep +- fix: checking process.env.NODE_ENV by:alexm +- fix: en translations by:alexm +- fix: move to boot (origin/7421-fix_checking_NODE_ENV, 7421-fix_checking_NODE_ENV) by:alexm +- fix: refs #6095 filter by refFk null by:pablone +- fix: refs #6600 rollback by:jorgep +- fix: refs #6889 allocate 'productionReviewer' role to revision dep. workers & check if is owner or reviewer by:jorgep +- fix: refs #6889 check if has collection or sectorCollection by:jorgep +- fix: refs #6889 e2e tests by:jorgep +- fix: refs #6889 fix back tests by:jorgep +- fix: refs #6889 modify fixtures by:jorgep +- fix: refs #6889 rollback by:jorgep +- fix: refs #6942 acls & back by:jorgep +- fix: refs #6942 add deleteById acl by:jorgep +- fix: refs #6942 add test & change column name by:jorgep +- fix: refs #6942 create invoiceIn acl by:jorgep +- fix: refs #6942 delete by:jorgep +- fix: refs #6942 drop quotes by:jorgep +- fix : refs #6942 remove grafana update priv by:jorgep +- fix: refs #6942 revoke update isBooked by:jorgep +- fix: refs #6942 toBook/toUnbook by:jorgep +- fix: refs #7442 Fix kubernetes deploy by:Juan Ferrer Toribio +- fix(salix): refs #7272 #7272 Add aclService in routes.js by:Javier Segarra +- fix(salix): refs #7272 #7272 Back validateToken endpoint by:Javier Segarra +- fix(salix): refs #7272 #7272 Bug when acl not loaded by:Javier Segarra +- fix(salix): refs #7272 #7272 Call validateToken by:Javier Segarra +- fix(salix): refs #7272 #7272 Errors when Token not exists by:Javier Segarra +- fix(salix): refs #7272 #7272 Front retry calls by:Javier Segarra +- fix(salix): refs #7272 #7272 i18n Error by:Javier Segarra +- fix(salix): refs #7272 #7272 Remove aclService from auth.js by:Javier Segarra +- fix: simplify by:alexm +- fix traduction & e2e by:carlossa +- refs #6820 fix back by:carlossa +- refs #6820 fix pr by:carlossa +- refs #6832 fix: ToItem (origin/6832_refactorBackToItem) by:Sergio De la torre +- refs #7292 fix tback by:carlossa +- refs #7296 fix pr errors, trad by:carlossa +- test(salix): refs #7272 #7272 fix renew-token.spec by:Javier Segarra + # Changelog -- 2.40.1 From bd13ecd464277c41ac7a9e56d68aad4fc3e31cbd Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 11 Jun 2024 07:59:53 +0200 Subject: [PATCH 163/413] refactor: refs #7486 engine memory and primary key sales_merge --- db/routines/vn/procedures/sales_merge.sql | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/sales_merge.sql b/db/routines/vn/procedures/sales_merge.sql index a91268c2f..3dd01f9bc 100644 --- a/db/routines/vn/procedures/sales_merge.sql +++ b/db/routines/vn/procedures/sales_merge.sql @@ -1,5 +1,5 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sales_merge`(vTicketFk INT) +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sales_merge`(vTicketFk INT) BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN @@ -8,19 +8,21 @@ BEGIN END; CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + (PRIMARY KEY (id)) + ENGINE = MEMORY SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity FROM sale s JOIN item i ON i.id = s.itemFk JOIN itemType it ON it.id = i.typeFk WHERE s.ticketFk = vTicketFk AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; + GROUP BY s.itemFk, s.price, s.discount; START TRANSACTION; UPDATE sale s JOIN tSalesToPreserve stp ON stp.id = s.id - SET quantity = newQuantity + SET s.quantity = newQuantity WHERE s.ticketFk = vTicketFk; DELETE s.* @@ -35,5 +37,5 @@ BEGIN COMMIT; DROP TEMPORARY TABLE tSalesToPreserve; -END$$ -DELIMITER ; +END$$ +DELIMITER ; -- 2.40.1 From 2dec51804cb92d41872eced40fb9a1780b2dd524 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 11 Jun 2024 08:38:26 +0200 Subject: [PATCH 164/413] build: dump --- db/dump/.dump/data.sql | 59 +- db/dump/.dump/privileges.sql | 200 ++++-- db/dump/.dump/structure.sql | 1304 +++++++++++++++------------------- db/dump/.dump/triggers.sql | 37 +- 4 files changed, 798 insertions(+), 802 deletions(-) diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index 3be9dd4f5..c0d0c34e6 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -3,7 +3,7 @@ USE `util`; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -INSERT INTO `version` VALUES ('vn-database','11071','60ac8cf6fc77b99b199b27866011b1efe8c961e8','2024-05-28 07:32:50','11074'); +INSERT INTO `version` VALUES ('vn-database','11090','7adf4a373d19ce126adbc7b1077f69a74559c09a','2024-06-11 08:32:36','11094'); INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL); @@ -775,6 +775,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','10975','00-action.sql','jenkins@ INSERT INTO `versionLog` VALUES ('vn-database','10975','01-expeditionFk.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-03 12:04:52',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10976','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-18 07:40:57',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10977','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-18 07:40:57',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','10978','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:33',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10984','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10988','00-pbx_prefix.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-04-11 17:00:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10990','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); @@ -800,6 +801,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','11010','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11012','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:27',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11013','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11014','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-14 07:45:27',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11015','00-photoMotivation.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11016','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-27 13:16:09',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11018','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:34:21',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11019','00-locker.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:17',NULL,NULL); @@ -819,6 +821,8 @@ INSERT INTO `versionLog` VALUES ('vn-database','11040','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11044','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:31',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11045','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-10 14:53:29',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11046','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:46',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11050','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11050','01-elementFilter.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11051','00-sipConfig_callLimit.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-14 14:31:10',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11054','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:46',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11055','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:46',NULL,NULL); @@ -827,8 +831,22 @@ INSERT INTO `versionLog` VALUES ('vn-database','11057','01-part.sql','jenkins@db INSERT INTO `versionLog` VALUES ('vn-database','11057','02-part.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:47',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11057','03-part.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11058','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11059','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11060','00-createRoleReviewer.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11061','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11065','00-modifyInvoiceInPrivileges.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11065','01-modifyInvoiceInAcls.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11068','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11069','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11071','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11074','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11075','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-28 12:54:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11078','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11079','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 08:22:10',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11080','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 12:01:58',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11083','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-03 10:46:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11090','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11092','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-07 08:21:23',NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; @@ -924,6 +942,7 @@ INSERT INTO `role` VALUES (125,'claimViewer','Trabajadores que consulta las recl INSERT INTO `role` VALUES (126,'greenhouseBoss','Jefe de invernadero',1,'2023-11-16 14:32:13','2023-11-16 14:32:13',NULL); INSERT INTO `role` VALUES (127,'timeControl','Tablet para fichar',1,'2024-01-09 16:36:56','2024-01-09 16:36:56',NULL); INSERT INTO `role` VALUES (129,'buyerAssistant','Comprador que tienes mas permisos para ayudar al buyerBoss en algunas tareas',1,'2024-02-06 06:59:12','2024-02-06 06:59:12',783); +INSERT INTO `role` VALUES (130,'reviewer','Revisor de producción',1,'2024-06-11 00:00:00','2024-06-11 00:00:00',10578); INSERT INTO `roleInherit` VALUES (1,1,2,NULL); INSERT INTO `roleInherit` VALUES (2,1,3,NULL); @@ -950,7 +969,6 @@ INSERT INTO `roleInherit` VALUES (27,21,53,NULL); INSERT INTO `roleInherit` VALUES (28,22,13,NULL); INSERT INTO `roleInherit` VALUES (29,22,21,NULL); INSERT INTO `roleInherit` VALUES (30,30,5,NULL); -INSERT INTO `roleInherit` VALUES (31,30,20,NULL); INSERT INTO `roleInherit` VALUES (32,30,22,NULL); INSERT INTO `roleInherit` VALUES (33,30,53,NULL); INSERT INTO `roleInherit` VALUES (34,30,64,NULL); @@ -1182,7 +1200,6 @@ INSERT INTO `roleInherit` VALUES (353,110,49,NULL); INSERT INTO `roleInherit` VALUES (354,103,119,NULL); INSERT INTO `roleInherit` VALUES (355,127,11,NULL); INSERT INTO `roleInherit` VALUES (356,123,125,NULL); -INSERT INTO `roleInherit` VALUES (357,36,35,NULL); INSERT INTO `roleInherit` VALUES (358,36,49,NULL); INSERT INTO `roleInherit` VALUES (359,129,35,NULL); INSERT INTO `roleInherit` VALUES (360,101,129,NULL); @@ -1190,6 +1207,11 @@ INSERT INTO `roleInherit` VALUES (361,50,112,NULL); INSERT INTO `roleInherit` VALUES (362,122,15,NULL); INSERT INTO `roleInherit` VALUES (364,35,18,NULL); INSERT INTO `roleInherit` VALUES (365,123,119,NULL); +INSERT INTO `roleInherit` VALUES (366,30,37,NULL); +INSERT INTO `roleInherit` VALUES (367,30,73,NULL); +INSERT INTO `roleInherit` VALUES (368,130,49,10578); +INSERT INTO `roleInherit` VALUES (369,50,130,10578); +INSERT INTO `roleInherit` VALUES (370,72,130,10578); INSERT INTO `userPassword` VALUES (1,7,1,0,2,1); @@ -1373,7 +1395,7 @@ INSERT INTO `ACL` VALUES (213,'TravelThermograph','*','WRITE','ALLOW','ROLE','bu INSERT INTO `ACL` VALUES (214,'Entry','*','*','ALLOW','ROLE','buyer'); INSERT INTO `ACL` VALUES (216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (218,'Intrastat','*','*','ALLOW','ROLE','buyer'); -INSERT INTO `ACL` VALUES (221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'); +INSERT INTO `ACL` VALUES (221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','guest'); INSERT INTO `ACL` VALUES (226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'); INSERT INTO `ACL` VALUES (227,'Address','*','READ','ALLOW','ROLE','trainee'); INSERT INTO `ACL` VALUES (228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'); @@ -1402,7 +1424,7 @@ INSERT INTO `ACL` VALUES (259,'Client','createReceipt','*','ALLOW','ROLE','sales INSERT INTO `ACL` VALUES (260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'); INSERT INTO `ACL` VALUES (262,'Entry','*','*','ALLOW','ROLE','administrative'); -INSERT INTO `ACL` VALUES (263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (263,'InvoiceIn','*','READ','ALLOW','ROLE','administrative'); INSERT INTO `ACL` VALUES (264,'StarredModule','*','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'); INSERT INTO `ACL` VALUES (266,'ZoneLog','*','READ','ALLOW','ROLE','employee'); @@ -1469,7 +1491,6 @@ INSERT INTO `ACL` VALUES (338,'Shelving','*','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (339,'OsTicket','*','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (340,'OsTicketConfig','*','*','ALLOW','ROLE','it'); INSERT INTO `ACL` VALUES (341,'ClientConsumptionQueue','*','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (342,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (343,'Ticket','deliveryNoteEmail','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (344,'Ticket','deliveryNoteCsvPdf','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (345,'Ticket','deliveryNoteCsvEmail','READ','ALLOW','ROLE','employee'); @@ -1644,7 +1665,7 @@ INSERT INTO `ACL` VALUES (522,'Client','replaceOrCreate','*','ALLOW','ROLE','emp INSERT INTO `ACL` VALUES (523,'Client','updateAll','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (524,'Client','upsertWithWhere','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (525,'Defaulter','observationEmail','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (527,'VnUser','acl','READ','ALLOW','ROLE','account'); +INSERT INTO `ACL` VALUES (527,'VnUser','acl','READ','ALLOW','ROLE','guest'); INSERT INTO `ACL` VALUES (528,'VnUser','getCurrentUserData','READ','ALLOW','ROLE','account'); INSERT INTO `ACL` VALUES (530,'Account','exists','READ','ALLOW','ROLE','account'); INSERT INTO `ACL` VALUES (531,'Account','exists','READ','ALLOW','ROLE','account'); @@ -1809,7 +1830,7 @@ INSERT INTO `ACL` VALUES (727,'Account','find','READ','ALLOW','ROLE','employee') INSERT INTO `ACL` VALUES (728,'Account','exists','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (729,'Sale','clone','WRITE','ALLOW','ROLE','buyer'); INSERT INTO `ACL` VALUES (730,'Ticket','setDeleted','WRITE','ALLOW','ROLE','deliveryAssistant'); -INSERT INTO `ACL` VALUES (732,'Sale','isInPreparing','*','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (732,'Sale','isInPreparing','*','ALLOW','ROLE','reviewer'); INSERT INTO `ACL` VALUES (733,'Train','*','READ','ALLOW','ROLE','production'); INSERT INTO `ACL` VALUES (734,'WorkerDepartment','*','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (735,'VnUser','higherPrivileges','*','ALLOW','ROLE','itManagement'); @@ -1866,7 +1887,7 @@ INSERT INTO `ACL` VALUES (785,'VnRole','*','WRITE','ALLOW','ROLE','it'); INSERT INTO `ACL` VALUES (786,'State','isAllEditable','READ','ALLOW','ROLE','delivery'); INSERT INTO `ACL` VALUES (787,'Ticket','makePdfList','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (788,'Ticket','invoiceTicketsAndPdf','*','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (789,'InvoiceIn','*','*','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (789,'InvoiceIn','*','READ','ALLOW','ROLE','buyer'); INSERT INTO `ACL` VALUES (790,'InvoiceIn','getSerial','READ','ALLOW','ROLE','buyer'); INSERT INTO `ACL` VALUES (791,'InvoiceIn','corrective','WRITE','ALLOW','ROLE','administrative'); INSERT INTO `ACL` VALUES (792,'InvoiceInCorrection','*','*','ALLOW','ROLE','administrative'); @@ -1920,6 +1941,25 @@ INSERT INTO `ACL` VALUES (842,'Worker','__get__locker','READ','ALLOW','ROLE','hr INSERT INTO `ACL` VALUES (843,'Worker','__get__locker','READ','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (844,'RoadmapStop','*','*','ALLOW','ROLE','production'); INSERT INTO `ACL` VALUES (845,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss'); +INSERT INTO `ACL` VALUES (846,'Ticket','refund','WRITE','ALLOW','ROLE','logistic'); +INSERT INTO `ACL` VALUES (847,'RouteConfig','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (848,'InvoiceIn','updateInvoiceIn','WRITE','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (849,'InvoiceIn','clone','WRITE','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (850,'InvoiceIn','corrective','WRITE','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (851,'InvoiceIn','exchangeRateUpdate','WRITE','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (852,'InvoiceIn','invoiceInEmail','WRITE','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (853,'InvoiceIn','toBook','WRITE','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (854,'InvoiceIn','toUnbook','WRITE','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (855,'InvoiceIn','deleteById','WRITE','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (856,'InvoiceIn','updateInvoiceIn','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (857,'InvoiceIn','clone','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (858,'InvoiceIn','corrective','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (859,'InvoiceIn','exchangeRateUpdate','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (860,'InvoiceIn','invoiceInEmail','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (861,'InvoiceIn','toBook','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (862,'InvoiceIn','deleteById','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (863,'InvoiceIn','create','WRITE','ALLOW','ROLE','administrative'); +INSERT INTO `ACL` VALUES (864,'InvoiceIn','create','WRITE','ALLOW','ROLE','buyer'); INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee'); INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee'); @@ -2008,6 +2048,7 @@ INSERT INTO `defaultViewConfig` VALUES ('itemsIndex','{\"intrastat\":false,\"ste INSERT INTO `defaultViewConfig` VALUES ('latestBuys','{\"intrastat\":false,\"description\":false,\"density\":false,\"isActive\":false,\n \"freightValue\":false,\"packageValue\":false,\"isIgnored\":false,\"price2\":false,\"ektFk\":false,\"weight\":false,\n \"size\":false,\"comissionValue\":false,\"landing\":false}'); INSERT INTO `defaultViewConfig` VALUES ('ticketsMonitor','{\"id\":false}'); INSERT INTO `defaultViewConfig` VALUES ('clientsDetail','{\"id\":true,\"phone\":true,\"city\":true,\"socialName\":true,\"salesPersonFk\":true,\"email\":true,\"name\":false,\"fi\":false,\"credit\":false,\"creditInsurance\":false,\"mobile\":false,\"street\":false,\"countryFk\":false,\"provinceFk\":false,\"postcode\":false,\"created\":false,\"businessTypeFk\":false,\"payMethodFk\":false,\"sageTaxTypeFk\":false,\"sageTransactionTypeFk\":false,\"isActive\":false,\"isVies\":false,\"isTaxDataChecked\":false,\"isEqualizated\":false,\"isFreezed\":false,\"hasToInvoice\":false,\"hasToInvoiceByAddress\":false,\"isToBeMailed\":false,\"hasLcr\":false,\"hasCoreVnl\":false,\"hasSepaVnl\":false}'); +INSERT INTO `defaultViewConfig` VALUES ('routesList','{\"ID\":true,\"worker\":true,\"agency\":true,\"vehicle\":true,\"date\":true,\"volume\":true,\"description\":true,\"started\":true,\"finished\":true,\"actions\":true}'); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql index 39b7d4a8c..00ef1018b 100644 --- a/db/dump/.dump/privileges.sql +++ b/db/dump/.dump/privileges.sql @@ -303,7 +303,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','jerarquia' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerBusinessAgreement','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','tarifa_componentes','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','tarifa_componentes_series','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','Entradas','alexm@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','itemType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','cl_main','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','cl_main','alexm@%','0000-00-00 00:00:00','Select',''); @@ -349,7 +348,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','empresa','alex INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','sectorType','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Tintas','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','Movimientos','juan@%','0000-00-00 00:00:00','Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','ticket_observation','juan@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas_dits','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','sale','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -365,9 +364,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','tickets_ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Tickets','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Entradas','root@localhost','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Entradas','alexm@%','0000-00-00 00:00:00','Update',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','Tintas','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','filtros','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_kop','alexm@%','0000-00-00 00:00:00','Select',''); @@ -600,7 +597,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','ektEntryAssign','a INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionBoss','itemShelving','root@localhost','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','propertyDms','juan@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerTimeControlConfig','juan@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entry','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select','Update'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entry','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','businessType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entryLog','juan@10.5.1.2','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','projectState','alexm@%','0000-00-00 00:00:00','Select',''); @@ -627,7 +624,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','wks','alexm@%' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','entryObservation','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','itemShelvingList','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','cmrConfig','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','expeditionTruck','alexm@%','0000-00-00 00:00:00','Insert,Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','expeditionTruck','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','alertLevel','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','expeditionSticker','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','artificialBoss','entryObservation','alexm@%','0000-00-00 00:00:00','Select',''); @@ -650,9 +647,9 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','pgcMaster',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemBarcode','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','host','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticket','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceIn','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','invoiceIn','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','invoiceIn','alexm@%','0000-00-00 00:00:00','Select,Insert',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','Update'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','Update'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','inventoryFailure','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','intrastat','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','inventoryFailure','alexm@%','0000-00-00 00:00:00','Select',''); @@ -660,7 +657,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','inventoryFailureCause INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','invoiceCorrection','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceCorrectionDataSource','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesPerson','invoiceCorrectionType','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','invoiceIn','alexm@%','0000-00-00 00:00:00','Insert',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceInDueDay','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','invoiceInDueDay','alexm@%','0000-00-00 00:00:00','Insert,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','invoiceInIntrastat__','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); @@ -751,7 +748,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','buy','alexm@%','0000- INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','buy','alexm@%','0000-00-00 00:00:00','Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleGoal','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','packingSiteLog','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','Entradas','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','saleComponent','alexm@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','arcRead','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','clientProtected','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -773,7 +769,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','PreciosEspecia INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','movingState','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','bufferType','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','bufferState','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','buffer','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','buffer','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','bufferGroup','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','lastRFID','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','person__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -788,7 +784,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','vehicleState INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','vehicleEvent','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','cooler','Tintas','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','itemBotanical','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','cooler','Entradas','alexm@%','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','account','developer','signInLog','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketTracking','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','deviceProductionState','alexm@%','0000-00-00 00:00:00','Select',''); @@ -1190,7 +1185,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','businessCalendar',' INSERT IGNORE INTO `tables_priv` VALUES ('','edi','employee','item','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','vehicleNotes','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','vehicleDms','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','palletizerBoss','expeditionTruck','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','invoiceInConfig','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','palletizerBoss','zoneEvent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','palletizerBoss','routesMonitor','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','propertyNotes','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update',''); @@ -1224,7 +1219,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','module','juan@ INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','printConfig','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','url','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','userConfigView','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimRedelivery','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','claimRedelivery','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientRisk','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','bs','buyer','sale','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -1252,7 +1247,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','expeditio INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','expeditionScan','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','expeditionPallet','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','province','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','expeditionTruck','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','visitAccess','root@localhost','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryAssistant','v_botanic_export','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','itemCost','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','bs','deliveryAssistant','m3','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -1309,6 +1304,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','project','gu INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','ink','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','visitAgent','root@localhost','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','remittance','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','vehicleConsumption','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','vehicleConsumption','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); @@ -1398,14 +1394,27 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','farmingDeliv INSERT IGNORE INTO `tables_priv` VALUES ('','sage','grafana','TiposIva','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','bs','buyer','waste','alexm@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientObservation','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceInConfig','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','visit','root@localhost','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyDetail','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyReview','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','chat','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','roadmapStop','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','roadmapStop','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','agencyWorkCenter','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','roadmapStop','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','antenna','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','bufferPool','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','enteringLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','expeditionLoading','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','failureLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','movingLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','sorterLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','entryEditor','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert','Update'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientInforma','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','solunionCAP','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientUnpaid','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','pay_dem','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); /*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */; @@ -1465,35 +1474,28 @@ INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','user_id','0 INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','extension','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','name','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','active','0000-00-00 00:00:00','Select'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','id','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','supplierFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','dated','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','invoiceNumber','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isExcludedFromAvailable','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','notes','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isConfirmed','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isOrdered','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isRaid','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','commission','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','created','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','evaNotes','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','travelFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','currencyFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','companyFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','gestDocFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','invoiceInFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','isBlocked','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','loadPriority','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','kop','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','sub','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','pro','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','auction','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','invoiceAmount','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','buyerFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','typeFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','reference','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','observationEditorFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','entry','clonedFrom','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','editorFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','expenseFkDeductible','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','withholdingSageFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','isVatDeductible','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','bookEntried','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','siiTrascendencyInvoiceInFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','cplusTaxBreakFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','cplusSubjectOpFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','cplusRectificationTypeFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','siiTypeInvoiceInFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','operated','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','booked','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','docFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','companyFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','created','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','currencyFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','supplierRef','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','issued','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','supplierFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','serial','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','serialNumber','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','id','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','routeFk','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','name','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','beachFk','0000-00-00 00:00:00','Update'); @@ -1601,7 +1603,10 @@ INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','editorFk', INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','recycledPlastic','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','nonRecycledPlastic','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','item','minQuantity','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Id_Entrada','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','item','originFk','0000-00-00 00:00:00','Select,Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Id_Proveedor','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Fecha','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','id','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','warehouseFk','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','ticket','shipped','0000-00-00 00:00:00','Update'); @@ -1668,6 +1673,93 @@ INSERT IGNORE INTO `columns_priv` VALUES ('','vn','entryEditor','entry','cloned INSERT IGNORE INTO `columns_priv` VALUES ('','vn','entryEditor','entry','editorFk','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','entryEditor','entry','lockerUserFk','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','entryEditor','entry','locked','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Referencia','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Inventario','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Confirmada','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Pedida','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Redada','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','comision','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','odbc_date','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Notas_Eva','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','travel_id','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','Id_Moneda','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','empresa_id','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','gestdoc_id','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','recibida_id','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','loadPriority','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','kop','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','sub','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','pro','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','invoiceAmount','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','buyerFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','typeFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn2008','entryEditor','Entradas','reference','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','id','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','serialNumber','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','serial','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','supplierFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','issued','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','supplierRef','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','currencyFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','created','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','companyFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','docFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','booked','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','operated','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','siiTypeInvoiceInFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','cplusRectificationTypeFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','cplusSubjectOpFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','cplusTaxBreakFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','siiTrascendencyInvoiceInFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','bookEntried','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','isVatDeductible','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','withholdingSageFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','expenseFkDeductible','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','hrBoss','invoiceIn','editorFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','id','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','serialNumber','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','serial','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','supplierFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','issued','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','supplierRef','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','currencyFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','created','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','companyFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','docFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','booked','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','operated','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','siiTypeInvoiceInFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','cplusRectificationTypeFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','cplusSubjectOpFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','cplusTaxBreakFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','siiTrascendencyInvoiceInFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','bookEntried','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','isVatDeductible','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','withholdingSageFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','expenseFkDeductible','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','buyer','invoiceIn','editorFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','id','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','serialNumber','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','serial','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','supplierFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','issued','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','supplierRef','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','currencyFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','created','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','companyFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','docFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','booked','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','operated','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','siiTypeInvoiceInFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','cplusRectificationTypeFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','cplusSubjectOpFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','cplusTaxBreakFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','siiTrascendencyInvoiceInFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','bookEntried','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','isVatDeductible','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','withholdingSageFk','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','expenseFkDeductible','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','logistic','invoiceIn','editorFk','0000-00-00 00:00:00','Update'); /*!40000 ALTER TABLE `columns_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `procs_priv` DISABLE KEYS */; @@ -1732,8 +1824,10 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','barcodeToItem','FUN INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticket_splititempackingtype','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','entry_getCommission','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','deliveryAssistant','expeditionstate_addbypallet','PROCEDURE','alexm@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ledger_nextTx','PROCEDURE','guillermo@10.5.1.3','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','mail_insert','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','entry_fixMisfit','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','entry_updateComission','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','VN_CURDATE','FUNCTION','juan@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','marketingBoss','clientTaxArea','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','clientTaxArea','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); @@ -1761,7 +1855,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','manager','collection_make','PR INSERT IGNORE INTO `procs_priv` VALUES ('','util','android','debugadd','PROCEDURE','jenkins@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','copyComponentsFromSaleList','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaEntryValueUpdate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaInvoiceInBooking','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','duaInvoiceInBooking','PROCEDURE','carlosap@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelvinglog_get','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','expedition_getstate','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','srt','production','expedition_scan','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -1861,7 +1955,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','workercalendar_calculateb INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticketparking_findskipped','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticketcollection_getnopacked','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','supplier_checkbalance','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','item_valuateinventory','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ledger_docompensation','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ledger_next','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','invoicein_booking','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2055,10 +2148,9 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','entry_getTransf INSERT IGNORE INTO `procs_priv` VALUES ('','vn','buyer','entry_getTransfer','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','intrastat_estimateNet','FUNCTION','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','artificialBoss','confection_controlSource','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','remittance_calc','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','remittance_calc','PROCEDURE','alexm@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','developer','connection_kill','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','client_getRisk','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','grafana','item_ValuateInventory','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financialBoss','balance_create','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hrBoss','balance_create','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buy_recalcPricesByEntry','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2066,6 +2158,8 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_recalcPricesByE INSERT IGNORE INTO `procs_priv` VALUES ('','vn','entryEditor','buy_recalcPricesByBuy','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buy_recalcPricesByBuy','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','buy_recalcPricesByBuy','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','ledger_nextTx','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hr','ledger_docompensation','PROCEDURE','guillermo@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); /*!40000 ALTER TABLE `procs_priv` ENABLE KEYS */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; @@ -2090,7 +2184,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','buyer','{\"access\": 0, \"version_ INSERT IGNORE INTO `global_priv` VALUES ('','buyerAssistant','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','buyerBoss','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}'); INSERT IGNORE INTO `global_priv` VALUES ('','claimManager','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','cooler','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','cooler','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','coolerAssist','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','coolerBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','customer','{\"access\": 0, \"max_questions\": 0, \"max_updates\": 30000, \"max_connections\": 300000, \"max_user_connections\": 400, \"max_statement_time\": 0.000000, \"is_role\": true,\"version_id\":100707}'); @@ -2128,7 +2222,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','marketingBoss','{\"access\":0,\"ve INSERT IGNORE INTO `global_priv` VALUES ('','officeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','packager','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','palletizer','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','palletizerBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','palletizerBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','preservedBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','production','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','productionAssi','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}'); diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index b61cbcc5c..dd068cdc7 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -3223,7 +3223,7 @@ BEGIN -- Marcamos para no repetir UPDATE vn.claimEnd ce JOIN vn.claim c ON c.id = ce.claimFk - SET c.isChargedToMana = TRUE + SET ce.isGreuge = TRUE WHERE ce.claimDestinationFk NOT IN (1,5) AND NOT ce.isGreuge AND c.claimStateFk = 3; @@ -10095,42 +10095,39 @@ BEGIN DECLARE vXtraLongAgj INT; DECLARE vDefaultKlo INT; - SELECT - ec.usefulAuctionLeftSegmentLength, - ec.standardBarcodeLength, - ec.floridayBarcodeLength, - ec.floramondoBarcodeLength, - ec.defaultKlo - INTO - vUsefulAuctionLeftSegmentLength, + SELECT usefulAuctionLeftSegmentLength, + standardBarcodeLength, + floridayBarcodeLength, + floramondoBarcodeLength, + defaultKlo + INTO vUsefulAuctionLeftSegmentLength, vStandardBarcodeLength, vFloridayBarcodeLength, vFloramondoBarcodeLength, vDefaultKlo - FROM edi.ektConfig ec; + FROM ektConfig; - DROP TEMPORARY TABLE IF EXISTS tmp.ekt; - CREATE TEMPORARY TABLE tmp.ekt + CREATE OR REPLACE TEMPORARY TABLE tmp.ekt ENGINE = MEMORY SELECT id ektFk FROM ekt LIMIT 0; - CASE + CASE WHEN LENGTH(vBarcode) <= vFloridayBarcodeLength THEN INSERT INTO tmp.ekt SELECT id - FROM edi.ektRecent e + FROM ektRecent e WHERE e.cps = vBarcode OR e.batchNumber = vBarcode; WHEN LENGTH(vBarcode) = vFloramondoBarcodeLength THEN INSERT INTO tmp.ekt SELECT e.id - FROM edi.ektRecent e + FROM ektRecent e WHERE e.pro = MID(vBarcode,2,6) - AND CAST(e.ptd AS SIGNED) = MID(vBarcode,8,5); + AND CAST(e.ptd AS SIGNED) = MID(vBarcode, 8, 5); ELSE - SET vBarcode = LPAD(vBarcode,vStandardBarcodeLength,'0'); + SET vBarcode = LPAD(vBarcode, vStandardBarcodeLength, '0'); SET vAuction = MID(vBarcode, 1, 3); SET vKlo = MID(vBarcode, 4, 2); SET vFec = MAKEDATE(YEAR(util.VN_CURDATE()), MID(vBarcode, 6, 3)); @@ -10141,21 +10138,23 @@ BEGIN -- Clásico de subasta -- Trade standard -- Trade que construye como la subasta - -- Trade como el anterior pero sin trade code + -- Trade como el anterior pero sin trade code INSERT INTO tmp.ekt SELECT id FROM ekt WHERE fec >= vFec - INTERVAL 1 DAY - AND (( - vKlo = vDefaultKlo + AND ( + (vKlo = vDefaultKlo AND (klo = vKlo OR klo IS NULL OR klo = 0) - AND agj IN (vShortAgj, vLongAgj, vXtraLongAgj)) - OR (klo = vKlo + AND agj IN (vShortAgj, vLongAgj, vXtraLongAgj) + ) OR ( + klo = vKlo AND auction = vAuction - AND agj = vShortAgj) + AND agj = vShortAgj + ) ) - ORDER BY agj DESC, fec DESC - LIMIT 1; + ORDER BY agj DESC, fec DESC + LIMIT 1; SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; @@ -10163,9 +10162,11 @@ BEGIN IF NOT vIsFound THEN INSERT INTO tmp.ekt SELECT id - FROM edi.ektRecent e - WHERE e.batchNumber - = LEFT(vBarcode,vUsefulAuctionLeftSegmentLength) + FROM ektRecent e + WHERE e.batchNumber = LEFT( + vBarcode, + vUsefulAuctionLeftSegmentLength + ) AND e.batchNumber > 0; SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; @@ -10175,7 +10176,7 @@ BEGIN IF NOT vIsFound THEN INSERT INTO tmp.ekt SELECT id - FROM edi.ektRecent e + FROM ektRecent e WHERE e.putOrderFk = vBarcode; SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; @@ -10185,18 +10186,28 @@ BEGIN IF NOT vIsFound THEN INSERT INTO tmp.ekt SELECT id - FROM edi.ektRecent e - WHERE e.deliveryNumber - = MID(vBarcode, 4, 13) + FROM ektRecent e + WHERE e.deliveryNumber = MID(vBarcode, 4, 13) AND e.deliveryNumber > 0; SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; END IF; + + -- Solo campo agj + IF NOT vIsFound THEN + INSERT INTO tmp.ekt + SELECT id + FROM ektRecent + WHERE agj = vShortAgj; + + SELECT COUNT(*) FROM tmp.ekt INTO vIsFound; + END IF; + END CASE; IF vIsFound THEN UPDATE ekt e - JOIN tmp.ekt t ON t.ektFk = e.id + JOIN tmp.ekt t ON t.ektFk = e.id SET e.scanned = TRUE; END IF; END ;; @@ -11067,26 +11078,6 @@ CREATE TABLE `addressPostCode` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Client''s address registered for floranet network'; /*!40101 SET character_set_client = @saved_cs_client */; --- --- Table structure for table `builder` --- - -DROP TABLE IF EXISTS `builder`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `builder` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `itemFk` int(11) NOT NULL, - `elementFk` int(11) NOT NULL, - `quantity` int(10) unsigned NOT NULL DEFAULT 1, - PRIMARY KEY (`id`), - KEY `builder_FK` (`itemFk`), - KEY `builder_FK_1` (`elementFk`), - CONSTRAINT `builder_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `builder_FK_1` FOREIGN KEY (`elementFk`) REFERENCES `element` (`itemFk`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Links handmade products with their elements'; -/*!40101 SET character_set_client = @saved_cs_client */; - -- -- Table structure for table `catalogue` -- @@ -11106,37 +11097,25 @@ CREATE TABLE `catalogue` ( `description` text DEFAULT NULL, `created` timestamp NULL DEFAULT current_timestamp(), `payed` datetime DEFAULT NULL, + `addressFk` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `itemFk` (`itemFk`), + KEY `catalogue_address_FK` (`addressFk`), + CONSTRAINT `catalogue_address_FK` FOREIGN KEY (`addressFk`) REFERENCES `vn`.`address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `catalogue_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `element` +-- Table structure for table `config` -- -DROP TABLE IF EXISTS `element`; +DROP TABLE IF EXISTS `config`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `element` ( - `itemFk` int(11) NOT NULL, - `typeFk` smallint(5) unsigned DEFAULT NULL, - `size` int(11) DEFAULT NULL, - `inkFk` char(3) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL, - `originFk` tinyint(2) unsigned DEFAULT NULL, - `name` varchar(30) DEFAULT NULL, - `quantity` int(11) NOT NULL DEFAULT 1, - PRIMARY KEY (`itemFk`), - KEY `element_FK` (`itemFk`), - KEY `element_FK_1` (`typeFk`), - KEY `element_FK_2` (`inkFk`), - KEY `element_FK_3` (`originFk`), - CONSTRAINT `element_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `element_FK_1` FOREIGN KEY (`typeFk`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `element_FK_2` FOREIGN KEY (`inkFk`) REFERENCES `vn`.`ink` (`id`) ON UPDATE CASCADE, - CONSTRAINT `element_FK_3` FOREIGN KEY (`originFk`) REFERENCES `vn`.`origin` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Filtro para localizar posibles items que coincidan con la descripción'; +CREATE TABLE `config` ( + `email` varchar(255) NOT NULL DEFAULT 'floranet@verdnatura.es' +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -11166,6 +11145,27 @@ CREATE TABLE `order` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `recipe` +-- + +DROP TABLE IF EXISTS `recipe`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `recipe` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(11) NOT NULL COMMENT 'Bouquet or plant name', + `elementFk` int(11) NOT NULL COMMENT 'Item detail for bouquet''s composition', + `quantity` int(10) unsigned NOT NULL DEFAULT 1, + `cost` decimal(10,2) NOT NULL DEFAULT 1.00, + PRIMARY KEY (`id`), + KEY `recipe_FK` (`itemFk`), + KEY `recipe_FK_1` (`elementFk`), + CONSTRAINT `recipe_FK` FOREIGN KEY (`itemFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE, + CONSTRAINT `recipe_item_FK` FOREIGN KEY (`elementFk`) REFERENCES `vn`.`item` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='Links handmade products with their elements'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Dumping events for database 'floranet' -- @@ -11278,19 +11278,28 @@ proc:BEGIN postalCode, `type`, image, - description + description, + addressFk ) - SELECT i.name, - i.`size`, - i.id, + SELECT CONCAT(i.name, ' by ',a.nickname), + r.price + apc.deliveryCost, + r.itemFk, vLanded, vPostalCode, it.name, CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image), - i.description + i.description, + apc.addressFk FROM vn.item i + JOIN (SELECT itemFk, SUM(quantity * cost) price + FROM recipe + GROUP BY itemFk) r ON r.itemFk = i.id JOIN vn.itemType it ON it.id = i.typeFk - WHERE it.code IN ('FNR','FNP'); + JOIN addressPostCode apc + ON apc.dayOfWeek = dayOfWeek(vLanded) + AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR + AND apc.postCode = vPostalCode + JOIN vn.address a ON a.id = apc.addressFk; SELECT * FROM catalogue @@ -11324,9 +11333,18 @@ BEGIN /** * Set actions for contact request * - * @param vPostalCode Delivery address postal code + * @param vName Name + * @param vPhone Phone number + * @param vEmail e-mail + * @param vMessage text of the message */ - + + CALL vn.mail_insert( + 'floranet@verdnatura.es', + vEmail, + 'Contact request', + CONCAT('Phone: ',vPhone, ' Message: ', vMessage) + ); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11362,7 +11380,7 @@ BEGIN apc.dayOfWeek - vCurrentDayOfWeek, 7 - apc.dayOfWeek ) DAY nextDay, - NOW() + INTERVAL apc.hoursInAdvance - 12 HOUR minDeliveryTime + NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime FROM addressPostCode apc WHERE apc.postCode = vPostalCode HAVING nextDay > minDeliveryTime) sub; @@ -11384,21 +11402,165 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `order_confirm`(vCatalogueFk INT) READS SQL DATA -BEGIN -/** Update order.isPaid field. +proc:BEGIN +/** Update order.isPaid field, and makes the ticket * * @param vCatalogueFk floranet.catalogue.id * * @returns floranet.order.isPaid */ + DECLARE vNewTicketFk INT; + DECLARE vCustomerEmail VARCHAR(255); + DECLARE vFloranetEmail VARCHAR(255); + DECLARE vSubjectEmail VARCHAR(100); + DECLARE vBodyEmail TEXT; + DECLARE vZoneFk INT; + + DECLARE exit handler FOR SQLEXCEPTION + BEGIN + ROLLBACK; + + GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; + + SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')) AS `SQLEXCEPTION`; + + CALL vn.mail_insert( + 'floranet@verdnatura.es,pako@verdnatura.es', + 'noreply@verdnatura.es', + 'Floranet.order_confirm failure', + CONCAT('CatalogueFk: ', vCatalogueFk, '\n','ERROR ', IFNULL(@errno, 0), ': ', ifnull(@text, 'texto')) + ); + END; + + IF (SELECT isPaid FROM `order` WHERE catalogueFk = vCatalogueFk) THEN + SELECT CONCAT('CatalogueFk: ', vCatalogueFk, ' Esta orden ya está confirmada') AS `ERROR`; + LEAVE proc; + END IF; + + START TRANSACTION; + UPDATE `order` SET isPaid = TRUE, payed = NOW() WHERE catalogueFk = vCatalogueFk; - SELECT isPaid + SELECT zoneFk + INTO vZoneFk + FROM ( + SELECT zoneFk, COUNT(*) totalCount + FROM vn.ticket t + JOIN catalogue c ON c.id = vCatalogueFk + WHERE t.shipped > util.VN_CURDATE() - INTERVAL 1 YEAR + AND t.addressFk = c.addressFk + GROUP BY zoneFk + ORDER BY totalCount DESC + LIMIT 10000000000000000000 + ) sub + LIMIT 1; + + INSERT INTO vn.ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + routeFk, + companyFk, + landed, + zoneFk + ) + SELECT a.clientFk, + c.dated - INTERVAL 1 DAY, + c.addressFk, + a.agencyModeFk, + a.nickname, + ag.warehouseFk, + NULL, + co.id, + c.dated, + vZoneFk + FROM vn.address a + JOIN vn.agencyMode am ON am.id = a.agencyModeFk + JOIN vn.agency ag ON ag.id = am.agencyFk + JOIN catalogue c ON c.addressFk = a.id + JOIN vn.company co ON co.code = 'VNL' + WHERE c.id = vCatalogueFk; + + SET vNewTicketFk = LAST_INSERT_ID(); + + INSERT INTO vn.sale( + ticketFk, + itemFk, + concept, + price, + quantity) + SELECT + vNewTicketFk, + c.itemFk, + CONCAT('Entrega: ',c.name), + - c.price, + 1 + FROM catalogue c + JOIN addressPostCode apc + ON apc.addressFk = c.addressFk + AND apc.dayOfWeek = dayOfWeek(c.dated) + WHERE c.id = vCatalogueFk; + + INSERT INTO vn.sale( + ticketFk, + itemFk, + concept, + price, + quantity) + SELECT + vNewTicketFk, + r.elementFk, + i.longName, + r.cost, + r.quantity + FROM catalogue c + JOIN recipe r ON r.itemFk = c.itemFk + JOIN vn.item i ON i.id = r.elementFk + WHERE c.id = vCatalogueFk; + + SELECT cl.email, + cf.email, + CONCAT('Nuevo pedido FLORANET para entrega el ',c.dated), + CONCAT_WS('\n', + CONCAT('Producto: ', c.name), + CONCAT('Fecha de entrega: ',c.dated), + CONCAT('Destinatario: ', o.deliveryName), + CONCAT('Dirección: ', o.address), + CONCAT('CP: ', c.postalCode), + CONCAT('Foto: ', c.image), + CONCAT('Mensaje: ', IFNULL(o.message,"Ninguno.")), + CONCAT('Teléfono: ',IFNULL(o.deliveryPhone,"--")), + CONCAT('Observaciones: ', IFNULL(o.observations,"No hay.")) + ) + INTO vCustomerEmail, + vFloranetEmail, + vSubjectEmail, + vBodyEmail + FROM vn.client cl + JOIN vn.address a ON a.clientFk = cl.id + JOIN catalogue c ON c.addressFk = a.id + JOIN `order` o ON o.catalogueFk = c.id + JOIN config cf + WHERE c.id = vCatalogueFk; + + CALL vn.mail_insert( + vCustomerEmail, + vFloranetEmail, + vSubjectEmail, + vBodyEmail); + + SELECT isPaid, vNewTicketFk FROM `order` WHERE catalogueFk = vCatalogueFk; + + COMMIT; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11423,7 +11585,7 @@ BEGIN * * @param vJsonData The order data in json format */ - INSERT INTO `order` + REPLACE `order` SET catalogueFk = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.products[0].id')), customerName = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.customerName')), email = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.email')), @@ -11431,7 +11593,8 @@ BEGIN message= JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.message')), deliveryName = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.deliveryName')), address = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.address')), - deliveryPhone = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.deliveryPhone')); + deliveryPhone = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.deliveryPhone')), + observations = JSON_UNQUOTE(JSON_EXTRACT(vJsonData, '$.customer.customerData.observations')); SELECT LAST_INSERT_ID() orderFk; END ;; @@ -11457,13 +11620,12 @@ BEGIN * Returns list of url for sliders. */ SELECT - CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image) url, - i.longName - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - WHERE it.code IN ('FNR','FNP') - LIMIT 3; - + CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image) url, + i.longName + FROM vn.item i + JOIN vn.itemType it ON it.id = i.typeFk + WHERE it.code IN ('FNR','FNP') + LIMIT 3; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -24856,6 +25018,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `midnight`() RETURNS datetime READS SQL DATA + DETERMINISTIC BEGIN RETURN TIMESTAMP(util.VN_CURDATE(), '23:59:59'); @@ -25935,14 +26098,14 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_commit`(isTx BOOL) +CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_commit`(vIsTx BOOL) BEGIN /** * Confirma los cambios asociados a una transacción. * - * @param isTx es true si existe transacción asociada + * @param vIsTx es true si existe transacción asociada */ - IF isTx THEN + IF vIsTx THEN COMMIT; END IF; END ;; @@ -25961,14 +26124,14 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_rollback`(isTx BOOL) +CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_rollback`(vIsTx BOOL) BEGIN /** * Deshace los cambios asociados a una transacción. * - * @param isTx es true si existe transacción asociada + * @param vIsTx es true si existe transacción asociada */ - IF isTx THEN + IF vIsTx THEN ROLLBACK; END IF; END ;; @@ -25987,14 +26150,14 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_start`(isTx BOOL) +CREATE DEFINER=`root`@`localhost` PROCEDURE `tx_start`(vIsTx BOOL) BEGIN /** * Inicia una transacción. * - * @param isTx es true si existe transacción asociada + * @param vIsTx es true si existe transacción asociada */ - IF isTx THEN + IF vIsTx THEN START TRANSACTION; END IF; END ;; @@ -32529,6 +32692,7 @@ CREATE TABLE `item` ( `nonRecycledPlastic` decimal(10,2) DEFAULT NULL, `minQuantity` int(10) unsigned DEFAULT NULL COMMENT 'Cantidad mínima para una línea de venta', `isBoxPickingMode` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'FALSE: using item.packingOut TRUE: boxPicking using itemShelving.packing', + `photoMotivation` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `item_supplyResponseFk_idx` (`supplyResponseFk`), KEY `Color` (`inkFk`), @@ -34183,6 +34347,14 @@ CREATE TABLE `mrwConfig` ( `password` varchar(100) DEFAULT NULL, `franchiseCode` varchar(100) DEFAULT NULL, `subscriberCode` varchar(100) DEFAULT NULL, + `defaultHeight` int(10) unsigned DEFAULT NULL COMMENT 'default height in centimeters', + `defaultLength` int(10) unsigned DEFAULT NULL COMMENT 'default length in centimeters', + `defaultWidth` int(10) unsigned DEFAULT NULL COMMENT 'default width in centimeters', + `defaultWeight` int(10) unsigned DEFAULT NULL COMMENT 'default weight in centimeters', + `expeditionDeadLine` time DEFAULT NULL COMMENT 'This field stores the latest time by which expeditions can be generated to be sent today', + `counterWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', + `serviceTypeWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', + `portugalPostCodeTrim` int(10) unsigned DEFAULT NULL COMMENT 'It will trim the last characters of the postal code', PRIMARY KEY (`id`), CONSTRAINT `mrwConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -35631,6 +35803,7 @@ CREATE TABLE `productionConfig` ( `collection_assign_lockname` varchar(100) DEFAULT 'collection_assign' COMMENT 'Lockname value for proc vn.collection_new', `defaultSectorFk` int(10) unsigned NOT NULL DEFAULT 37 COMMENT 'Default sector', `scannableCodeType` enum('qr','barcode') NOT NULL DEFAULT 'barcode', + `scannablePreviusCodeType` enum('qr','barcode') NOT NULL DEFAULT 'barcode', PRIMARY KEY (`id`), KEY `productionConfig_FK` (`shortageAddressFk`), KEY `productionConfig_FK_1` (`clientSelfConsumptionFk`), @@ -38881,6 +39054,7 @@ CREATE TABLE `ticketLog` ( KEY `logTicketuserFk` (`userFk`), KEY `ticketLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`), KEY `ticketLog_originFk` (`originFk`,`creationDate`), + KEY `ticketLog_creationDate_IDX` (`creationDate`,`changedModel`,`action`) USING BTREE, CONSTRAINT `ticketLog_user` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci `PAGE_COMPRESSED`=1; /*!40101 SET character_set_client = @saved_cs_client */; @@ -42520,10 +42694,7 @@ BEGIN */ DECLARE vClient INT DEFAULT NULL; - -- SET vPhone = vPhone COLLATE 'utf8_unicode_ci'; - - DROP TEMPORARY TABLE IF EXISTS tClient; - CREATE TEMPORARY TABLE tClient + CREATE OR REPLACE TEMPORARY TABLE tClient ENGINE = MEMORY SELECT id clientFk FROM `client` @@ -42536,13 +42707,14 @@ BEGIN OR mobile = vPhone UNION SELECT clientFk - FROM vn.clientContact + FROM clientContact WHERE phone = vPhone; SELECT t.clientFk INTO vClient FROM tClient t JOIN `client` c ON c.id = t.clientFk WHERE c.isActive + AND c.salesPersonFk LIMIT 1; DROP TEMPORARY TABLE tClient; @@ -45818,7 +45990,7 @@ BEGIN DECLARE vIsTooLittle TINYINT(1); SELECT (SUM(IFNULL(sv.litros, 0)) < vc.minTicketVolume - OR IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle + AND IFNULL(t.totalWithoutVat, 0) < vc.minTicketValue) INTO vIsTooLittle FROM ticket t LEFT JOIN saleVolume sv ON sv.ticketFk = t.id JOIN volumeConfig vc @@ -51162,28 +51334,12 @@ BEGIN * @param vCollectionFk Id de colección */ DECLARE vHasTooMuchCollections BOOL; - DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vWarehouseFk INT; - DECLARE vLockName VARCHAR(215); - DECLARE vLockTime INT DEFAULT 30; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF vLockName IS NOT NULL THEN - DO RELEASE_LOCK(vLockName); - CALL util.debugAdd('releaseLock', vLockName); -- Tmp - END IF; - - RESIGNAL; - END; -- Si hay colecciones sin terminar, sale del proceso CALL collection_get(vUserFk); - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, - collection_assign_lockname - INTO vHasTooMuchCollections, - vLockName + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 + INTO vHasTooMuchCollections FROM productionConfig pc LEFT JOIN tCollection ON TRUE; @@ -51193,21 +51349,6 @@ BEGIN CALL util.throw('Hay colecciones pendientes'); END IF; - SELECT warehouseFk, itemPackingTypeFk - INTO vWarehouseFk, vItemPackingTypeFk - FROM operator - WHERE workerFk = vUserFk; - - SET vLockName = CONCAT_WS('/', - vLockName, - vWarehouseFk, - vItemPackingTypeFk - ); - - IF NOT GET_LOCK(vLockName, vLockTime) THEN - CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); - END IF; - -- Se eliminan las colecciones sin asignar que estan obsoletas INSERT INTO ticketTracking(stateFk, ticketFk) SELECT s.id, tc.ticketFk @@ -51215,7 +51356,7 @@ BEGIN JOIN ticketCollection tc ON tc.collectionFk = c.id JOIN `state` s ON s.code = 'PRINTED_AUTO' JOIN productionConfig pc - WHERE c.workerFk IS NULL + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* @@ -51229,8 +51370,7 @@ BEGIN VALUES(vUserFk); -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) - INTO vCollectionFk + SELECT MIN(c.id) INTO vCollectionFk FROM `collection` c JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) @@ -51256,116 +51396,6 @@ BEGIN UPDATE `collection` SET workerFk = vUserFk WHERE id = vCollectionFk; - - DO RELEASE_LOCK(vLockName); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `collection_assign2` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign2`( - vUserFk INT, - OUT vCollectionFk INT -) -proc:BEGIN -/** - * Comprueba si existen colecciones libres que se ajustan - * al perfil del usuario y le asigna la más antigua. - * Añade un registro al semillero de colecciones. - * - * @param vUserFk Id de usuario - * @param vCollectionFk Id de colección - */ - DECLARE vHasTooMuchCollections BOOL; - DECLARE vLockTime INT DEFAULT 15; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('collection_assign2'); - - RESIGNAL; - END; - - -- Si hay colecciones sin terminar, sale del proceso - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections - FROM tCollection - JOIN productionConfig pc ; - - DROP TEMPORARY TABLE tCollection; - - IF vHasTooMuchCollections THEN - CALL util.throw('Hay colecciones pendientes'); - LEAVE proc; - END IF; - - IF NOT GET_LOCK('collection_assign2',vLockTime) THEN - LEAVE proc; - END IF; - - -- Se eliminan las colecciones sin asignar que estan obsoletas - INSERT INTO ticketTracking(stateFk, ticketFk) - SELECT s.id, tc.ticketFk - FROM `collection` c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN `state` s ON s.code = 'PRINTED_AUTO' - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - DELETE c.* - FROM `collection` c - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - INSERT INTO collectionHotbed(userFk) - VALUES(vUserFk); - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) - INTO vCollectionFk - FROM `collection` c - JOIN operator o - ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk - AND c.workerFk IS NULL - AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) - JOIN ( - SELECT tc.collectionFk, SUM(sv.volume) volume - FROM ticketCollection tc - JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk - WHERE sv.shipped >= util.VN_CURDATE() - GROUP BY tc.collectionFk - ) sub ON sub.collectionFk = c.id - AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) - WHERE o.workerFk = vUserFk; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - END IF; - - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; - - DO RELEASE_LOCK('collection_assign2'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51663,7 +51693,10 @@ BEGIN BEGIN IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); - CALL util.debugAdd('releaseLock', vLockName); -- Tmp + CALL util.debugAdd(JSON_OBJECT( + 'type', 'releaseLock', + 'userFk', vUserFk + ), vLockName); -- Tmp END IF; RESIGNAL; @@ -53435,12 +53468,12 @@ BEGIN * * @param vDuaFk Id del dua a recalcular */ - DECLARE done BOOL DEFAULT FALSE; + DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; - DECLARE vASIEN BIGINT DEFAULT 0; - DECLARE vCounter INT DEFAULT 0; + DECLARE vBookEntry INT; + DECLARE vFiscalYear INT; - DECLARE rs CURSOR FOR + DECLARE vInvoicesIn CURSOR FOR SELECT DISTINCT e.invoiceInFk FROM entry e JOIN duaEntry de ON de.entryFk = e.id @@ -53449,9 +53482,7 @@ BEGIN AND de.customsValue AND ii.isBooked = FALSE; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - OPEN rs; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; UPDATE invoiceIn ii JOIN entry e ON e.invoiceInFk = ii.id @@ -53465,38 +53496,36 @@ BEGIN e.isConfirmed = TRUE WHERE d.id = vDuaFk; - SELECT IFNULL(ASIEN,0) INTO vASIEN - FROM dua - WHERE id = vDuaFk; + SELECT ASIEN INTO vBookEntry FROM dua WHERE id = vDuaFk; - FETCH rs INTO vInvoiceFk; + IF vBookEntry IS NULL THEN + SELECT YEAR(IFNULL(ii.bookEntried, d.bookEntried)) INTO vFiscalYear + FROM invoiceIn ii + JOIN entry e ON e.invoiceInFk = ii.id + JOIN duaEntry de ON de.entryFk = e.id + JOIN dua d ON d.id = de.duaFk + WHERE d.id = vDuaFk + LIMIT 1; + CALL ledger_nextTx(vFiscalYear, vBookEntry); + END IF; - WHILE NOT done DO + OPEN vInvoicesIn; - CALL invoiceIn_booking(vInvoiceFk); - - IF vCounter > 0 OR vASIEN > 0 THEN - - UPDATE XDiario x - JOIN ledgerConfig lc ON lc.lastBookEntry = x.ASIEN - SET x.ASIEN = vASIEN; - - ELSE - - SELECT lastBookEntry INTO vASIEN FROM ledgerConfig; +l: LOOP + SET vDone = FALSE; + FETCH vInvoicesIn INTO vInvoiceFk; + IF vDone THEN + LEAVE l; END IF; - SET vCounter = vCounter + 1; + CALL invoiceIn_booking(vInvoiceFk, vBookEntry); + END LOOP; - FETCH rs INTO vInvoiceFk; - - END WHILE; - - CLOSE rs; + CLOSE vInvoicesIn; UPDATE dua - SET ASIEN = vASIEN + SET ASIEN = vBookEntry WHERE id = vDuaFk; UPDATE invoiceIn ii @@ -53566,7 +53595,7 @@ BEGIN WHERE id = vDuaFk; IF vBookNumber IS NULL OR NOT vBookNumber THEN - CALL ledger_next(YEAR(vBookDated), vBookNumber); + CALL ledger_nextTx(YEAR(vBookDated), vBookNumber); END IF; -- Apunte de la aduana @@ -54048,41 +54077,6 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `entry_checkBooked` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_checkBooked`( - vSelf INT -) -BEGIN -/** - * Comprueba si una entrada está contabilizada, - * y si lo está retorna un throw. - * - * @param vSelf Id de entrada - */ - DECLARE vIsBooked BOOL; - - SELECT isBooked INTO vIsBooked - FROM `entry` - WHERE id = vSelf; - - IF vIsBooked AND NOT IFNULL(@isModeInventory, FALSE) THEN - CALL util.throw('Entry is already booked'); - END IF; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `entry_checkPackaging` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; @@ -54599,6 +54593,43 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `entry_isEditable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_isEditable`( + vSelf INT +) +BEGIN +/** + * Comprueba si una entrada se puede actualizar + * si no se puede retorna un throw. + * + * @param vSelf Id de entrada + */ + DECLARE vIsEditable BOOL; + + SELECT e.isBooked INTO vIsEditable + FROM `entry` e + JOIN entryType et ON et.code = e.typeFk + WHERE NOT et.isInformal + AND e.id = vSelf; + + IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN + CALL util.throw('Entry is not editable'); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `entry_lock` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -55150,7 +55181,8 @@ BEGIN JOIN vn.travel t ON t.id = e.travelFk JOIN vn.warehouse w ON w.id = t.warehouseInFk WHERE t.shipped >= util.VN_CURDATE() - AND e.currencyFk = vCurrency; + AND e.currencyFk = vCurrency + AND NOT e.isBooked; SET vComission = currency_getCommission(vCurrency); @@ -57311,9 +57343,19 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_booking`(vSelf INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_booking`( + vSelf INT, + vBookNumber INT +) BEGIN - DECLARE vBookNumber INT; +/** + * Genera la contabilidad para una factura y la marca como contabilizada + * Cuadra el asiento generado en si encuentra problemas derivados + * de los calculos con decimales + * + * @param vSelf Id invoiceIn + * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo + */ DECLARE vFiscalYear INT; CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn @@ -57370,7 +57412,10 @@ BEGIN WHERE ii.id = vSelf; SELECT YEAR(bookEntried) INTO vFiscalYear FROM tInvoiceIn LIMIT 1; - CALL ledger_next(vFiscalYear, vBookNumber); + + IF vBookNumber IS NULL THEN + CALL ledger_nextTx(vFiscalYear, vBookNumber); + END IF; -- Apunte del proveedor INSERT INTO XDiario( @@ -57499,7 +57544,7 @@ BEGIN LEFT JOIN ( SELECT e.id FROM tInvoiceIn tii - JOIN expense e ON e.id = tii.expenseFk + JOIN expense e ON e.id = tii.expenseFk WHERE e.isWithheld LIMIT 1 ) eWithheld ON TRUE @@ -57776,7 +57821,7 @@ BEGIN WHERE io.id = vInvoice; SELECT YEAR(FECHA) INTO vFiscalYear FROM rs LIMIT 1; - CALL ledger_next(vFiscalYear, vBookNumber); + CALL ledger_nextTx(vFiscalYear, vBookNumber); -- Linea del cliente INSERT INTO XDiario( ASIEN, @@ -60051,13 +60096,15 @@ BEGIN SELECT itemFk, packing, - created + created, + buyFk FROM itemShelving WHERE id = vItemShelvingFk ) ish2 ON ish2.itemFk = ish.itemFk AND ish2.packing = ish.packing AND date(ish2.created) = date(ish.created) + AND ish2.buyFk = ish.buyFk WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; IF vNewItemShelvingFk THEN @@ -60094,7 +60141,6 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) BEGIN - /** * Añade registro o lo actualiza si ya existe. * @@ -60107,11 +60153,23 @@ BEGIN * @param vWarehouseFk indica el sector * **/ - DECLARE vItemFk INT; + DECLARE vBuyFk INT; + + SELECT id INTO vBuyFk + FROM buy WHERE id = vBarcode; SELECT barcodeToItem(vBarcode) INTO vItemFk; + IF vBuyFk IS NULL THEN + CALL cache.last_buy_refresh(FALSE); + + SELECT buy_id INTO vBuyFk + FROM cache.last_buy + WHERE item_id = vItemFk + AND warehouse_id = vWarehouseFk; + END IF; + IF vPacking IS NULL THEN SET vPacking = itemPacking(vBarcode, vWarehouseFk); @@ -60121,31 +60179,32 @@ BEGIN IF (SELECT COUNT(*) FROM itemShelving WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk - AND packing = vPacking) = 1 THEN + AND packing = vPacking + AND buyFk = vBuyFk) THEN UPDATE itemShelving - SET visible = visible+vQuantity + SET visible = visible + vQuantity WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; ELSE - CALL cache.last_buy_refresh(FALSE); - INSERT INTO itemShelving( itemFk, - shelvingFk, - visible, - grouping, - packing, - packagingFk) - SELECT vItemFk, - vShelvingFk, - vQuantity, - IFNULL(vGrouping, b.grouping), - IFNULL(vPacking, b.packing), - IFNULL(vPackagingFk, b.packagingFk) - FROM item i - LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id - WHERE i.id = vItemFk; + INSERT INTO itemShelving( + itemFk, + shelvingFk, + visible, + grouping, + packing, + packagingFk, + buyFk) + SELECT vItemFk, + vShelvingFk, + vQuantity, + IFNULL(vGrouping, b.grouping), + IFNULL(vPacking, b.packing), + IFNULL(vPackagingFk, b.packagingFk), + id + FROM buy b + WHERE id = vBuyFk; END IF; END ;; DELIMITER ; @@ -61478,7 +61537,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_comparative`( vAvailableSince DATE, vBuyerFk INT, vIsFloramondo BOOL, - vCountryFk INT + vCountryFk INT ) proc: BEGIN /** @@ -61495,7 +61554,6 @@ proc: BEGIN * @param tmp.comparativeFilterType(filterFk INT ,itemTypeFk INT) * @return tmp.comparative */ - DECLARE vDayRangeStart DATE; DECLARE vDayRangeEnd DATE; DECLARE w1, w2, w3, w4, w5, w6, w7 INT; @@ -61531,14 +61589,14 @@ proc: BEGIN END IF; SELECT MIN(dated) INTO vDayRangeStart - FROM vn.time + FROM `time` WHERE dated <= vDate GROUP BY period ORDER BY dated desc LIMIT 1 OFFSET vWeekRange; SELECT MAX(dated) INTO vDayRangeEnd - FROM vn.time + FROM `time` WHERE dated >= vDate GROUP BY period ORDER BY dated ASC @@ -61555,12 +61613,11 @@ proc: BEGIN JOIN itemType t ON t.id = i.typeFk JOIN itemCategory c ON c.id = t.categoryFk LEFT JOIN worker w ON w.id = t.workerFk - WHERE (NOT vHasTypeFilter - OR t.id IN (SELECT itemTypeFk FROM tmp.comparativeFilterType)) - AND (vBuyerFk IS NULL - OR t.workerFk = vBuyerFk) - AND (vIsFloramondo IS NULL - OR i.isFloramondo = vIsFloramondo); + WHERE (NOT vHasTypeFilter OR t.id IN ( + SELECT itemTypeFk FROM tmp.comparativeFilterType + )) + AND (vBuyerFk IS NULL OR t.workerFk = vBuyerFk) + AND (vIsFloramondo IS NULL OR i.isFloramondo = vIsFloramondo); IF vDate < util.VN_CURDATE() THEN ALTER TABLE tmp.itemInventory @@ -61587,10 +61644,11 @@ proc: BEGIN SET i = i + 1; SELECT t.period INTO vPeriod - FROM vn.`time` t + FROM `time` t WHERE t.dated = vDayRangeStart + INTERVAL (vWeekCount * (i - 1)) DAY; - INSERT IGNORE INTO tTable(cy, ly, zy) VALUES(vPeriod, vPeriod - 100, vPeriod - 200); + INSERT IGNORE INTO tTable(cy, ly, zy) + VALUES(vPeriod, vPeriod - 100, vPeriod - 200); UNTIL i = vWeekCount END REPEAT; SELECT cy, ly, zy INTO w1, y1, z1 FROM tTable LIMIT 1; @@ -61602,7 +61660,6 @@ proc: BEGIN SELECT cy, ly, zy INTO w7, y7, z7 FROM tTable WHERE cy > w6 LIMIT 1; -- Genera una tabla con los datos del año pasado. - CREATE OR REPLACE TEMPORARY TABLE tLastYear (KEY (lItemFk)) ENGINE = MEMORY @@ -61623,15 +61680,14 @@ proc: BEGIN SUM(IF(c.timePeriod = y7, c.price, 0)) lprice7 FROM tmp.itemInventory ai JOIN comparative c ON c.itemFk = ai.id - JOIN warehouse w on w.id = c.warehouseFk + JOIN warehouse w ON w.id = c.warehouseFk JOIN tTable wt ON c.timePeriod = wt.ly - WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk + WHERE (vWarehouseFk IS NULL OR vWarehouseFk = c.warehouseFk) AND w.isComparative AND (vCountryFk IS NULL OR c.countryFk = vCountryFk) GROUP BY ai.id; - -- Genera una tabla con los datos de hace DOS años. - + -- Genera una tabla con los datos de hace 2 años CREATE OR REPLACE TEMPORARY TABLE tTwoYearsAgo (KEY (tItemFk)) ENGINE = MEMORY @@ -61652,73 +61708,72 @@ proc: BEGIN SUM(IF(c.timePeriod = z7, c.price, 0)) vlprice7 FROM tmp.itemInventory ai JOIN comparative c ON c.itemFk = ai.id - JOIN warehouse w on w.id = c.warehouseFk + JOIN warehouse w ON w.id = c.warehouseFk JOIN tTable wt ON c.timePeriod = wt.zy - WHERE IFNULL(vWarehouseFk, c.warehouseFk) = c.warehouseFk + WHERE (vWarehouseFk IS NULL OR vWarehouseFk = c.warehouseFk) AND w.isComparative AND (vCountryFk IS NULL OR c.countryFk = vCountryFk) GROUP BY ai.id; - -- Genera una tabla con los datos de este año.ss - + -- Genera una tabla con los datos de este año CREATE OR REPLACE TEMPORARY TABLE tCurrentYear (KEY (cItemFk)) ENGINE = MEMORY SELECT t.itemFk cItemFk, - SUM(IF(week = w1, total, 0)) cweek1, - SUM(IF(week = w2, total, 0)) cweek2, - SUM(IF(week = w3, total, 0)) cweek3, - SUM(IF(week = w4, total, 0)) cweek4, - SUM(IF(week = w5, total, 0)) cweek5, - SUM(IF(week = w6, total, 0)) cweek6, - SUM(IF(week = w7, total, 0)) cweek7, - SUM(IF(week = w1, price, 0)) cprice1, - SUM(IF(week = w2, price, 0)) cprice2, - SUM(IF(week = w3, price, 0)) cprice3, - SUM(IF(week = w4, price, 0)) cprice4, - SUM(IF(week = w5, price, 0)) cprice5, - SUM(IF(week = w6, price, 0)) cprice6, - SUM(IF(week = w7, price, 0)) cprice7 + SUM(IF(`week` = w1, total, 0)) cweek1, + SUM(IF(`week` = w2, total, 0)) cweek2, + SUM(IF(`week` = w3, total, 0)) cweek3, + SUM(IF(`week` = w4, total, 0)) cweek4, + SUM(IF(`week` = w5, total, 0)) cweek5, + SUM(IF(`week` = w6, total, 0)) cweek6, + SUM(IF(`week` = w7, total, 0)) cweek7, + SUM(IF(`week` = w1, price, 0)) cprice1, + SUM(IF(`week` = w2, price, 0)) cprice2, + SUM(IF(`week` = w3, price, 0)) cprice3, + SUM(IF(`week` = w4, price, 0)) cprice4, + SUM(IF(`week` = w5, price, 0)) cprice5, + SUM(IF(`week` = w6, price, 0)) cprice6, + SUM(IF(`week` = w7, price, 0)) cprice7 FROM ( SELECT s.itemFk, ti.period `week`, SUM(s.quantity) total, - TRUNCATE(SUM(s.quantity * s.priceFixed),0) price - FROM ticket t + TRUNCATE(SUM(s.quantity * s.priceFixed), 0) price + FROM ticket t FORCE INDEX (Fecha) JOIN sale s ON t.id = s.ticketFk - JOIN tmp.itemInventory it ON it.id = s.itemFk - JOIN time ti ON ti.dated = DATE(t.shipped) + JOIN tmp.itemInventory it ON it.id = s.itemFk + JOIN `time` ti ON ti.dated = DATE(t.shipped) 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 warehouse w ON w.id = t.warehouseFk - STRAIGHT_JOIN address ad ON ad.id = t.addressFk - JOIN province p ON p.id = ad.provinceFk + JOIN `address` ad ON ad.id = t.addressFk + JOIN province p ON p.id = ad.provinceFk JOIN `client` c ON c.id = ad.clientFk WHERE t.shipped BETWEEN vDayRangeStart AND util.dayEnd(vDayRangeEnd) - AND c.typeFk IN ('Normal','handMaking') - AND w.id = COALESCE(vWarehouseFk, w.id) + AND c.typeFk IN ('normal', 'handMaking') + AND (vWarehouseFk IS NULL OR vWarehouseFk = w.id) + AND (vCountryFk IS NULL OR p.countryFk = vCountryFk) AND w.isComparative - AND (vCountryFk IS NULL OR p.countryFk = vCountryFk) - GROUP BY i.id, week + GROUP BY i.id, `week` ) t GROUP BY t.itemFk; - -- Genera la tabla con la comparativa. + -- Genera la tabla con la comparativa CREATE OR REPLACE TEMPORARY TABLE tmp.comparative ENGINE = MEMORY - SELECT it.subName productor, - b.packing, + SELECT it.subName productor, + b.packing, b.buyingValue costefijo, b.groupingMode caja, it.image ArticleImage, - IFNULL(it.inkFk,"?") color, + IFNULL(it.inkFk, '?') color, tp.code tipo, it.typeFk tipo_id, o.code origen, it.category categoria, it.stems tallos, - it.size medida, + it.`size` medida, it.name article, w.code codigoTrabajador, tp.categoryFk reino_id, @@ -61729,24 +61784,27 @@ proc: BEGIN it.id Id_Article, i.buy_id, tp.life, - IFNULL(i.sd,0) sd, + IFNULL(i.sd, 0) sd, i.avalaible, i.visible, i.buy_date, e.id provider_id, it.comment comments, it.description itemDescription, - IF(cy.cItemFk IS NULL AND i.visible = 0 AND i.avalaible = 0 - AND IFNULL(i.sd, 0) = 0, FALSE, TRUE) filtret, + IF(cy.cItemFk IS NULL AND i.visible = 0 + AND i.avalaible = 0 AND (i.sd IS NULL OR i.sd = 0), + FALSE, + TRUE + ) filtret, IF(it.hasMinPrice, FORMAT(it.minPrice, 2), "") pvp, s.company_name FROM tmp.itemInventory i JOIN item it ON it.id = i.id - LEFT JOIN itemType tp ON tp.id = it.typeFk - LEFT JOIN worker w ON w.id = tp.workerFk + JOIN itemType tp ON tp.id = it.typeFk + JOIN worker w ON w.id = tp.workerFk LEFT JOIN buy b ON b.id = i.buy_id - LEFT JOIN entry e ON e.id = b.entryFk - LEFT JOIN origin o ON o.id = it.originFk + LEFT JOIN `entry` e ON e.id = b.entryFk + JOIN origin o ON o.id = it.originFk LEFT JOIN tLastYear ly ON ly.lItemFk = it.id LEFT JOIN tCurrentYear cy ON cy.cItemFk = it.id LEFT JOIN tTwoYearsAgo zy ON zy.tItemFk = it.id @@ -61759,8 +61817,8 @@ proc: BEGIN OR ly.lweek1 OR ly.lweek2 OR ly.lweek3 OR ly.lweek4 OR ly.lweek5 OR ly.lweek6 OR ly.lweek7 OR zy.vlweek1 OR zy.vlweek2 OR zy.vlweek3 OR zy.vlweek4 OR zy.vlweek5 OR zy.vlweek6 OR zy.vlweek7; - -- Elimina las tablas temporales creadas... - DROP TEMPORARY TABLE IF EXISTS tmp.itemInventory, + DROP TEMPORARY TABLE IF EXISTS + tmp.itemInventory, tTwoYearsAgo, tLastYear, tCurrentYear, @@ -63551,256 +63609,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `item_ValuateInventory` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `item_ValuateInventory`(vDated DATE, vIsDetailed BOOLEAN) -BEGIN - DECLARE vInventoried DATE; - DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE; - DECLARE vInventoryClone DATE; - DECLARE vDateDayEnd DATETIME; - DECLARE vInventorySupplierFk INT; - - SELECT inventorySupplierFk INTO vInventorySupplierFk - FROM entryConfig; - - SET vDateDayEnd = util.dayEnd(vDated); - - SELECT tr.landed INTO vInventoried - FROM travel tr - JOIN `entry` e ON e.travelFk = tr.id - JOIN entryConfig ec - WHERE landed <= vDateDayEnd - AND e.supplierFk = vInventorySupplierFk - ORDER BY tr.landed DESC - LIMIT 1; - - SET vHasNotInventory = (vInventoried IS NULL); - - IF vHasNotInventory THEN - SELECT landed INTO vInventoryClone - FROM travel tr - JOIN `entry` e ON e.travelFk = tr.id - JOIN entryConfig ec - WHERE landed >= vDated - AND e.supplierFk = vInventorySupplierFk - ORDER BY landed ASC - LIMIT 1; - - SET vInventoried = vDated + INTERVAL 1 DAY; - SET vDateDayEnd = vInventoryClone; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tInventory( - warehouseFk SMALLINT, - itemFk BIGINT, - quantity INT, - cost DOUBLE DEFAULT 0, - total DOUBLE DEFAULT 0, - warehouseInventory VARCHAR(20), - PRIMARY KEY (warehouseInventory, itemFk) USING HASH - ) - ENGINE = MEMORY; - - -- Inventario inicial - IF vHasNotInventory THEN - INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) - SELECT tr.warehouseInFk, - b.itemFk, - SUM(b.quantity), - w.name - FROM buy b - JOIN item i ON i.id = b.itemFk - JOIN `entry` e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN itemType t ON t.id = i.typeFk - JOIN warehouse w ON w.id = warehouseInFk - JOIN entryConfig ec - WHERE landed = vDateDayEnd - AND e.supplierFk = vInventorySupplierFk - AND w.valuatedInventory - AND t.isInventory - GROUP BY tr.warehouseInFk, b.itemFk; - ELSE - INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) - SELECT tr.warehouseInFk, - b.itemFk, - SUM(b.quantity), - w.name - FROM buy b - JOIN item i ON i.id = b.itemFk - JOIN `entry` e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN itemType t ON t.id = i.typeFk - JOIN warehouse w ON w.id = warehouseInFk - JOIN entryConfig ec - WHERE landed = vInventoried - AND e.supplierFk = vInventorySupplierFk - AND w.valuatedInventory - AND t.isInventory - GROUP BY tr.warehouseInFk, b.itemFk; - END IF; - - -- Añadimos las entradas - INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) - SELECT tr.warehouseInFk, - b.itemFk, - b.quantity * IF(vHasNotInventory, -1, 1), - w.name - FROM buy b - JOIN item i ON i.id = b.itemFk - JOIN `entry` e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN itemType t ON t.id = i.typeFk - JOIN warehouse w ON w.id = tr.warehouseInFk - JOIN entryConfig ec - WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd - AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE) - AND NOT e.isRaid - AND w.valuatedInventory - AND t.isInventory - AND e.supplierFk <> vInventorySupplierFk - ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory, -1, 1)); - - -- Descontamos las salidas - INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) - SELECT tr.warehouseOutFk, - b.itemFk, - b.quantity * IF(vHasNotInventory, 1, -1), - w.name - FROM buy b - JOIN item i ON i.id = b.itemFk - JOIN `entry` e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN itemType t ON t.id = i.typeFk - JOIN warehouse w ON w.id = tr.warehouseOutFk - WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd - AND NOT e.isRaid - AND w.valuatedInventory - AND t.isInventory - ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory,1,-1)); - - -- Descontamos las lineas de venta - INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) - SELECT w.id, - s.itemFk, - s.quantity * IF(vHasNotInventory, 1, -1), - w.name - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN `client` c ON c.id = t.clientFk - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vInventoried AND vDateDayEnd - AND w.valuatedInventory - AND it.isInventory - ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1); - - -- Volver a poner lo que esta aun en las estanterias - IF vDated = util.VN_CURDATE() THEN - INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) - SELECT w.id, - s.itemFk, - s.quantity * IF(vHasNotInventory, 0, 1), - w.name - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN `client` c ON c.id = t.clientFk - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDated AND vDateDayEnd - AND NOT (s.isPicked OR t.isLabeled) - AND w.valuatedInventory - AND it.isInventory - ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 0, 1); - END IF; - - -- Mercancia en transito - INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) - SELECT tr.warehouseInFk, - b.itemFk, - b.quantity, - CONCAT(wOut.`name`, ' - ', wIn.`name`) - FROM buy b - JOIN item i ON i.id = b.itemFk - JOIN `entry` e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN itemType t ON t.id = i.typeFk - JOIN warehouse wIn ON wIn.id = tr.warehouseInFk - JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk - WHERE vDated >= tr.shipped AND vDated < tr.landed - AND NOT isRaid - AND wIn.valuatedInventory - AND t.isInventory - AND e.isConfirmed - ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity); - - CALL vn.buyUltimate(NULL, vDateDayEnd); - - UPDATE tInventory i - JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.itemFk = bu.itemFk - JOIN buy b ON b.id = bu.buyFk - SET total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)), - cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0) - WHERE i.quantity; - - DELETE FROM tInventory - WHERE quantity IS NULL OR NOT quantity; - - IF vIsDetailed THEN - SELECT ti.warehouseFk, - i.id itemFk, - i.longName, - i.size, - ti.quantity, - tp.name Tipo, - ic.name Reino, - ti.cost, - CAST(ti.total AS DECIMAL(10, 2)) total, - ti.warehouseInventory almacen - FROM tInventory ti - JOIN warehouse w ON w.id = warehouseFk - JOIN item i ON i.id = ti.itemFk - JOIN itemType tp ON tp.id = i.typeFk - JOIN itemCategory ic ON ic.id = tp.categoryFk - WHERE w.valuatedInventory - AND ti.total > 0 - ORDER BY ti.total DESC; - ELSE - SELECT i.warehouseInventory Almacen, - ic.name Reino, - CAST(i.total AS DECIMAL(10, 2)) Euros, - w.code Comprador, - it.id - FROM tInventory i - JOIN warehouse wh ON wh.id = warehouseFk - JOIN item it ON it.id = i.itemFk - JOIN itemType itp ON itp.id = it.typeFk - LEFT JOIN worker w ON w.id = itp.workerFk - JOIN itemCategory ic ON ic.id = itp.categoryFk - WHERE wh.valuatedInventory - AND i.total > 0; - END IF; - - DROP TEMPORARY TABLE - tmp.buyUltimate, - tInventory; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `item_zoneClosure` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -63876,7 +63684,7 @@ BEGIN DECLARE vIsOriginalAClient BOOL; DECLARE vPayMethodCompensation INT; - CALL ledger_next(YEAR(vDated), vNewBookEntry); + CALL ledger_nextTx(YEAR(vDated), vNewBookEntry); SELECT COUNT(id) INTO vIsOriginalAClient FROM client @@ -63974,32 +63782,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_next`( OUT vLastBookEntry INT ) BEGIN - DECLARE vHasStartTransaction BOOLEAN; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - - IF vHasStartTransaction THEN - ROLLBACK TO sp; - RESIGNAL; - ELSE - ROLLBACK; - CALL util.throw ('It has not been possible to generate a new ledger'); - END IF; - END; - IF vFiscalYear IS NULL THEN CALL util.throw('Fiscal year is required'); END IF; - SELECT @@in_transaction INTO vHasStartTransaction; - - IF NOT vHasStartTransaction THEN - START TRANSACTION; - ELSE - SAVEPOINT sp; - END IF; - SELECT bookEntry + 1 INTO vLastBookEntry FROM ledgerCompany WHERE fiscalYear = vFiscalYear @@ -64015,12 +63801,41 @@ BEGIN UPDATE ledgerCompany SET bookEntry = vLastBookEntry WHERE fiscalYear = vFiscalYear; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ledger_nextTx` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_nextTx`( + IN vFiscalYear INT, + OUT vLastBookEntry INT +) +BEGIN + DECLARE vIsRequiredTx BOOL DEFAULT NOT @@in_transaction; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + CALL util.tx_rollback(vIsRequiredTx); + RESIGNAL; + END; - IF vHasStartTransaction THEN - RELEASE SAVEPOINT sp; - ELSE - COMMIT; - END IF; + IF vFiscalYear IS NULL THEN + CALL util.throw('Fiscal year is required'); + END IF; + + CALL util.tx_start(vIsRequiredTx); + CALL ledger_next(vFiscalYear, vLastBookEntry); + CALL util.tx_commit(vIsRequiredTx); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65713,13 +65528,19 @@ proc: BEGIN -- Líneas y volumen por ticket UPDATE tmp.productionBuffer pb JOIN ( - SELECT tt.ticketFk, - COUNT(*) `lines`, - SUM(sv.volume) m3, - IFNULL(SUM(IF(sv.isPicked, sv.volume, 0)) / SUM(sv.volume), 0) rate - FROM tmp.productionTicket tt - JOIN saleVolume sv ON sv.ticketFk = tt.ticketFk - GROUP BY tt.ticketFk + SELECT tt.ticketFk, + COUNT(*) `lines`, + SUM(s.quantity * ic.cm3delivery / 1000000) m3, + IFNULL(SUM(IF(s.isPicked, + (s.quantity * ic.cm3delivery / 1000000), + 0)) / SUM(s.quantity * ic.cm3delivery / 1000000), + 0) rate + FROM tmp.productionTicket tt + JOIN sale s ON s.ticketFk = tt.ticketFk + AND s.quantity > 0 + JOIN itemCost ic ON ic.itemFk = s.itemFk + AND ic.warehouseFk = vWarehouseFk + GROUP BY tt.ticketFk ) m ON m.ticketFk = pb.ticketFk SET pb.`lines` = m.`lines`, pb.m3 = m.m3, @@ -65786,6 +65607,8 @@ proc: BEGIN AND ish.visible GROUP BY ish.itemFk, p.sectorFk; + CREATE INDEX idxItem ON tItemShelvingStock (itemFk); + INSERT INTO tmp.ticketWithPrevia(ticketFk, salesCount) SELECT pb.ticketFk, COUNT(DISTINCT s.id) FROM tmp.productionBuffer pb @@ -67475,19 +67298,21 @@ BEGIN END; CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + (PRIMARY KEY (id)) + ENGINE = MEMORY SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity FROM sale s JOIN item i ON i.id = s.itemFk JOIN itemType it ON it.id = i.typeFk WHERE s.ticketFk = vTicketFk AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; + GROUP BY s.itemFk, s.price, s.discount; START TRANSACTION; UPDATE sale s JOIN tSalesToPreserve stp ON stp.id = s.id - SET quantity = newQuantity + SET s.quantity = newQuantity WHERE s.ticketFk = vTicketFk; DELETE s.* @@ -68401,10 +68226,15 @@ BEGIN FROM tmp.sale_getProblems tp JOIN ticket t ON t.id = tp.ticketFk JOIN ( - SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat + SELECT t.addressFk, + SUM(ROUND(`ic`.`cm3delivery` * `s`.`quantity` / 1000, 0)) litros, + t.totalWithoutVat FROM tmp.ticket_list tl - JOIN saleVolume sv ON sv.ticketFk = tl.ticketFk JOIN ticket t ON t.id = tl.ticketFk + JOIN sale s ON s.ticketFk = t.id + AND s.quantity > 0 + JOIN itemCost ic ON ic.itemFk = s.itemFk + AND ic.warehouseFk = t.warehouseFk JOIN zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = util.VN_CURDATE() JOIN agencyMode am ON am.id = t.agencyModeFk @@ -68432,12 +68262,12 @@ BEGIN FROM ( SELECT COUNT(s.id) nComp, tl.ticketFk, s.id saleFk FROM tmp.ticket_list tl - JOIN vn.sale s ON s.ticketFk = tl.ticketFk - LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id - LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN sale s ON s.ticketFk = tl.ticketFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN component c ON c.id = sc.componentFk AND c.isRequired + JOIN ticket t ON t.id = tl.ticketFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk WHERE dm.code IN ('AGENCY','DELIVERY','PICKUP') AND s.quantity > 0 GROUP BY s.id @@ -69088,7 +68918,7 @@ BEGIN FROM ticket t JOIN sale s ON s.ticketFk = t.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (vComponentFk IS NULL OR sc.componentFk = vComponentFk) GROUP BY s.id) sub; @@ -71590,14 +71420,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticketPackaging_add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketPackaging_add`( vClientFk INT, @@ -71627,7 +71457,10 @@ BEGIN SELECT DISTINCT clientFk FROM ( SELECT clientFk, SUM(quantity) totalQuantity - FROM tmp.packagingToInvoice + FROM tmp.packagingToInvoice tpi + JOIN client c ON c.id = tpi.clientFk + LEFT JOIN supplier s ON s.nif = c.fi + WHERE s.id IS NULL GROUP BY itemFk, clientFk HAVING totalQuantity > 0)sub; @@ -74661,7 +74494,7 @@ BEGIN ENGINE = MEMORY SELECT t.id ticketFk, FALSE hasProblem FROM ticket t - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (vClientFk IS NULL OR t.clientFk = vClientFk); UPDATE tmp.ticket t @@ -74703,7 +74536,7 @@ BEGIN ENGINE = MEMORY SELECT t.id ticketFk, FALSE hasProblem FROM ticket t - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (vSelf IS NULL OR t.id = vSelf); UPDATE tmp.ticket t @@ -74837,7 +74670,7 @@ BEGIN SELECT t.id ticketFk, IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem FROM ticket t JOIN client c ON c.id = t.clientFk - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (c.id = vClientFk OR vClientFk IS NULL); CALL ticket_setProblem('isTaxDataChecked'); @@ -74909,7 +74742,7 @@ BEGIN SELECT t.id ticketFk FROM vn.ticket t LEFT JOIN vn.sale s ON s.ticketFk = t.id - WHERE t.shipped >= util.midnight() + WHERE t.shipped >= util.VN_CURDATE() AND (s.itemFk = vItemFk OR vItemFk IS NULL) GROUP BY t.id )SELECT ticketFk, ticket_isTooLittle(ticketFk) hasProblem @@ -76481,8 +76314,8 @@ BEGIN DECLARE vEvaNotes VARCHAR(255); DECLARE vDone BOOL; DECLARE vAuxEntryFk INT; - DECLARE vTx BOOLEAN DEFAULT @@in_transaction; - DECLARE vRsEntry CURSOR FOR + DECLARE vIsRequiredTx BOOLEAN DEFAULT NOT @@in_transaction; + DECLARE vRsEntry CURSOR FOR SELECT e.id FROM entry e JOIN travel t ON t.id = e.travelFk @@ -76492,11 +76325,11 @@ BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - CALL util.tx_rollback(vTx); + CALL util.tx_rollback(vIsRequiredTx); RESIGNAL; END; - CALL util.tx_start(vTx); + CALL util.tx_start(vIsRequiredTx); INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, cargoSupplierFk, kg,clonedFrom) SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3,cargoSupplierFk, kg,vTravelFk @@ -76533,7 +76366,7 @@ BEGIN SET @isModeInventory = FALSE; CLOSE vRsEntry; - CALL util.tx_commit(vTx); + CALL util.tx_commit(vIsRequiredTx); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76810,6 +76643,33 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `travel_throwAwb` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_throwAwb`(vSelf INT) +BEGIN +/** + * Throws an error if travel does not have a logical AWB + * or there are several AWBs associated with the same DUA + * + * @param vSelf The travel id + */ + IF NOT travel_hasUniqueAwb(vSelf) THEN + CALL util.throw('A different AWB is found in the entries'); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `travel_upcomingArrivals` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -79979,7 +79839,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `xdiario_new`( ) BEGIN IF vBookNumber IS NULL THEN - CALL ledger_next(YEAR(vDated), vBookNumber); + CALL ledger_nextTx(YEAR(vDated), vBookNumber); END IF; INSERT INTO XDiario @@ -87135,7 +86995,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `ticketPreviousPreparingList` AS select `s`.`ticketFk` AS `ticketFk`,`w`.`code` AS `code`,count(`s`.`id`) AS `saleLines`,sum(`s`.`isPicked` <> 0) AS `alreadyMadeSaleLines`,sum(`s`.`isPicked` <> 0) / count(`s`.`id`) AS `madeRate`,`sg`.`created` AS `created`,`p`.`code` AS `parking`,`iss`.`sectorFk` AS `sectorFk`,`al`.`code` AS `alertCode` from (((((((`saleGroup` `sg` join `saleGroupDetail` `sgd` on(`sgd`.`saleGroupFk` = `sg`.`id`)) join `sale` `s` on(`s`.`id` = `sgd`.`saleFk`)) join `ticketState` `tls` on(`tls`.`ticketFk` = `s`.`ticketFk`)) join `alertLevel` `al` on(`al`.`id` = `tls`.`alertLevel`)) join `worker` `w` on(`w`.`id` = `sg`.`userFk`)) left join `parking` `p` on(`p`.`id` = `sg`.`parkingFk`)) join `itemShelvingStock` `iss` on(`iss`.`itemFk` = `s`.`itemFk`)) where `sg`.`created` >= `util`.`VN_CURDATE`() + interval 0.1 day group by `sg`.`id` */; +/*!50001 VIEW `ticketPreviousPreparingList` AS select `s`.`ticketFk` AS `ticketFk`,`w`.`code` AS `code`,count(`s`.`id`) AS `saleLines`,sum(`s`.`isPicked` <> 0) AS `alreadyMadeSaleLines`,sum(`s`.`isPicked` <> 0) / count(`s`.`id`) AS `madeRate`,`sg`.`created` AS `created`,`p`.`code` AS `parking`,`iss`.`sectorFk` AS `sectorFk`,`al`.`code` AS `alertCode` from (((((((`saleGroup` `sg` join `saleGroupDetail` `sgd` on(`sgd`.`saleGroupFk` = `sg`.`id`)) join `sale` `s` FORCE INDEX (PRIMARY) on(`s`.`id` = `sgd`.`saleFk`)) join `ticketState` `tls` on(`tls`.`ticketFk` = `s`.`ticketFk`)) join `alertLevel` `al` on(`al`.`id` = `tls`.`alertLevel`)) join `worker` `w` on(`w`.`id` = `sg`.`userFk`)) left join `parking` `p` on(`p`.`id` = `sg`.`parkingFk`)) join `itemShelvingStock` `iss` on(`iss`.`itemFk` = `s`.`itemFk`)) where `sg`.`created` >= `util`.`VN_CURDATE`() + interval 0.1 day group by `sg`.`id` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -89855,4 +89715,4 @@ USE `vn2008`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-05-28 6:58:24 +-- Dump completed on 2024-06-11 6:35:36 diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql index fd1042138..b2f550bbe 100644 --- a/db/dump/.dump/triggers.sql +++ b/db/dump/.dump/triggers.sql @@ -2239,7 +2239,7 @@ trig: BEGIN LEAVE trig; END IF; - CALL entry_checkBooked(NEW.entryFk); + CALL entry_isEditable(NEW.entryFk); IF NEW.printedStickers <> 0 THEN CALL util.throw('it is not possible to create buy lines with printedstickers other than 0'); END IF; @@ -2366,7 +2366,7 @@ trig:BEGIN LEAVE trig; END IF; - CALL entry_checkBooked(OLD.entryFk); + CALL entry_isEditable(OLD.entryFk); SET NEW.editorFk = account.myUser_getId(); SELECT defaultEntry INTO vDefaultEntry @@ -2515,7 +2515,7 @@ DELIMITER ;; BEFORE DELETE ON `buy` FOR EACH ROW BEGIN - CALL entry_checkBooked(OLD.entryFk); + CALL entry_isEditable(OLD.entryFk); IF OLD.printedStickers <> 0 THEN CALL util.throw("it is not possible to delete buys with printed labels "); END IF; @@ -4591,8 +4591,8 @@ BEGIN CALL supplier_checkIsActive(NEW.supplierFk); SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); - IF NEW.travelFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.travelFk) THEN - CALL util.throw('The travel is incorrect, there is a different AWB in the associated entries'); + IF NEW.travelFk IS NOT NULL THEN + CALL travel_throwAwb(NEW.travelFk); END IF; END */;; DELIMITER ; @@ -4619,7 +4619,7 @@ BEGIN DECLARE vTotalBuy INT; IF NEW.isBooked = OLD.isBooked THEN - CALL entry_checkBooked(OLD.id); + CALL entry_isEditable(OLD.id); ELSE IF NEW.isBooked THEN SELECT COUNT(*) INTO vTotalBuy @@ -4635,8 +4635,8 @@ BEGIN IF NOT (NEW.travelFk <=> OLD.travelFk) THEN - IF NEW.travelFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.travelFk) THEN - CALL util.throw('The travel is incorrect, there is a different AWB in the associated entries'); + IF NEW.travelFk IS NOT NULL THEN + CALL travel_throwAwb(NEW.travelFk); END IF; SELECT COUNT(*) > 0 INTO vIsVirtual @@ -4721,7 +4721,7 @@ DELIMITER ;; BEFORE DELETE ON `entry` FOR EACH ROW BEGIN - CALL entry_checkBooked(OLD.id); + CALL entry_isEditable(OLD.id); DELETE FROM buy WHERE entryFk = OLD.id; END */;; DELIMITER ; @@ -6783,13 +6783,12 @@ BEGIN DECLARE vIsCash BOOLEAN; DECLARE vIsSupplierActive BOOLEAN; - -- PAK 10/02/15 No se asientan los pagos directamente, salvo en el caso de las cajas de CASH SELECT (at2.code = 'cash') INTO vIsCash FROM accounting a JOIN accountingType at2 ON at2.id = a.accountingTypeFk WHERE a.id = NEW.bankFk; - IF vIsCash THEN + IF vIsCash THEN SELECT account INTO vBankAccount FROM accounting WHERE id = NEW.bankFk; @@ -6798,7 +6797,7 @@ BEGIN FROM supplier WHERE id = NEW.supplierFk; - CALL ledger_next(YEAR(NEW.received), NEW.companyFk, vNewBookEntry); + CALL ledger_next(YEAR(NEW.received), vNewBookEntry); INSERT INTO XDiario ( ASIEN, @@ -8986,7 +8985,9 @@ BEGIN SET hasNewRoute = TRUE WHERE ticketFk = NEW.id; - CALL ticket_doCmr(NEW.id); + IF NEW.cmrFk THEN + CALL ticket_doCmr(NEW.id); + END IF; END IF; END */;; DELIMITER ; @@ -9897,8 +9898,8 @@ BEGIN CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); - IF NEW.awbFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.id) THEN - CALL util.throw('The AWB is incorrect, there is a different AWB in the associated entries'); + IF NEW.awbFk IS NOT NULL THEN + CALL travel_throwAwb(NEW.id); END IF; END */;; DELIMITER ; @@ -9949,8 +9950,8 @@ BEGIN END IF; END IF; - IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.id) THEN - CALL util.throw('The AWB is incorrect, there is a different AWB in the associated entries'); + IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL THEN + CALL travel_throwAwb(NEW.id); END IF; END */;; DELIMITER ; @@ -10824,4 +10825,4 @@ USE `vn2008`; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-05-28 6:58:42 +-- Dump completed on 2024-06-11 6:35:55 -- 2.40.1 From 873f36fef6f96de60f78cb719a8dc74fe3d39352 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 11 Jun 2024 08:50:32 +0200 Subject: [PATCH 165/413] refactor: refs #7503 Added relations and ACLs --- modules/invoiceOut/back/models/invoice-out.json | 5 +++++ modules/ticket/back/models/ticket.json | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/modules/invoiceOut/back/models/invoice-out.json b/modules/invoiceOut/back/models/invoice-out.json index 2bf5182e8..1ee36accb 100644 --- a/modules/invoiceOut/back/models/invoice-out.json +++ b/modules/invoiceOut/back/models/invoice-out.json @@ -44,6 +44,11 @@ "model": "Client", "foreignKey": "clientFk" }, + "user": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "clientFk" + }, "company": { "type": "belongsTo", "model": "Company", diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json index 248c0312f..d1b202f83 100644 --- a/modules/ticket/back/models/ticket.json +++ b/modules/ticket/back/models/ticket.json @@ -77,6 +77,11 @@ "model": "Client", "foreignKey": "clientFk" }, + "user": { + "type": "belongsTo", + "model": "VnUser", + "foreignKey": "clientFk" + }, "warehouse": { "type": "belongsTo", "model": "Warehouse", -- 2.40.1 From f0ad012835aa14e67f0e48fc7f04446653dc5288 Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 11 Jun 2024 09:39:06 +0200 Subject: [PATCH 166/413] refactor: refs #6436 first wave --- .../collection/spec/setSaleQuantity.spec.js | 14 ++-------- .../specs/getStarredModules.spec.js | 22 +++++----------- .../starred-module/specs/setPosition.spec.js | 24 +++++------------ .../specs/toggleStarredModule.spec.js | 26 ++++++------------- db/.pullinfo.json | 2 +- .../methods/vn-model/specs/crud.spec.js | 14 ++-------- .../vn-model/specs/rewriteDbError.spec.js | 14 ++-------- .../entry/specs/editLatestBuys.spec.js | 15 ++--------- .../invoice-in-due-day/specs/new.spec.js | 9 ++----- .../back/models/specs/supplier.spec.js | 15 ++--------- .../travel/specs/createThermograph.spec.js | 14 ++-------- .../back/methods/worker/specs/new.spec.js | 15 ++--------- 12 files changed, 39 insertions(+), 145 deletions(-) diff --git a/back/methods/collection/spec/setSaleQuantity.spec.js b/back/methods/collection/spec/setSaleQuantity.spec.js index b563f5b19..7abcda36b 100644 --- a/back/methods/collection/spec/setSaleQuantity.spec.js +++ b/back/methods/collection/spec/setSaleQuantity.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('setSaleQuantity()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should change quantity sale', async() => { diff --git a/back/methods/starred-module/specs/getStarredModules.spec.js b/back/methods/starred-module/specs/getStarredModules.spec.js index bf9bd1d73..25b4989fa 100644 --- a/back/methods/starred-module/specs/getStarredModules.spec.js +++ b/back/methods/starred-module/specs/getStarredModules.spec.js @@ -1,22 +1,14 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +// const LoopBackContext = require('loopback-context'); describe('getStarredModules()', () => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = {req: activeCtx}; + const {ctx} = beforeAll; - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + // beforeEach(() => { + // spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + // active: ctx + // }); + // }); it(`should return the starred modules for a given user`, async() => { const newStarred = await models.StarredModule.create({workerFk: 9, moduleFk: 'customer', position: 1}); diff --git a/back/methods/starred-module/specs/setPosition.spec.js b/back/methods/starred-module/specs/setPosition.spec.js index a428fcf22..61b99440e 100644 --- a/back/methods/starred-module/specs/setPosition.spec.js +++ b/back/methods/starred-module/specs/setPosition.spec.js @@ -1,24 +1,14 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +// const LoopBackContext = require('loopback-context'); describe('setPosition()', () => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = { - req: activeCtx - }; + const {ctx} = beforeAll; - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + // beforeEach(() => { + // spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + // active: activeCtx + // }); + // }); it('should increase the orders module position by replacing it with clients and vice versa', async() => { const tx = await models.StarredModule.beginTransaction({}); diff --git a/back/methods/starred-module/specs/toggleStarredModule.spec.js b/back/methods/starred-module/specs/toggleStarredModule.spec.js index 848c1475a..10dd0492c 100644 --- a/back/methods/starred-module/specs/toggleStarredModule.spec.js +++ b/back/methods/starred-module/specs/toggleStarredModule.spec.js @@ -1,24 +1,14 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +// const LoopBackContext = require('loopback-context'); describe('toggleStarredModule()', () => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = { - req: activeCtx - }; + const {ctx} = beforeAll; - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + // beforeEach(() => { + // spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + // active: activeCtx + // }); + // }); it('should create a new starred module and then remove it by calling the method again with same args', async() => { const starredModule = await models.StarredModule.toggleStarredModule(ctx, 'order'); @@ -26,7 +16,7 @@ describe('toggleStarredModule()', () => { expect(starredModules.length).toEqual(1); expect(starredModule.moduleFk).toEqual('order'); - expect(starredModule.workerFk).toEqual(activeCtx.accessToken.userId); + expect(starredModule.workerFk).toEqual(ctx.req.accessToken.userId); expect(starredModule.position).toEqual(starredModules.length); await models.StarredModule.toggleStarredModule(ctx, 'order'); diff --git a/db/.pullinfo.json b/db/.pullinfo.json index f4afbc5fb..0defed845 100644 --- a/db/.pullinfo.json +++ b/db/.pullinfo.json @@ -9,7 +9,7 @@ }, "vn": { "view": { - "expeditionPallet_Print": "288cbd6e8289df083ed5eb1a2c808f7a82ba4c90c8ad9781104808a7a54471fb" + "expeditionPallet_Print": "06613719475fcdba8309607c38cc78efc2e348cca7bc96b48dc3ae3c12426f54" } } } diff --git a/loopback/common/methods/vn-model/specs/crud.spec.js b/loopback/common/methods/vn-model/specs/crud.spec.js index 56af72bd9..d120db92a 100644 --- a/loopback/common/methods/vn-model/specs/crud.spec.js +++ b/loopback/common/methods/vn-model/specs/crud.spec.js @@ -1,19 +1,9 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Model crud()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); let insertId; const barcodeModel = app.models.ItemBarcode; diff --git a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js index a3dba14d7..e3c24e74a 100644 --- a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js +++ b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Model rewriteDbError()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should extend rewriteDbError properties to any model passed', () => { diff --git a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js index 885171ed5..bff758eea 100644 --- a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js @@ -1,20 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Buy editLatestsBuys()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should change the value of a given column for the selected buys', async() => { diff --git a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js index f21dad9f2..02a43d4af 100644 --- a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js @@ -1,14 +1,9 @@ -const LoopBackContext = require('loopback-context'); const models = require('vn-loopback/server/server').models; +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('invoiceInDueDay new()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should correctly create a new due day', async() => { diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index 05d78240d..2c0d1910f 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('loopback model Supplier', () => { let supplierOne; @@ -8,18 +8,7 @@ describe('loopback model Supplier', () => { beforeAll(async() => { supplierOne = await models.Supplier.findById(1); supplierTwo = await models.Supplier.findById(442); - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); describe('payMethodFk', () => { diff --git a/modules/travel/back/methods/travel/specs/createThermograph.spec.js b/modules/travel/back/methods/travel/specs/createThermograph.spec.js index e812eae70..9c93d6d52 100644 --- a/modules/travel/back/methods/travel/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/travel/specs/createThermograph.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Travel createThermograph()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); const travelId = 3; const currentUserId = 1102; diff --git a/modules/worker/back/methods/worker/specs/new.spec.js b/modules/worker/back/methods/worker/specs/new.spec.js index 66959e0a7..186e003cf 100644 --- a/modules/worker/back/methods/worker/specs/new.spec.js +++ b/modules/worker/back/methods/worker/specs/new.spec.js @@ -1,20 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Worker new', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); const employeeId = 1; -- 2.40.1 From b3fa8697574edb4e18be1237ec79181808258bea Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 11 Jun 2024 10:00:30 +0200 Subject: [PATCH 167/413] refactor: refs #6436 second wave --- .../specs/getStarredModules.spec.js | 7 ------ .../starred-module/specs/setPosition.spec.js | 7 ------ .../specs/toggleStarredModule.spec.js | 7 ------ .../back/methods/claim/specs/filter.spec.js | 10 +------- .../claim/specs/regularizeClaim.spec.js | 14 ++--------- .../methods/claim/specs/updateClaim.spec.js | 15 ++---------- .../claim/specs/updateClaimAction.spec.js | 14 ++--------- .../agency-term/specs/createInvoiceIn.spec.js | 17 ++------------ .../back/methods/route/specs/clone.spec.js | 15 ++---------- .../methods/route/specs/guessPriority.spec.js | 23 ++++++++----------- .../route/specs/updateWorkCenter.spec.js | 14 ++--------- 11 files changed, 23 insertions(+), 120 deletions(-) diff --git a/back/methods/starred-module/specs/getStarredModules.spec.js b/back/methods/starred-module/specs/getStarredModules.spec.js index 25b4989fa..cce353f93 100644 --- a/back/methods/starred-module/specs/getStarredModules.spec.js +++ b/back/methods/starred-module/specs/getStarredModules.spec.js @@ -1,15 +1,8 @@ const {models} = require('vn-loopback/server/server'); -// const LoopBackContext = require('loopback-context'); describe('getStarredModules()', () => { const {ctx} = beforeAll; - // beforeEach(() => { - // spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - // active: ctx - // }); - // }); - it(`should return the starred modules for a given user`, async() => { const newStarred = await models.StarredModule.create({workerFk: 9, moduleFk: 'customer', position: 1}); const starredModules = await models.StarredModule.getStarredModules(ctx); diff --git a/back/methods/starred-module/specs/setPosition.spec.js b/back/methods/starred-module/specs/setPosition.spec.js index 61b99440e..495bc8384 100644 --- a/back/methods/starred-module/specs/setPosition.spec.js +++ b/back/methods/starred-module/specs/setPosition.spec.js @@ -1,15 +1,8 @@ const {models} = require('vn-loopback/server/server'); -// const LoopBackContext = require('loopback-context'); describe('setPosition()', () => { const {ctx} = beforeAll; - // beforeEach(() => { - // spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - // active: activeCtx - // }); - // }); - it('should increase the orders module position by replacing it with clients and vice versa', async() => { const tx = await models.StarredModule.beginTransaction({}); diff --git a/back/methods/starred-module/specs/toggleStarredModule.spec.js b/back/methods/starred-module/specs/toggleStarredModule.spec.js index 10dd0492c..d5a5c8ab3 100644 --- a/back/methods/starred-module/specs/toggleStarredModule.spec.js +++ b/back/methods/starred-module/specs/toggleStarredModule.spec.js @@ -1,15 +1,8 @@ const {models} = require('vn-loopback/server/server'); -// const LoopBackContext = require('loopback-context'); describe('toggleStarredModule()', () => { const {ctx} = beforeAll; - // beforeEach(() => { - // spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - // active: activeCtx - // }); - // }); - it('should create a new starred module and then remove it by calling the method again with same args', async() => { const starredModule = await models.StarredModule.toggleStarredModule(ctx, 'order'); let starredModules = await models.StarredModule.getStarredModules(ctx); diff --git a/modules/claim/back/methods/claim/specs/filter.spec.js b/modules/claim/back/methods/claim/specs/filter.spec.js index 872f49aa3..b55e554b9 100644 --- a/modules/claim/back/methods/claim/specs/filter.spec.js +++ b/modules/claim/back/methods/claim/specs/filter.spec.js @@ -2,15 +2,7 @@ const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models; describe('claim filter()', () => { - let ctx; - beforeEach(() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - } - }; - }); + const {ctx} = beforeAll; it('should return 1 result filtering by id', async() => { const tx = await app.models.Claim.beginTransaction({}); diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 95c356374..224adc997 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('claim regularizeClaim()', () => { const userId = 18; @@ -41,17 +41,7 @@ describe('claim regularizeClaim()', () => { } beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should send a chat message with value "Trash" and then change claim state to resolved', async() => { diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index b7725e7f8..5c8f08132 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -1,22 +1,11 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); const i18n = require('i18n'); describe('Update Claim', () => { let url; let claimStatesMap = {}; beforeAll(async() => { - url = await app.models.Url.getUrl(); - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); const claimStates = await app.models.ClaimState.find(); claimStatesMap = claimStates.reduce((acc, state) => ({...acc, [state.code]: state.id}), {}); }); diff --git a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js index 99436fed6..c939f59de 100644 --- a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js @@ -1,19 +1,9 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Update Claim', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); const newDate = Date.vnNew(); const original = { diff --git a/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js b/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js index d3a0755ef..a625605d2 100644 --- a/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js +++ b/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js @@ -1,21 +1,8 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +// const LoopBackContext = require('loopback-context'); describe('AgencyTerm createInvoiceIn()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const {ctx} = beforeAll; const rows = [ { routeFk: 2, diff --git a/modules/route/back/methods/route/specs/clone.spec.js b/modules/route/back/methods/route/specs/clone.spec.js index 496ae1c89..98240488c 100644 --- a/modules/route/back/methods/route/specs/clone.spec.js +++ b/modules/route/back/methods/route/specs/clone.spec.js @@ -1,20 +1,9 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('route clone()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); const createdDate = Date.vnNew(); diff --git a/modules/route/back/methods/route/specs/guessPriority.spec.js b/modules/route/back/methods/route/specs/guessPriority.spec.js index 902647ba1..d73db6379 100644 --- a/modules/route/back/methods/route/specs/guessPriority.spec.js +++ b/modules/route/back/methods/route/specs/guessPriority.spec.js @@ -1,20 +1,17 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +// const LoopBackContext = require('loopback-context'); describe('route guessPriority()', () => { const targetRouteId = 7; let routeTicketsToRestore; - const activeCtx = { - accessToken: {userId: 9}, - __: () => {} - }; + const {ctx} = beforeAll; - beforeAll(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + // beforeAll(() => { + // spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + // active: activeCtx + // }); + // }); afterAll(async() => { let restoreFixtures = []; @@ -25,9 +22,9 @@ describe('route guessPriority()', () => { }); it('should call guessPriority() then check all tickets in that route have their priorities defined', async() => { - const ctx = { - req: activeCtx - }; + // const ctx = { + // req: activeCtx + // }; routeTicketsToRestore = await app.models.Ticket.find({where: {routeFk: targetRouteId}}); await app.models.Route.guessPriority(ctx, targetRouteId); diff --git a/modules/route/back/methods/route/specs/updateWorkCenter.spec.js b/modules/route/back/methods/route/specs/updateWorkCenter.spec.js index a1c716299..315460d4a 100644 --- a/modules/route/back/methods/route/specs/updateWorkCenter.spec.js +++ b/modules/route/back/methods/route/specs/updateWorkCenter.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('route updateWorkCenter()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); const routeId = 1; -- 2.40.1 From 093eaeb4751a150f2414ced30c93c18bf02bae83 Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 11 Jun 2024 10:45:46 +0200 Subject: [PATCH 168/413] refactor: refs #6436 third wave --- .../client/specs/addressesPropagateRe.spec.js | 15 ++------------- .../methods/client/specs/createAddress.spec.js | 15 ++------------- .../methods/client/specs/updateAddress.spec.js | 15 ++------------- modules/client/back/models/specs/address.spec.js | 15 ++------------- .../fixed-price/specs/upsertFixedPrice.spec.js | 14 ++------------ .../item/back/methods/item/specs/clone.spec.js | 14 ++------------ .../back/methods/item/specs/getBalance.spec.js | 7 ++----- modules/item/back/methods/item/specs/new.spec.js | 15 ++------------- .../back/methods/item/specs/updateTaxes.spec.js | 14 ++------------ .../zone/back/methods/zone/specs/clone.spec.js | 14 ++------------ .../back/methods/zone/specs/exclusionGeo.spec.js | 14 ++------------ .../methods/zone/specs/toggleIsIncluded.spec.js | 15 +++------------ 12 files changed, 25 insertions(+), 142 deletions(-) diff --git a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js index 74d80b964..ec4ebe471 100644 --- a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js +++ b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js @@ -1,20 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Client addressesPropagateRe', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should propagate the isEqualizated on both addresses of Mr Wayne and set hasToInvoiceByAddress to false', async() => { diff --git a/modules/client/back/methods/client/specs/createAddress.spec.js b/modules/client/back/methods/client/specs/createAddress.spec.js index ae179cf6c..0556ce2cf 100644 --- a/modules/client/back/methods/client/specs/createAddress.spec.js +++ b/modules/client/back/methods/client/specs/createAddress.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Address createAddress', () => { const clientFk = 1101; @@ -8,18 +8,7 @@ describe('Address createAddress', () => { const customAgentOneId = 1; beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should throw a non uee member error if no incoterms is defined', async() => { diff --git a/modules/client/back/methods/client/specs/updateAddress.spec.js b/modules/client/back/methods/client/specs/updateAddress.spec.js index 6f02323c5..dd5142af0 100644 --- a/modules/client/back/methods/client/specs/updateAddress.spec.js +++ b/modules/client/back/methods/client/specs/updateAddress.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Address updateAddress', () => { const clientId = 1101; @@ -15,18 +15,7 @@ describe('Address updateAddress', () => { }; beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should throw the non uee member error if no incoterms is defined', async() => { diff --git a/modules/client/back/models/specs/address.spec.js b/modules/client/back/models/specs/address.spec.js index f0b421d35..4baa1bdca 100644 --- a/modules/client/back/models/specs/address.spec.js +++ b/modules/client/back/models/specs/address.spec.js @@ -1,23 +1,12 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('loopback model address', () => { let createdAddressId; const clientId = 1101; - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - beforeAll(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); afterAll(async() => { diff --git a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js index 823406500..36a15849c 100644 --- a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js +++ b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('upsertFixedPrice()', () => { const now = Date.vnNew(); @@ -8,17 +8,7 @@ describe('upsertFixedPrice()', () => { beforeAll(async() => { originalFixedPrice = await models.FixedPrice.findById(fixedPriceId); - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it(`should toggle the hasMinPrice boolean if there's a minPrice and update the rest of the data`, async() => { diff --git a/modules/item/back/methods/item/specs/clone.spec.js b/modules/item/back/methods/item/specs/clone.spec.js index 01210677e..1a479cd84 100644 --- a/modules/item/back/methods/item/specs/clone.spec.js +++ b/modules/item/back/methods/item/specs/clone.spec.js @@ -1,20 +1,10 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('item clone()', () => { let nextItemId; beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); beforeEach(async() => { diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js index 728b5f33e..d1bb65b75 100644 --- a/modules/item/back/methods/item/specs/getBalance.spec.js +++ b/modules/item/back/methods/item/specs/getBalance.spec.js @@ -2,17 +2,14 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('item getBalance()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it('should return the balance lines of a client type loses in which one has highlighted true', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const activeCtx = { - accessToken: {userId: 9}, - }; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx + active: ctx }); const losesClientId = 1111; const ticket = await models.Ticket.findById(7, null, options); diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js index 2ffaf87a5..7a3612ebc 100644 --- a/modules/item/back/methods/item/specs/new.spec.js +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -1,20 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('item new()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should create a new item, adding the name as a tag', async() => { diff --git a/modules/item/back/methods/item/specs/updateTaxes.spec.js b/modules/item/back/methods/item/specs/updateTaxes.spec.js index 793e43de8..49f95c1ed 100644 --- a/modules/item/back/methods/item/specs/updateTaxes.spec.js +++ b/modules/item/back/methods/item/specs/updateTaxes.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('item updateTaxes()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should throw an error if the taxClassFk is blank', async() => { diff --git a/modules/zone/back/methods/zone/specs/clone.spec.js b/modules/zone/back/methods/zone/specs/clone.spec.js index 1b7393912..465abdc9c 100644 --- a/modules/zone/back/methods/zone/specs/clone.spec.js +++ b/modules/zone/back/methods/zone/specs/clone.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('agency clone()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should clone a zone', async() => { diff --git a/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js b/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js index fbe96fc5f..746be502f 100644 --- a/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js +++ b/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('zone exclusionGeo()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); const zoneId = 1; const today = Date.vnNew(); diff --git a/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js b/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js index 2da176330..39986498e 100644 --- a/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js +++ b/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js @@ -1,18 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); + describe('zone toggleIsIncluded()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should return the created location with isIncluded true', async() => { -- 2.40.1 From 76f76b8304ccc75458216b7cceda417723024341 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 11 Jun 2024 10:48:24 +0200 Subject: [PATCH 169/413] feat: refs #7568 Added freelancer exception --- db/routines/vn/procedures/ticket_doCmr.sql | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/ticket_doCmr.sql b/db/routines/vn/procedures/ticket_doCmr.sql index 2da8464b4..e9cd1d659 100644 --- a/db/routines/vn/procedures/ticket_doCmr.sql +++ b/db/routines/vn/procedures/ticket_doCmr.sql @@ -18,7 +18,7 @@ BEGIN com.id companyFk, a.id addressFk, c2.defaultAddressFk, - su.id supplierFk, + IFNULL(sat.supplierFk, su.id) supplierFk, t.landed FROM ticket t JOIN ticketState ts ON ts.ticketFk = t.id @@ -28,15 +28,18 @@ BEGIN JOIN `address` a ON a.id = t.addressFk JOIN province p ON p.id = a.provinceFk JOIN country co ON co.id = p.countryFk - JOIN agencyMode am ON am.id = t.agencyModeFk JOIN warehouse w ON w.id = t.warehouseFk JOIN company com ON com.id = t.companyFk JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk JOIN supplier su ON su.id = sa.supplierFk LEFT JOIN route r ON r.id = t.routeFk LEFT JOIN worker wo ON wo.id = r.workerFk LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency ag ON ag.id = am.agencyFk + LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id + AND wo.isFreelance WHERE al.code IN ('PACKED', 'DELIVERED') AND co.code <> 'ES' AND am.name <> 'ABONO' -- 2.40.1 From 96366c475ad4b465108eca76401ac16e664ebf4c Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 11 Jun 2024 10:48:28 +0200 Subject: [PATCH 170/413] fix: refs 6449 update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fc8cfc13..68868d17a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ - feat: refs #7438 Added volume to item_valuateInventory by:guillermo - feat: refs #7438 Requested changes and little changes by:guillermo - refs #6281 feat:buyFk in itemShelving by:sergiodt +- feat: refs #6449 item ID is displayed in the sale line by:jorgep ### Changed 📦 @@ -90,7 +91,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - (Worker -> time-control) Corrección de errores - (InvoiceOut -> Crear factura) Cuando falla al crear una factura, se devuelve un error -- (Ticket -> Logs) Ahora se muestra el id del item de la línea de venta - (Worker -> Ver albarán) Ya no aparece la página en blanco ### Changed -- 2.40.1 From bd45352215ef383240669ccbfc4c16a6b5cf789b Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 11 Jun 2024 12:02:15 +0200 Subject: [PATCH 171/413] refactor: refs #6436 fourth wave --- .../item/back/methods/item/specs/new.spec.js | 5 +--- .../back/methods/tag/specs/onSubmit.spec.js | 14 ++--------- .../specs/deleteExpeditions.spec.js | 13 ++--------- .../expedition/specs/moveExpeditions.spec.js | 14 ++--------- .../back/methods/sale/specs/canEdit.spec.js | 14 ++--------- .../methods/sale/specs/deleteSales.spec.js | 14 ++--------- .../back/methods/sale/specs/reserve.spec.js | 14 ++--------- .../methods/sale/specs/updateConcept.spec.js | 14 ++--------- .../ticket-request/specs/confirm.spec.js | 23 ++----------------- .../ticket/specs/componentUpdate.spec.js | 14 ++--------- .../back/methods/ticket/specs/merge.spec.js | 14 ++--------- .../ticket/specs/updateDiscount.spec.js | 14 ++--------- .../models/specs/ticket-packaging.spec.js | 14 ++--------- 13 files changed, 25 insertions(+), 156 deletions(-) diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js index 7a3612ebc..5611b28ab 100644 --- a/modules/item/back/methods/item/specs/new.spec.js +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('item new()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + const {ctx} = beforeAll; it('should create a new item, adding the name as a tag', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/methods/tag/specs/onSubmit.spec.js b/modules/item/back/methods/tag/specs/onSubmit.spec.js index 1e96d9e81..1830aafcf 100644 --- a/modules/item/back/methods/tag/specs/onSubmit.spec.js +++ b/modules/item/back/methods/tag/specs/onSubmit.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('tag onSubmit()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should delete a tag', async() => { diff --git a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js index bf8bafe34..2c34c994b 100644 --- a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js +++ b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js @@ -1,18 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket deleteExpeditions()', () => { - let ctx; beforeAll(async() => { - ctx = { - accessToken: {userId: 9}, - req: { - headers: {origin: 'http://localhost'} - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx - }); + mockLoopBackContext(); }); it('should delete the selected expeditions', async() => { diff --git a/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js index 5f211543e..27b20bcd2 100644 --- a/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js +++ b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket moveExpeditions()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should move the selected expeditions to new ticket', async() => { diff --git a/modules/ticket/back/methods/sale/specs/canEdit.spec.js b/modules/ticket/back/methods/sale/specs/canEdit.spec.js index 200ea24cc..3185b01e7 100644 --- a/modules/ticket/back/methods/sale/specs/canEdit.spec.js +++ b/modules/ticket/back/methods/sale/specs/canEdit.spec.js @@ -1,20 +1,10 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale canEdit()', () => { const employeeId = 1; beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); describe('sale not exists', () => { diff --git a/modules/ticket/back/methods/sale/specs/deleteSales.spec.js b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js index 3d3e06e22..8d0e4bd4e 100644 --- a/modules/ticket/back/methods/sale/specs/deleteSales.spec.js +++ b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale deleteSales()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should throw an error if the ticket of the given sales is not editable', async() => { diff --git a/modules/ticket/back/methods/sale/specs/reserve.spec.js b/modules/ticket/back/methods/sale/specs/reserve.spec.js index 7ba5999b3..37ebf10ab 100644 --- a/modules/ticket/back/methods/sale/specs/reserve.spec.js +++ b/modules/ticket/back/methods/sale/specs/reserve.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale reserve()', () => { const ctx = { @@ -11,17 +11,7 @@ describe('sale reserve()', () => { }; beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should throw an error if the ticket can not be modified', async() => { diff --git a/modules/ticket/back/methods/sale/specs/updateConcept.spec.js b/modules/ticket/back/methods/sale/specs/updateConcept.spec.js index 1b42e7140..0610e9eab 100644 --- a/modules/ticket/back/methods/sale/specs/updateConcept.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateConcept.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale updateConcept()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); const ctx = {req: {accessToken: {userId: 9}}}; diff --git a/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js index 668a991f4..8a1130e7d 100644 --- a/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js @@ -1,29 +1,10 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket-request confirm()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); - let ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - } - }; - ctx.req.__ = value => { - return value; - }; it(`should throw an error if the item doesn't exist`, async() => { const tx = await models.TicketRequest.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index 8abb1a4a1..b138b88ea 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket componentUpdate()', () => { const userID = 1101; @@ -17,17 +17,7 @@ describe('ticket componentUpdate()', () => { let componentValue; beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); const deliveryComponenet = await models.Component.findOne({where: {code: 'delivery'}}); deliveryComponentId = deliveryComponenet.id; componentOfSaleSeven = `SELECT value diff --git a/modules/ticket/back/methods/ticket/specs/merge.spec.js b/modules/ticket/back/methods/ticket/specs/merge.spec.js index 646b9739f..702b496af 100644 --- a/modules/ticket/back/methods/ticket/specs/merge.spec.js +++ b/modules/ticket/back/methods/ticket/specs/merge.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket merge()', () => { const tickets = { @@ -11,17 +11,7 @@ describe('ticket merge()', () => { }; beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); const ctx = { diff --git a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js index 41de1fd6e..c0c5333ba 100644 --- a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js +++ b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale updateDiscount()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); const originalSaleId = 8; diff --git a/modules/ticket/back/models/specs/ticket-packaging.spec.js b/modules/ticket/back/models/specs/ticket-packaging.spec.js index 6d59456a3..97a936018 100644 --- a/modules/ticket/back/models/specs/ticket-packaging.spec.js +++ b/modules/ticket/back/models/specs/ticket-packaging.spec.js @@ -1,19 +1,9 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket model TicketTracking', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); let ticketTrackingId; -- 2.40.1 From 1cefe817f55096390ce68b63f377a80c494764c6 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 11 Jun 2024 12:06:44 +0200 Subject: [PATCH 172/413] feat: add editZone ACL for buyer --- db/versions/11096-blackChico/00-addBuyerAcl.sql | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 db/versions/11096-blackChico/00-addBuyerAcl.sql diff --git a/db/versions/11096-blackChico/00-addBuyerAcl.sql b/db/versions/11096-blackChico/00-addBuyerAcl.sql new file mode 100644 index 000000000..1b4adee5c --- /dev/null +++ b/db/versions/11096-blackChico/00-addBuyerAcl.sql @@ -0,0 +1,8 @@ +INSERT INTO salix.ACL + SET + model = 'Ticket', + property = 'editZone', + accessType = 'WRITE', + permission = 'ALLOW', + principalType = 'ROLE', + principalId = 'buyer'; \ No newline at end of file -- 2.40.1 From 5d7a570c3fb917590e4947738765eebf2f72ecec Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 11 Jun 2024 12:28:49 +0200 Subject: [PATCH 173/413] refs #6897 fix redirection --- back/nodemonConfig.json | 1 + front/module-import.js | 1 + modules/entry/front/index.js | 3 +- modules/entry/front/index/index.html | 85 ---------------------------- modules/entry/front/index/index.js | 14 ----- modules/entry/front/main/index.html | 0 modules/entry/front/main/index.js | 17 ++++++ 7 files changed, 20 insertions(+), 101 deletions(-) delete mode 100644 modules/entry/front/index/index.html delete mode 100644 modules/entry/front/index/index.js create mode 100644 modules/entry/front/main/index.html create mode 100644 modules/entry/front/main/index.js diff --git a/back/nodemonConfig.json b/back/nodemonConfig.json index c468a2f73..9552460bd 100644 --- a/back/nodemonConfig.json +++ b/back/nodemonConfig.json @@ -8,6 +8,7 @@ "modules/account/front/**/*", "modules/claim/front/**/*", "modules/client/front/**/*", + "modules/entry/front/**/*", "modules/invoiceIn/front/**/*", "modules/invoiceOut/front/**/*", "modules/item/front/**/*", diff --git a/front/module-import.js b/front/module-import.js index 85731c72c..22a2747d2 100755 --- a/front/module-import.js +++ b/front/module-import.js @@ -22,5 +22,6 @@ export default function moduleImport(moduleName) { case 'supplier': return import('supplier/front'); case 'shelving': return import('shelving/front'); case 'monitor': return import('monitor/front'); + case 'entry': return import('entry/front'); } } diff --git a/modules/entry/front/index.js b/modules/entry/front/index.js index f4cae889c..a7209a0bd 100644 --- a/modules/entry/front/index.js +++ b/modules/entry/front/index.js @@ -1,4 +1,3 @@ export * from './module'; -import './index/'; - +import './main'; diff --git a/modules/entry/front/index/index.html b/modules/entry/front/index/index.html deleted file mode 100644 index 42177be21..000000000 --- a/modules/entry/front/index/index.html +++ /dev/null @@ -1,85 +0,0 @@ - - - - - - - - - Id - Landed - Reference - Invoice number - Supplier - Booked - Confirmed - Ordered - - - - - - - - - - - - {{::entry.id}} - - - {{::entry.landed | date:'dd/MM/yyyy'}} - - - {{::entry.reference}} - {{::entry.invoiceNumber}} - {{::entry.supplierName}} - - - - - - - - - - - - - - - - - - -
- - - - - - -
\ No newline at end of file diff --git a/modules/entry/front/index/index.js b/modules/entry/front/index/index.js deleted file mode 100644 index 8635d3fb4..000000000 --- a/modules/entry/front/index/index.js +++ /dev/null @@ -1,14 +0,0 @@ -import ngModule from '../module'; -import Section from 'salix/components/section'; - -export default class Controller extends Section { - preview(entry) { - this.entrySelected = entry; - this.$.summary.show(); - } -} - -ngModule.vnComponent('vnEntryIndex', { - template: require('./index.html'), - controller: Controller -}); diff --git a/modules/entry/front/main/index.html b/modules/entry/front/main/index.html new file mode 100644 index 000000000..e69de29bb diff --git a/modules/entry/front/main/index.js b/modules/entry/front/main/index.js new file mode 100644 index 000000000..de0beced4 --- /dev/null +++ b/modules/entry/front/main/index.js @@ -0,0 +1,17 @@ +import ngModule from '../module'; +import ModuleMain from 'salix/components/module-main'; + +export default class Entry extends ModuleMain { + constructor($element, $) { + super($element, $); + } + async $onInit() { + this.$state.go('home'); + window.location.href = await this.vnApp.getUrl(`entry/`); + } +} + +ngModule.vnComponent('vnEntry', { + controller: Entry, + template: require('./index.html') +}); -- 2.40.1 From 665d03f0480601e3aa97d9f915b5cb66d902f015 Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 11 Jun 2024 12:35:44 +0200 Subject: [PATCH 174/413] refactor: refs #6436 user-config and some sections tests --- .../user-config/specs/getUserConfig.spec.js | 2 +- .../back/methods/client/specs/getCard.spec.js | 2 +- .../back/methods/client/specs/getDebt.spec.js | 2 +- .../back/methods/client/specs/sendSms.spec.js | 2 +- .../back/methods/client/specs/summary.spec.js | 2 +- .../methods/entry/specs/importBuysPreview.spec.js | 7 ++----- .../back/methods/invoiceOut/specs/book.spec.js | 2 +- .../methods/order-row/specs/addToOrder.spec.js | 2 +- .../order/back/methods/order/specs/filter.spec.js | 6 +----- modules/order/back/methods/order/specs/new.spec.js | 2 +- .../back/methods/order/specs/newFromTicket.spec.js | 2 +- .../specs/addExpeditionState.spec.js | 2 +- .../methods/sale/specs/recalculatePrice.spec.js | 3 +-- .../back/methods/sale/specs/updateConcept.spec.js | 7 +------ .../back/methods/ticket-request/specs/deny.spec.js | 14 ++------------ .../thermograph/specs/createThermograph.spec.js | 2 +- 16 files changed, 18 insertions(+), 41 deletions(-) diff --git a/back/methods/user-config/specs/getUserConfig.spec.js b/back/methods/user-config/specs/getUserConfig.spec.js index 8b510a706..c27018b07 100644 --- a/back/methods/user-config/specs/getUserConfig.spec.js +++ b/back/methods/user-config/specs/getUserConfig.spec.js @@ -1,12 +1,12 @@ const models = require('vn-loopback/server/server').models; describe('userConfig getUserConfig()', () => { + const {ctx} = beforeAll; it(`should return the configuration data of a given user`, async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const ctx = {req: {accessToken: {userId: 9}}}; const result = await models.UserConfig.getUserConfig(ctx, options); expect(result.warehouseFk).toEqual(1); diff --git a/modules/client/back/methods/client/specs/getCard.spec.js b/modules/client/back/methods/client/specs/getCard.spec.js index 962e0a2d4..1082b4009 100644 --- a/modules/client/back/methods/client/specs/getCard.spec.js +++ b/modules/client/back/methods/client/specs/getCard.spec.js @@ -1,11 +1,11 @@ const models = require('vn-loopback/server/server').models; describe('Client getCard()', () => { + const {ctx} = beforeAll; it('should receive a formated card of Bruce Wayne', async() => { const tx = await models.Client.beginTransaction({}); try { - const ctx = {req: {accessToken: {userId: 9}}}; const options = {transaction: tx}; const id = 1101; diff --git a/modules/client/back/methods/client/specs/getDebt.spec.js b/modules/client/back/methods/client/specs/getDebt.spec.js index b3b5286c0..7fc76ee94 100644 --- a/modules/client/back/methods/client/specs/getDebt.spec.js +++ b/modules/client/back/methods/client/specs/getDebt.spec.js @@ -1,9 +1,9 @@ const models = require('vn-loopback/server/server').models; describe('client getDebt()', () => { + const {ctx} = beforeAll; it('should return the client debt', async() => { const tx = await models.Client.beginTransaction({}); - const ctx = {req: {accessToken: {userId: 9}}}; try { const options = {transaction: tx}; diff --git a/modules/client/back/methods/client/specs/sendSms.spec.js b/modules/client/back/methods/client/specs/sendSms.spec.js index df680c55f..b6cb55062 100644 --- a/modules/client/back/methods/client/specs/sendSms.spec.js +++ b/modules/client/back/methods/client/specs/sendSms.spec.js @@ -1,12 +1,12 @@ const models = require('vn-loopback/server/server').models; describe('client sendSms()', () => { + const {ctx} = beforeAll; it('should now send a message and log it', async() => { const tx = await models.Client.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}}; const id = 1101; const destination = 222222222; const message = 'this is the message created in a test'; diff --git a/modules/client/back/methods/client/specs/summary.spec.js b/modules/client/back/methods/client/specs/summary.spec.js index 227f4c398..d15d183c6 100644 --- a/modules/client/back/methods/client/specs/summary.spec.js +++ b/modules/client/back/methods/client/specs/summary.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('client summary()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it('should return a summary object containing data', async() => { const clientId = 1101; const tx = await models.Client.beginTransaction({}); diff --git a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js index c860e228e..bab46ad59 100644 --- a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js +++ b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js @@ -1,13 +1,10 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); -const activeCtx = {accessToken: {userId: 9}}; +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('entry importBuysPreview()', () => { const entryId = 1; beforeAll(async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should return the buys with the calculated packagingFk', async() => { diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index 3af7542ca..29e21a27c 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('invoiceOut book()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; const invoiceOutId = 5; it('should update the booked property', async() => { diff --git a/modules/order/back/methods/order-row/specs/addToOrder.spec.js b/modules/order/back/methods/order-row/specs/addToOrder.spec.js index 96544a1a9..327c86db0 100644 --- a/modules/order/back/methods/order-row/specs/addToOrder.spec.js +++ b/modules/order/back/methods/order-row/specs/addToOrder.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order addToOrder()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; const orderId = 8; it('should add a row to a given order', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/back/methods/order/specs/filter.spec.js b/modules/order/back/methods/order/specs/filter.spec.js index 68de7fe04..95cb488c8 100644 --- a/modules/order/back/methods/order/specs/filter.spec.js +++ b/modules/order/back/methods/order/specs/filter.spec.js @@ -1,11 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order filter()', () => { - const ctx = { - req: {accessToken: {userId: 9}}, - args: {}, - params: {} - }; + const {ctx} = beforeAll; it('should call the filter method with a basic search', async() => { const myCtx = Object.assign({}, ctx); diff --git a/modules/order/back/methods/order/specs/new.spec.js b/modules/order/back/methods/order/specs/new.spec.js index c43527f66..6ed1fa4ae 100644 --- a/modules/order/back/methods/order/specs/new.spec.js +++ b/modules/order/back/methods/order/specs/new.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; const UserError = require('vn-loopback/util/user-error'); describe('order new()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it('should throw an error if the client isnt active', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/back/methods/order/specs/newFromTicket.spec.js b/modules/order/back/methods/order/specs/newFromTicket.spec.js index c509552fe..a592877cf 100644 --- a/modules/order/back/methods/order/specs/newFromTicket.spec.js +++ b/modules/order/back/methods/order/specs/newFromTicket.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order newFromTicket()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it('should create a new order from an existing ticket', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js index 6c7739006..ce9049a95 100644 --- a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js +++ b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('expeditionState addExpeditionState()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it('should update the expedition states', async() => { const tx = await models.ExpeditionState.beginTransaction({}); try { diff --git a/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js b/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js index 0fc68dee7..3c871dd6c 100644 --- a/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js @@ -1,6 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('sale recalculatePrice()', () => { + const {ctx} = beforeAll; it('should update the sale price', async() => { const tx = await models.Sale.beginTransaction({}); const sales = [ @@ -10,7 +11,6 @@ describe('sale recalculatePrice()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}}; const response = await models.Sale.recalculatePrice(ctx, sales, options); expect(response[0].affectedRows).toBeDefined(); @@ -30,7 +30,6 @@ describe('sale recalculatePrice()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}}; const immutableSale = [{id: 1, ticketFk: 1}]; await models.Sale.recalculatePrice(ctx, immutableSale, options); diff --git a/modules/ticket/back/methods/sale/specs/updateConcept.spec.js b/modules/ticket/back/methods/sale/specs/updateConcept.spec.js index 0610e9eab..be6ad77a3 100644 --- a/modules/ticket/back/methods/sale/specs/updateConcept.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateConcept.spec.js @@ -1,12 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale updateConcept()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); - - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; const saleId = 25; it('should throw if ID was undefined', async() => { diff --git a/modules/ticket/back/methods/ticket-request/specs/deny.spec.js b/modules/ticket/back/methods/ticket-request/specs/deny.spec.js index 875a75921..1259f1284 100644 --- a/modules/ticket/back/methods/ticket-request/specs/deny.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/deny.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket-request deny()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should return the denied ticket request', async() => { diff --git a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js index 90855bf81..49eeb86c2 100644 --- a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js @@ -5,7 +5,7 @@ describe('Termograph createThermograph()', () => { const model = 'DISPOSABLE'; const temperatureFk = 'COOL'; const warehouseId = 1; - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it(`should create a thermograph which is saved in both thermograph and travelThermograph`, async() => { const tx = await models.Thermograph.beginTransaction({}); -- 2.40.1 From ed7218c1332d4d8c752e6816e07b111ec0100127 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 11 Jun 2024 12:44:25 +0200 Subject: [PATCH 175/413] feat: previas con sitema de reservas refs #6861 --- .../collection_addWithReservation.sql | 24 ++++----- .../vn/procedures/collection_getAssigned.sql | 16 +++--- .../itemShelvingSale_addByCollection.sql | 2 +- .../itemShelvingSale_moveReserv.sql | 50 +++++++++++++++++++ ...oup.sql => itemShelvingSale_setPicked.sql} | 2 +- .../itemShelvingSale_setQuantity.sql | 45 +++-------------- ...Transfer.sql => itemShelving_transfer.sql} | 5 +- ....sql => sectorCollection_getMyPartial.sql} | 2 +- .../sectorCollection_hasSalesReserved.sql | 30 +++++------ .../vn/triggers/itemShelving_afterInsert.sql | 29 ----------- 10 files changed, 94 insertions(+), 111 deletions(-) create mode 100644 db/routines/vn/procedures/itemShelvingSale_moveReserv.sql rename db/routines/vn/procedures/{itemShelvingSale_setSaleGroup.sql => itemShelvingSale_setPicked.sql} (91%) rename db/routines/vn/procedures/{itemShelvingTransfer.sql => itemShelving_transfer.sql} (95%) rename db/routines/vn/procedures/{sectorCollection_getPartial.sql => sectorCollection_getMyPartial.sql} (95%) delete mode 100644 db/routines/vn/triggers/itemShelving_afterInsert.sql diff --git a/db/routines/vn/procedures/collection_addWithReservation.sql b/db/routines/vn/procedures/collection_addWithReservation.sql index cc207b572..faa00477e 100644 --- a/db/routines/vn/procedures/collection_addWithReservation.sql +++ b/db/routines/vn/procedures/collection_addWithReservation.sql @@ -23,7 +23,7 @@ BEGIN DECLARE vConcept VARCHAR(50); DECLARE vItemName VARCHAR(50); DECLARE vHasThrow BOOLEAN DEFAULT FALSE; - + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; @@ -48,21 +48,14 @@ BEGIN IF vAvailable < vQuantity THEN SET vHasThrow = TRUE; - SELECT vAvailable, vQuantity; ELSE - START TRANSACTION; - SELECT `name`, CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) INTO vItemName, vConcept FROM item WHERE id = vItemFk; - INSERT INTO ticketLog - SET originFk = vTicketFk, - userFk = getUser(), - `action` = 'update', - `description` = CONCAT('Añadido articulo ', vItemName, ' cantidad:', vQuantity); + START TRANSACTION; INSERT INTO sale SET itemFk = vItemFk, @@ -84,12 +77,13 @@ BEGIN IF vHasThrow THEN CALL util.throw("No hay disponibilidad para el artículo seleccionado"); ELSE - IF vSaleGroupFk THEN - INSERT INTO saleGroupDetail - SET saleFk = vSaleFk, - saleGroupFk = vSaleGroupFk; - COMMIT; + IF vSaleGroupFk THEN + INSERT INTO saleGroupDetail + SET saleFk = vSaleFk, + saleGroupFk = vSaleGroupFk; END IF; - END IF ; + COMMIT; + END IF; + END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/collection_getAssigned.sql b/db/routines/vn/procedures/collection_getAssigned.sql index 63805e701..575032e2e 100644 --- a/db/routines/vn/procedures/collection_getAssigned.sql +++ b/db/routines/vn/procedures/collection_getAssigned.sql @@ -1,11 +1,14 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_getAssigned`( vUserFk INT, - OUT vCollectionFk INT) -proc:BEGIN -/* Comprueba si existen colecciones libres que se ajustan al perfil del usuario + OUT vCollectionFk INT +) +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan al perfil del usuario * y le asigna la más antigua. * Añade un registro al semillero de colecciones y hace la reserva para la colección + * * @param vUserFk Id de usuario * @param vCollectionFk Id de colección */ @@ -28,17 +31,16 @@ proc:BEGIN CALL collection_get(vUserFk); SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, - collection_assign_lockname + pc.collection_assign_lockname INTO vHasTooMuchCollections, vLockName - FROM tCollection - JOIN productionConfig pc ; + FROM tCollection tc + JOIN productionConfig pc; DROP TEMPORARY TABLE tCollection; IF vHasTooMuchCollections THEN CALL util.throw('Hay colecciones pendientes'); - LEAVE proc; END IF; SELECT warehouseFk, itemPackingTypeFk diff --git a/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql b/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql index 9bc549235..7f9cc6616 100644 --- a/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql +++ b/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql @@ -26,7 +26,7 @@ BEGIN JOIN vn.saleTracking st ON st.saleFk = sa.saleFk JOIN vn.`state` s ON s.id = st.stateFk WHERE st.isChecked - AND s.semaphore = 1 + AND s.`code` IN ('PREVIOUS_PREPARATION', 'OK PREVIOUS', 'OK STOWAWAY') GROUP BY sa.saleFk ) SELECT s.saleFk FROM sales s diff --git a/db/routines/vn/procedures/itemShelvingSale_moveReserv.sql b/db/routines/vn/procedures/itemShelvingSale_moveReserv.sql new file mode 100644 index 000000000..7001ee4b8 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_moveReserv.sql @@ -0,0 +1,50 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_moveReserv`( + vItemShelvingFk INT(10), + vItemFk INT(10) +) +BEGIN +/** + * Elimina reservas de un itemShelvingSale e intenta reservar en otra ubicación + * + * @param vItemShelvingFk Id itemShelving + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + AND FALSE + FOR UPDATE; + + UPDATE itemShelving + SET visible = 0, + available = 0 + WHERE id = vItemShelvingFk + AND itemFk = vItemFk; + + INSERT INTO itemShelvingSaleReserv (saleFk) + SELECT DISTINCT iss.saleFk + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + + DELETE iss + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + COMMIT; + + CALL itemShelvingSale_doReserve(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_setSaleGroup.sql b/db/routines/vn/procedures/itemShelvingSale_setPicked.sql similarity index 91% rename from db/routines/vn/procedures/itemShelvingSale_setSaleGroup.sql rename to db/routines/vn/procedures/itemShelvingSale_setPicked.sql index 911034ed1..c1e58a9d1 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setSaleGroup.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setPicked.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setSaleGroup`( +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setPicked`( vSaleGroupFk INT(10) ) BEGIN diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index 13b8a16ad..6f008ab33 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -46,10 +46,8 @@ BEGIN CALL util.throw('La cantidad no puede distinta a la reserva'); END IF; - START TRANSACTION; - UPDATE itemShelvingSale SET isPicked = TRUE, quantity = vQuantity @@ -62,41 +60,10 @@ BEGIN FOR UPDATE; UPDATE itemShelving - SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0, visible - vQuantity)) + SET visible = GREATEST(0, visible - vQuantity) WHERE id = vItemShelvingFk; - COMMIT; - IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN - - UPDATE itemShelving - SET visible = 0, - available = 0 - WHERE id = vItemShelvingFk - AND itemFk = vItemFk; - - CALL itemShelvingSale_addBySale(vSaleFk); - - START TRANSACTION; - - INSERT INTO itemShelvingSaleReserv (saleFk) - SELECT DISTINCT iss.saleFk - FROM itemShelvingSale iss - JOIN itemShelving ish ON ish.id = iss.itemShelvingFk - WHERE iss.itemShelvingFk = vItemShelvingFk - AND ish.itemFk = vItemFk - AND NOT iss.isPicked; - - DELETE iss - FROM itemShelvingSale iss - JOIN itemShelving ish ON ish.id = iss.itemShelvingFk - WHERE iss.itemShelvingFk = vItemShelvingFk - AND ish.itemFk = vItemFk - AND NOT iss.isPicked; - COMMIT; - - CALL itemShelvingSale_doReserve(); - END IF; SELECT SUM(IF(isPicked, 0, quantity)), SUM(quantity) INTO vRemainingQuantity, vTotalQuantity @@ -104,8 +71,6 @@ BEGIN WHERE saleFk = vSaleFk; IF vRemainingQuantity = 0 THEN - START TRANSACTION; - CALL saleTracking_new( vSaleFk, TRUE, @@ -119,8 +84,12 @@ BEGIN SET s.quantity = vTotalQuantity, isPicked = TRUE WHERE s.id = vSaleFk; - - COMMIT; + END IF; + + COMMIT; + + IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN + CALL itemShelvingSale_moveReserv(vItemShelvingFk, vQuantity); END IF; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingTransfer.sql b/db/routines/vn/procedures/itemShelving_transfer.sql similarity index 95% rename from db/routines/vn/procedures/itemShelvingTransfer.sql rename to db/routines/vn/procedures/itemShelving_transfer.sql index 07012a654..47a9a7cf0 100644 --- a/db/routines/vn/procedures/itemShelvingTransfer.sql +++ b/db/routines/vn/procedures/itemShelving_transfer.sql @@ -1,7 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingTransfer`( +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_transfer`( vItemShelvingFk INT, - vShelvingFk VARCHAR(3)) + vShelvingFk VARCHAR(10) +) BEGIN /** * Transfiere producto de una ubicación a otra, fusionando si coincide el diff --git a/db/routines/vn/procedures/sectorCollection_getPartial.sql b/db/routines/vn/procedures/sectorCollection_getMyPartial.sql similarity index 95% rename from db/routines/vn/procedures/sectorCollection_getPartial.sql rename to db/routines/vn/procedures/sectorCollection_getMyPartial.sql index 2f59f591a..23e21d2f3 100644 --- a/db/routines/vn/procedures/sectorCollection_getPartial.sql +++ b/db/routines/vn/procedures/sectorCollection_getMyPartial.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorCollection_getPartial`() +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorCollection_getMyPartial`() BEGIN /** * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas diff --git a/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql b/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql index 0de49e90c..acb460190 100644 --- a/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql +++ b/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql @@ -2,28 +2,24 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION vn.sectorCollection_hasSalesReserved(vSelf INT) RETURNS tinyint(1) DETERMINISTIC BEGIN - /** -* Devuelve si sectorCollection tiene reservas -* @param vSelf Id de sectorCollection -* -* returns BOOLEAN -*/ - + * Devuelve si sectorCollection tiene reservas + * @param vSelf Id de sectorCollection + * + * returns BOOLEAN + */ DECLARE vHasSalesReserved BOOLEAN; - - SELECT DISTINCT COUNT(*)>0 INTO vHasSalesReserved - FROM vn.sectorCollection sc - JOIN vn.sectorCollectionSaleGroup scsg ON sc.id = scsg.sectorCollectionFk - JOIN vn.saleGroup sg ON sg.id = scsg.saleGroupFk - JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = sg.id - JOIN vn.sale s ON s.id = sgd.saleFk - JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id - JOIN vn.saleTracking st ON st.saleFk = s.id + SELECT DISTINCT COUNT(*) INTO vHasSalesReserved + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup scsg ON sc.id = scsg.sectorCollectionFk + JOIN saleGroup sg ON sg.id = scsg.saleGroupFk + JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id + JOIN sale s ON s.id = sgd.saleFk + JOIN itemShelvingSale iss ON iss.saleFk = s.id + JOIN saleTracking st ON st.saleFk = s.id WHERE sc.id = vSelf; RETURN vHasSalesReserved; - END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelving_afterInsert.sql b/db/routines/vn/triggers/itemShelving_afterInsert.sql deleted file mode 100644 index 819e3e790..000000000 --- a/db/routines/vn/triggers/itemShelving_afterInsert.sql +++ /dev/null @@ -1,29 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterInsert` - AFTER INSERT ON `itemShelving` - FOR EACH ROW -BEGIN - INSERT INTO vn.itemShelvingLog( - itemShelvingFk, - workerFk, - accion, - itemFk, - shelvingFk, - visible, - `grouping`, - packing, - available - ) - VALUES ( - NEW.id, - NEW.userFk, - 'CREA REGISTRO', - NEW.itemFk, - NEW.shelvingFk, - NEW.visible, - NEW.`grouping`, - NEW.packing, - NEW.available - ); -END$$ -DELIMITER ; \ No newline at end of file -- 2.40.1 From d75e008a23d14675cec169e478cc03d8ad44732a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 11 Jun 2024 12:49:33 +0200 Subject: [PATCH 176/413] feat: previas con sitema de reservas refs #6861 --- .../procedures/collection_addWithReservation.sql | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/db/routines/vn/procedures/collection_addWithReservation.sql b/db/routines/vn/procedures/collection_addWithReservation.sql index faa00477e..b483eff39 100644 --- a/db/routines/vn/procedures/collection_addWithReservation.sql +++ b/db/routines/vn/procedures/collection_addWithReservation.sql @@ -76,14 +76,14 @@ BEGIN IF vHasThrow THEN CALL util.throw("No hay disponibilidad para el artículo seleccionado"); - ELSE - IF vSaleGroupFk THEN - INSERT INTO saleGroupDetail - SET saleFk = vSaleFk, - saleGroupFk = vSaleGroupFk; - END IF; - COMMIT; END IF; - + + IF vSaleGroupFk THEN + INSERT INTO saleGroupDetail + SET saleFk = vSaleFk, + saleGroupFk = vSaleGroupFk; + END IF; + + COMMIT; END$$ DELIMITER ; -- 2.40.1 From 944355d54f619ee0c14115e606d0bf443784b420 Mon Sep 17 00:00:00 2001 From: Jon Date: Tue, 11 Jun 2024 13:17:19 +0200 Subject: [PATCH 177/413] refactor: refs #6436 end first wave of changes in modules --- .../expedition/specs/moveExpeditions.spec.js | 14 +++----------- .../methods/ticket/specs/isEditableOrThrow.spec.js | 4 +--- .../ticket/back/methods/ticket/specs/merge.spec.js | 12 +----------- .../ticket/specs/recalculateComponents.spec.js | 3 +-- .../back/methods/ticket/specs/sendSms.spec.js | 2 +- .../back/methods/calendar/specs/absences.spec.js | 2 +- .../methods/department/specs/getLeaves.spec.js | 2 +- .../methods/worker/specs/mySubordinates.spec.js | 2 +- .../agency/specs/getAgenciesWithWarehouse.spec.js | 2 +- .../back/methods/agency/specs/landsThatDay.spec.js | 2 +- .../zone/back/methods/zone/specs/getEvents.spec.js | 2 +- .../zone/back/methods/zone/specs/getLeaves.spec.js | 2 +- .../zone/specs/getUpcomingDeliveries.spec.js | 2 +- 13 files changed, 15 insertions(+), 36 deletions(-) diff --git a/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js index 27b20bcd2..621992c5d 100644 --- a/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js +++ b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js @@ -1,19 +1,11 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket moveExpeditions()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + const {ctx} = beforeAll; it('should move the selected expeditions to new ticket', async() => { const tx = await models.Expedition.beginTransaction({}); - const ctx = { - req: {accessToken: {userId: 9}}, - args: {}, - params: {} - }; - const myCtx = Object.assign({}, ctx); + const myCtx = ctx; try { const options = {transaction: tx}; @@ -28,7 +20,7 @@ describe('ticket moveExpeditions()', () => { }; - const ticket = await models.Expedition.moveExpeditions(myCtx, options); + const ticket = await models.Expedition.moveExpeditions(ctx, options); const newestTicketIdInFixtures = 27; diff --git a/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js b/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js index bdf547325..e78812bfe 100644 --- a/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js +++ b/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js @@ -1,14 +1,12 @@ const models = require('vn-loopback/server/server').models; describe('ticket isEditableOrThrow()', () => { + const {ctx} = beforeAll; it('should throw an error as the ticket does not exist', async() => { const tx = await models.Ticket.beginTransaction({}); let error; try { const options = {transaction: tx}; - const ctx = { - req: {accessToken: {userId: 9}} - }; await models.Ticket.isEditableOrThrow(ctx, 9999, options); await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/specs/merge.spec.js b/modules/ticket/back/methods/ticket/specs/merge.spec.js index 702b496af..21d4e5c75 100644 --- a/modules/ticket/back/methods/ticket/specs/merge.spec.js +++ b/modules/ticket/back/methods/ticket/specs/merge.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket merge()', () => { + const {ctx} = beforeAll; const tickets = { originId: 13, destinationId: 12, @@ -10,16 +10,6 @@ describe('ticket merge()', () => { workerFk: 1 }; - beforeAll(async() => { - mockLoopBackContext(); - }); - - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost:5000'}, - } - }; ctx.req.__ = value => { return value; }; diff --git a/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js b/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js index d358a79f5..5c3811583 100644 --- a/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js +++ b/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js @@ -3,6 +3,7 @@ const ForbiddenError = require('vn-loopback/util/forbiddenError'); describe('ticket recalculateComponents()', () => { const ticketId = 11; + const {ctx} = beforeAll; it('should update the ticket components', async() => { const tx = await models.Ticket.beginTransaction({}); @@ -10,7 +11,6 @@ describe('ticket recalculateComponents()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}}; const response = await models.Ticket.recalculateComponents(ctx, ticketId, options); expect(response.affectedRows).toBeDefined(); @@ -29,7 +29,6 @@ describe('ticket recalculateComponents()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}}; const immutableTicketId = 1; await models.Ticket.recalculateComponents(ctx, immutableTicketId, options); diff --git a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js index afc1ada54..b79e41d37 100644 --- a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js +++ b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js @@ -1,13 +1,13 @@ const models = require('vn-loopback/server/server').models; describe('ticket sendSms()', () => { + const {ctx} = beforeAll; it('should send a message and log it', async() => { const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}}; const id = 11; const destination = 222222222; const message = 'this is the message created in a test'; diff --git a/modules/worker/back/methods/calendar/specs/absences.spec.js b/modules/worker/back/methods/calendar/specs/absences.spec.js index b27c9549c..0e6f21a5f 100644 --- a/modules/worker/back/methods/calendar/specs/absences.spec.js +++ b/modules/worker/back/methods/calendar/specs/absences.spec.js @@ -1,6 +1,7 @@ const app = require('vn-loopback/server/server'); describe('Worker absences()', () => { + const {ctx} = beforeAll; it('should get the absence calendar for a full year contract', async() => { const ctx = {req: {accessToken: {userId: 1106}}}; const workerId = 1106; @@ -20,7 +21,6 @@ describe('Worker absences()', () => { it('should get the absence calendar for a permanent contract', async() => { const businessId = 1106; - const ctx = {req: {accessToken: {userId: 9}}}; const now = Date.vnNew(); const year = now.getFullYear(); diff --git a/modules/worker/back/methods/department/specs/getLeaves.spec.js b/modules/worker/back/methods/department/specs/getLeaves.spec.js index fb7c84ff4..d7e934d20 100644 --- a/modules/worker/back/methods/department/specs/getLeaves.spec.js +++ b/modules/worker/back/methods/department/specs/getLeaves.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('department getLeaves()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it('should return the department and the childs containing the search value', async() => { let result = await models.Department.getLeaves(ctx, null, 'INFORMATICA'); diff --git a/modules/worker/back/methods/worker/specs/mySubordinates.spec.js b/modules/worker/back/methods/worker/specs/mySubordinates.spec.js index 7eb118d9c..ecd668603 100644 --- a/modules/worker/back/methods/worker/specs/mySubordinates.spec.js +++ b/modules/worker/back/methods/worker/specs/mySubordinates.spec.js @@ -1,8 +1,8 @@ const app = require('vn-loopback/server/server'); describe('worker mySubordinates()', () => { + const {ctx} = beforeAll; it('should return an array of subordinates greather than 1', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; let result = await app.models.Worker.mySubordinates(ctx); expect(result.length).toBeGreaterThan(1); diff --git a/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js b/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js index f760559cb..27a48a848 100644 --- a/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js +++ b/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js @@ -1,8 +1,8 @@ const app = require('vn-loopback/server/server'); describe('Agency getAgenciesWithWarehouse()', () => { + const {ctx} = beforeAll; const today = Date.vnNew(); - const ctx = {req: {accessToken: {userId: 9}}}; it('should return the agencies that can handle the given delivery request', async() => { const tx = await app.models.Zone.beginTransaction({}); diff --git a/modules/zone/back/methods/agency/specs/landsThatDay.spec.js b/modules/zone/back/methods/agency/specs/landsThatDay.spec.js index 1ec675071..27e71bc6f 100644 --- a/modules/zone/back/methods/agency/specs/landsThatDay.spec.js +++ b/modules/zone/back/methods/agency/specs/landsThatDay.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('Agency landsThatDay()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; const today = Date.vnNew(); it('should return a list of agencies that can land a shipment on a day for an address', async() => { const tx = await models.Agency.beginTransaction({}); diff --git a/modules/zone/back/methods/zone/specs/getEvents.spec.js b/modules/zone/back/methods/zone/specs/getEvents.spec.js index c1dee3e0f..3c9dd76f2 100644 --- a/modules/zone/back/methods/zone/specs/getEvents.spec.js +++ b/modules/zone/back/methods/zone/specs/getEvents.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('zone getEvents()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it('should return all events for the specified geo and agency mode', async() => { const tx = await models.Zone.beginTransaction({}); diff --git a/modules/zone/back/methods/zone/specs/getLeaves.spec.js b/modules/zone/back/methods/zone/specs/getLeaves.spec.js index 9342a0b50..4b8ab926c 100644 --- a/modules/zone/back/methods/zone/specs/getLeaves.spec.js +++ b/modules/zone/back/methods/zone/specs/getLeaves.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('zone getLeaves()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it('should return the country and the childs containing the search value', async() => { const tx = await models.Zone.beginTransaction({}); diff --git a/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js b/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js index fe542fbf3..cf2a070f3 100644 --- a/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js +++ b/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('zone getUpcomingDeliveries()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const {ctx} = beforeAll; it('should check returns data', async() => { const tx = await models.Zone.beginTransaction({}); -- 2.40.1 From 8039530ab42db21e6e76bb72ca4ae90e1fda0e87 Mon Sep 17 00:00:00 2001 From: robert Date: Tue, 11 Jun 2024 14:15:10 +0200 Subject: [PATCH 178/413] fix: refs #7039 fix item-tax --- modules/item/front/tax/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/front/tax/index.js b/modules/item/front/tax/index.js index b72fbefa3..2d70414ab 100644 --- a/modules/item/front/tax/index.js +++ b/modules/item/front/tax/index.js @@ -11,7 +11,7 @@ export default class Controller extends Section { fields: ['id', 'countryFk', 'taxClassFk'], include: [{ relation: 'country', - scope: {fields: ['country']} + scope: {fields: ['name']} }] }; -- 2.40.1 From 13d1d0a61cd8d2f406799ff5ebe60704b3858925 Mon Sep 17 00:00:00 2001 From: pablone Date: Tue, 11 Jun 2024 14:29:16 +0200 Subject: [PATCH 179/413] feat: refs #7499 add printedStickers --- modules/entry/back/methods/entry/getBuys.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index 90c1bb9d0..0ed77e8d1 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -48,7 +48,8 @@ module.exports = Self => { 'weight', 'buyingValue', 'price2', - 'price3' + 'price3', + 'printedStickers' ], include: { relation: 'item', -- 2.40.1 From 79c922300bd53b0be596d9bf28e65757c4a8401b Mon Sep 17 00:00:00 2001 From: jgallego Date: Tue, 11 Jun 2024 14:50:47 +0200 Subject: [PATCH 180/413] hotfix #6408 --- modules/ticket/back/methods/ticket/state.js | 22 ++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/modules/ticket/back/methods/ticket/state.js b/modules/ticket/back/methods/ticket/state.js index 9b0b862f2..eede02d74 100644 --- a/modules/ticket/back/methods/ticket/state.js +++ b/modules/ticket/back/methods/ticket/state.js @@ -26,6 +26,7 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {}; let tx; + let newStateOrder; if (typeof options == 'object') Object.assign(myOptions, options); @@ -40,11 +41,16 @@ module.exports = Self => { throw new UserError('State cannot be blank'); if (params.stateFk) { - const {code} = await models.State.findById(params.stateFk, {fields: ['code']}, myOptions); + const {code, order} = await models.State.findById( + params.stateFk, + {fields: ['code', 'order']}, + myOptions); params.code = code; + newStateOrder = order; } else { - const {id} = await models.State.findOne({where: {code: params.code}}, myOptions); + const {id, order} = await models.State.findOne({where: {code: params.code}}, myOptions); params.stateFk = id; + newStateOrder = order; } if (!params.userFk) { @@ -75,7 +81,9 @@ module.exports = Self => { }, myOptions); const salesPersonFk = ticket.client().salesPersonFk; - if (salesPersonFk) { + const stateChecked = await models.State.findOne({fields: ['order'], where: {code: 'CHECKED'}}); + + if (salesPersonFk && newStateOrder >= stateChecked.order) { const sales = await Self.rawSql(` SELECT DISTINCT s.id, s.itemFk, @@ -83,17 +91,9 @@ module.exports = Self => { s.originalQuantity AS oldQuantity, s.quantity AS newQuantity FROM vn.sale s - JOIN vn.saleTracking st ON st.saleFk = s.id - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.ticketState ts ON ts.ticketFk = t.id - JOIN vn.state s2 ON s2.id = ts.stateFk WHERE s.ticketFk = ? - AND st.isChecked AND s.originalQuantity IS NOT NULL AND s.originalQuantity <> s.quantity - AND s2.\`order\` < (SELECT \`order\` FROM vn.state WHERE code = 'CHECKED') - ORDER BY st.created DESC `, [params.ticketFk], myOptions); let changes = ''; -- 2.40.1 From b9d1c3228b016fe52483faf669963d00b66e3d75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 11 Jun 2024 18:43:26 +0200 Subject: [PATCH 181/413] feat: previas con sitema de reservas refs #6861 --- .../vn/procedures/collection_addWithReservation.sql | 2 +- db/routines/vn/procedures/collection_getAssigned.sql | 2 +- db/routines/vn/procedures/collection_getTickets.sql | 8 ++++---- .../vn/procedures/itemShelvingSale_setQuantity.sql | 6 +++--- ...ingSale_moveReserv.sql => itemShelving_moveReserv.sql} | 7 +++---- .../vn/procedures/sectorCollection_getMyPartial.sql | 3 +-- db/routines/vn/triggers/itemShelvingSale_afterInsert.sql | 6 +++--- 7 files changed, 16 insertions(+), 18 deletions(-) rename db/routines/vn/procedures/{itemShelvingSale_moveReserv.sql => itemShelving_moveReserv.sql} (82%) diff --git a/db/routines/vn/procedures/collection_addWithReservation.sql b/db/routines/vn/procedures/collection_addWithReservation.sql index b483eff39..e3f4eb8d2 100644 --- a/db/routines/vn/procedures/collection_addWithReservation.sql +++ b/db/routines/vn/procedures/collection_addWithReservation.sql @@ -75,7 +75,7 @@ BEGIN END IF; IF vHasThrow THEN - CALL util.throw("No hay disponibilidad para el artículo seleccionado"); + CALL util.throw("There is no available for the selected item"); END IF; IF vSaleGroupFk THEN diff --git a/db/routines/vn/procedures/collection_getAssigned.sql b/db/routines/vn/procedures/collection_getAssigned.sql index 575032e2e..bfaa3096b 100644 --- a/db/routines/vn/procedures/collection_getAssigned.sql +++ b/db/routines/vn/procedures/collection_getAssigned.sql @@ -40,7 +40,7 @@ BEGIN DROP TEMPORARY TABLE tCollection; IF vHasTooMuchCollections THEN - CALL util.throw('Hay colecciones pendientes'); + CALL util.throw('There are pending collections'); END IF; SELECT warehouseFk, itemPackingTypeFk diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql index 8be8c8654..7ecff571a 100644 --- a/db/routines/vn/procedures/collection_getTickets.sql +++ b/db/routines/vn/procedures/collection_getTickets.sql @@ -7,7 +7,7 @@ BEGIN * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observation */ DECLARE vItemPackingTypeFk VARCHAR(1); - DECLARE vDated DATE; + DECLARE vYesterday DATE; -- Si los sacadores son los de pruebas, pinta los colores SELECT itemPackingTypeFk @@ -15,7 +15,7 @@ BEGIN FROM collection WHERE id = vParamFk; - SET vDated = util.yesterday(); + SET vYesterday = util.yesterday(); WITH observation AS ( SELECT tob.ticketFk, tob.description @@ -45,7 +45,7 @@ BEGIN LEFT JOIN vn.worker w ON w.id = c.salesPersonFk LEFT JOIN observation ob ON ob.ticketFk = t.id WHERE t.id = vParamFk - AND t.shipped >= vDated + AND t.shipped >= vYesterday UNION ALL SELECT t.id ticketFk, IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, @@ -84,6 +84,6 @@ BEGIN LEFT JOIN observation ob ON ob.ticketFk = t.id LEFT JOIN vn.client c ON c.id = t.clientFk WHERE sc.id = vParamFk - AND t.shipped >= vDated; + AND t.shipped >= vYesterday; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index 6f008ab33..aed4053bf 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -29,7 +29,7 @@ BEGIN END; IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN - CALL util.throw('Reserva completada'); + CALL util.throw('Reservation completed'); END IF; SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk, SUM(IFNULL(iss.quantity,0)) @@ -43,7 +43,7 @@ BEGIN OR (vQuantity < vReservedQuantity AND (NOT vIsItemShelvingSaleEmpty OR vIsItemShelvingSaleEmpty IS NULL)) OR (vIsItemShelvingSaleEmpty IS NOT NULL AND vQuantity = vReservedQuantity) THEN - CALL util.throw('La cantidad no puede distinta a la reserva'); + CALL util.throw('The quantity cannot be different from the reserved'); END IF; START TRANSACTION; @@ -89,7 +89,7 @@ BEGIN COMMIT; IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN - CALL itemShelvingSale_moveReserv(vItemShelvingFk, vQuantity); + CALL itemShelving_moveReserv(vItemShelvingFk, vQuantity); END IF; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_moveReserv.sql b/db/routines/vn/procedures/itemShelving_moveReserv.sql similarity index 82% rename from db/routines/vn/procedures/itemShelvingSale_moveReserv.sql rename to db/routines/vn/procedures/itemShelving_moveReserv.sql index 7001ee4b8..cff8f6e92 100644 --- a/db/routines/vn/procedures/itemShelvingSale_moveReserv.sql +++ b/db/routines/vn/procedures/itemShelving_moveReserv.sql @@ -1,11 +1,11 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_moveReserv`( +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_moveReserv`( vItemShelvingFk INT(10), vItemFk INT(10) ) BEGIN /** - * Elimina reservas de un itemShelvingSale e intenta reservar en otra ubicación + * Elimina reservas de un itemShelving e intenta reservar en otra ubicación * * @param vItemShelvingFk Id itemShelving */ @@ -17,10 +17,9 @@ BEGIN START TRANSACTION; - SELECT id INTO vItemShelvingFk + SELECT id INTO vItemShelvingFk FROM itemShelving WHERE id = vItemShelvingFk - AND FALSE FOR UPDATE; UPDATE itemShelving diff --git a/db/routines/vn/procedures/sectorCollection_getMyPartial.sql b/db/routines/vn/procedures/sectorCollection_getMyPartial.sql index 23e21d2f3..21f26770a 100644 --- a/db/routines/vn/procedures/sectorCollection_getMyPartial.sql +++ b/db/routines/vn/procedures/sectorCollection_getMyPartial.sql @@ -12,8 +12,7 @@ BEGIN LEFT JOIN vn.sale sl ON sl.id = sgd.saleFk LEFT JOIN itemShelvingSale iss ON iss.saleFk = sl.id WHERE sc.userFk = account.myUser_getId() - AND (ISNULL(scsg.sectorCollectionFk) - OR (NOT iss.isPicked)) + AND (scsg.sectorCollectionFk IS NULL OR NOT iss.isPicked) AND sc.created > util.VN_CURDATE() - INTERVAL 1 DAY; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql index f5bd88b1b..0c609d328 100644 --- a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql +++ b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql @@ -5,8 +5,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelvingSale_afte BEGIN UPDATE sale s - JOIN operator o ON o.workerFk = account.myUser_getId() - SET isPicked = IF(o.isOnReservationMode, isPicked, TRUE) - WHERE id = NEW.saleFk; + JOIN operator o ON o.workerFk = account.myUser_getId() + SET s.isPicked = IF(o.isOnReservationMode, isPicked, TRUE) + WHERE id = NEW.saleFk; END$$ DELIMITER ; \ No newline at end of file -- 2.40.1 From 17fa1e10f64993e99141c353da9eb74fb51347ba Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 12 Jun 2024 07:33:10 +0200 Subject: [PATCH 182/413] feat: refs #6701 Added claimRatio_afterInsert --- db/routines/vn/triggers/claimRatio_afterUpdate.sql | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 db/routines/vn/triggers/claimRatio_afterUpdate.sql diff --git a/db/routines/vn/triggers/claimRatio_afterUpdate.sql b/db/routines/vn/triggers/claimRatio_afterUpdate.sql new file mode 100644 index 000000000..daae7ecf0 --- /dev/null +++ b/db/routines/vn/triggers/claimRatio_afterUpdate.sql @@ -0,0 +1,11 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`claimRatio_afterUpdate` + AFTER UPDATE ON `claimRatio` + FOR EACH ROW +BEGIN + INSERT INTO clientRate(clientFk, `value`) + VALUES(NEW.clientFk, NEW.priceIncreasing) + ON DUPLICATE KEY UPDATE + `value` = VALUES(`value`); +END$$ +DELIMITER ; -- 2.40.1 From c4c6df5a78f445a235eb210987445100609d29fe Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 12 Jun 2024 07:41:00 +0200 Subject: [PATCH 183/413] feat(jenkinsfile): use build_id --- Jenkinsfile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index c8edac0a4..19f47c5b0 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -121,7 +121,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" + env.VERSION = "${packageJson.version}-build${env.BUILD_ID}" } sh 'docker-compose build back' } @@ -159,7 +159,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" + env.VERSION = "${packageJson.version}-build${env.BUILD_ID}" } sh 'gulp build' sh 'docker-compose build front' @@ -179,7 +179,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" + env.VERSION = "${packageJson.version}-build${env.BUILD_ID}" } sh 'docker login --username $CREDENTIALS_USR --password $CREDENTIALS_PSW $REGISTRY' sh 'docker-compose push' @@ -210,7 +210,7 @@ pipeline { steps { script { def packageJson = readJSON file: 'package.json' - env.VERSION = "${packageJson.version}-vn${env.BUILD_ID}" + env.VERSION = "${packageJson.version}-build${env.BUILD_ID}" } withKubeConfig([ serverUrl: "$KUBERNETES_API", -- 2.40.1 From 2b45c2c61a897562ee2e765d01ca7320e6246590 Mon Sep 17 00:00:00 2001 From: Jon Date: Wed, 12 Jun 2024 08:25:50 +0200 Subject: [PATCH 184/413] feat: refs #6436 new test changes, rollback order/filter and /ticket/clone --- .../methods/application/spec/execute.spec.js | 18 +++------------- .../entry/specs/addFromPackaging.spec.js | 16 +++----------- .../methods/invoice-in/specs/clone.spec.js | 21 +++++-------------- .../specs/getAlternative.spec.js | 7 ++----- .../methods/item/specs/regularize.spec.js | 14 ++----------- .../back/methods/order/specs/filter.spec.js | 6 +++++- .../supplier/specs/updateFiscalData.spec.js | 1 - .../specs/deleteExpeditions.spec.js | 6 ++---- .../back/methods/sale/specs/clone.spec.js | 19 ++++++++++++----- 9 files changed, 36 insertions(+), 72 deletions(-) diff --git a/loopback/common/methods/application/spec/execute.spec.js b/loopback/common/methods/application/spec/execute.spec.js index 1a0a8ace9..b697dbef9 100644 --- a/loopback/common/methods/application/spec/execute.spec.js +++ b/loopback/common/methods/application/spec/execute.spec.js @@ -2,18 +2,9 @@ const models = require('vn-loopback/server/server').models; describe('Application execute()/executeProc()/executeFunc()', () => { const userWithoutPrivileges = 1; - const userWithPrivileges = 9; const userWithInheritedPrivileges = 120; let tx; - - function getCtx(userId) { - return { - req: { - accessToken: {userId}, - headers: {origin: 'http://localhost'} - } - }; - } + const {ctx} = beforeAll; beforeEach(async() => { tx = await models.Application.beginTransaction({}); @@ -42,7 +33,7 @@ describe('Application execute()/executeProc()/executeFunc()', () => { }); it('should throw error when execute procedure and not have privileges', async() => { - const ctx = getCtx(userWithoutPrivileges); + const ctx = {req: {accessToken: {userId: userWithoutPrivileges}}}; let error; try { @@ -66,7 +57,6 @@ describe('Application execute()/executeProc()/executeFunc()', () => { }); it('should execute procedure and get data', async() => { - const ctx = getCtx(userWithPrivileges); try { const options = {transaction: tx}; @@ -90,7 +80,6 @@ describe('Application execute()/executeProc()/executeFunc()', () => { describe('Application executeProc()', () => { it('should execute procedure and get data (executeProc)', async() => { - const ctx = getCtx(userWithPrivileges); try { const options = {transaction: tx}; @@ -115,7 +104,6 @@ describe('Application execute()/executeProc()/executeFunc()', () => { describe('Application executeFunc()', () => { it('should execute function and get data', async() => { - const ctx = getCtx(userWithPrivileges); try { const options = {transaction: tx}; @@ -137,7 +125,7 @@ describe('Application execute()/executeProc()/executeFunc()', () => { }); it('should execute function and get data with user with inherited privileges', async() => { - const ctx = getCtx(userWithInheritedPrivileges); + const ctx = {req: {accessToken: {userId: userWithInheritedPrivileges}}}; try { const options = {transaction: tx}; diff --git a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js index 1b0d4656f..21940d57e 100644 --- a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js +++ b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js @@ -1,5 +1,5 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('entry addFromPackaging()', () => { const supplier = 442; @@ -8,21 +8,11 @@ describe('entry addFromPackaging()', () => { yesterday.setDate(today.getDate() - 1); beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 49}, - http: { - req: { - headers: {origin: 'http://localhost'}, - }, - }, - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx, - }); + mockLoopBackContext(); }); it('should create an incoming travel', async() => { - const ctx = {args: {isTravelReception: true, supplier}}; + const ctx = {accessToken: {userId: 49}, args: {isTravelReception: true, supplier}}; const tx = await models.Entry.beginTransaction({}); const options = {transaction: tx}; diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js index 436306aab..9fef506d4 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js @@ -1,24 +1,11 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('invoiceIn clone()', () => { - let ctx; + const {ctx} = beforeAll; let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.Sale.beginTransaction({}); options.transaction = tx; @@ -28,7 +15,8 @@ describe('invoiceIn clone()', () => { await tx.rollback(); }); - it('should return the cloned invoiceIn and also clone invoiceInDueDays and invoiceInTaxes if there are any referencing the invoiceIn', async() => { + it('should return the cloned invoiceIn and also clone invoiceInDueDays ' + + 'and invoiceInTaxes if there are any referencing the invoiceIn', async() => { const clone = await models.InvoiceIn.clone(ctx, 1, false, options); expect(clone.supplierRef).toEqual('1234(2)'); @@ -51,7 +39,8 @@ describe('invoiceIn clone()', () => { expect(invoiceInDueDay.length).toEqual(2); }); - it('should return the cloned invoiceIn and also clone invoiceInIntrastat and invoiceInTaxes if it is rectificative', async() => { + it('should return the cloned invoiceIn and also clone invoiceInIntrastat ' + + 'and invoiceInTaxes if it is rectificative', async() => { const clone = await models.InvoiceIn.clone(ctx, 1, true, options); expect(clone.supplierRef).toEqual('1234(2)'); 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 3f4917477..3082cabd1 100644 --- a/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js @@ -1,12 +1,9 @@ const {models} = require('vn-loopback/server/server'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('itemShelving getAlternative()', () => { beforeAll(async() => { - ctx = { - req: { - headers: {origin: 'http://localhost'}, - } - }; + mockLoopBackContext(); }); it('should return a list of items without alternatives', async() => { diff --git a/modules/item/back/methods/item/specs/regularize.spec.js b/modules/item/back/methods/item/specs/regularize.spec.js index e7df9a003..b61dec995 100644 --- a/modules/item/back/methods/item/specs/regularize.spec.js +++ b/modules/item/back/methods/item/specs/regularize.spec.js @@ -1,19 +1,9 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); +const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('regularize()', () => { beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 18}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); + mockLoopBackContext(); }); it('should create a new ticket and add a line', async() => { diff --git a/modules/order/back/methods/order/specs/filter.spec.js b/modules/order/back/methods/order/specs/filter.spec.js index 95cb488c8..68de7fe04 100644 --- a/modules/order/back/methods/order/specs/filter.spec.js +++ b/modules/order/back/methods/order/specs/filter.spec.js @@ -1,7 +1,11 @@ const models = require('vn-loopback/server/server').models; describe('order filter()', () => { - const {ctx} = beforeAll; + const ctx = { + req: {accessToken: {userId: 9}}, + args: {}, + params: {} + }; it('should call the filter method with a basic search', async() => { const myCtx = Object.assign({}, ctx); diff --git a/modules/supplier/back/methods/supplier/specs/updateFiscalData.spec.js b/modules/supplier/back/methods/supplier/specs/updateFiscalData.spec.js index 7cb95f840..f1efbbbba 100644 --- a/modules/supplier/back/methods/supplier/specs/updateFiscalData.spec.js +++ b/modules/supplier/back/methods/supplier/specs/updateFiscalData.spec.js @@ -3,7 +3,6 @@ const LoopBackContext = require('loopback-context'); describe('Supplier updateFiscalData()', () => { const supplierId = 1; - const administrativeId = 5; const buyerId = 35; const name = 'NEW PLANTS'; diff --git a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js index 2c34c994b..b72334142 100644 --- a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js +++ b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js @@ -1,10 +1,8 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); +// const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket deleteExpeditions()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + const {ctx} = beforeAll; it('should delete the selected expeditions', async() => { const tx = await models.Expedition.beginTransaction({}); diff --git a/modules/ticket/back/methods/sale/specs/clone.spec.js b/modules/ticket/back/methods/sale/specs/clone.spec.js index ef2c6a9a3..e2220c028 100644 --- a/modules/ticket/back/methods/sale/specs/clone.spec.js +++ b/modules/ticket/back/methods/sale/specs/clone.spec.js @@ -1,15 +1,24 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext, mockBeforeAll} = require('vn-loopback/../../back/vn-jasmine'); +const LoopBackContext = require('loopback-context'); describe('Ticket cloning - clone function', () => { - let ctx = mockBeforeAll({ejemploe: true}); + let ctx; let options; let tx; - beforeAll(async() => { - mockLoopBackContext(); - }); beforeEach(async() => { + ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'http://localhost'} + }, + args: {} + }; + + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: ctx.req + }); + options = {transaction: tx}; tx = await models.Sale.beginTransaction({}); options.transaction = tx; -- 2.40.1 From 789e0e65e3172737bc8b8a1dfc8a75d47e23fea6 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 12 Jun 2024 09:12:48 +0200 Subject: [PATCH 185/413] fix(sale): rocket is only sent if it has sales --- modules/ticket/back/methods/ticket/state.js | 60 +++++++++++---------- 1 file changed, 31 insertions(+), 29 deletions(-) diff --git a/modules/ticket/back/methods/ticket/state.js b/modules/ticket/back/methods/ticket/state.js index eede02d74..1e6069b79 100644 --- a/modules/ticket/back/methods/ticket/state.js +++ b/modules/ticket/back/methods/ticket/state.js @@ -86,39 +86,41 @@ module.exports = Self => { if (salesPersonFk && newStateOrder >= stateChecked.order) { const sales = await Self.rawSql(` SELECT DISTINCT s.id, - s.itemFk, - s.concept, - s.originalQuantity AS oldQuantity, - s.quantity AS newQuantity + s.itemFk, + s.concept, + s.originalQuantity AS oldQuantity, + s.quantity AS newQuantity FROM vn.sale s - WHERE s.ticketFk = ? - AND s.originalQuantity IS NOT NULL - AND s.originalQuantity <> s.quantity + WHERE s.ticketFk = ? + AND s.originalQuantity IS NOT NULL + AND s.originalQuantity <> s.quantity `, [params.ticketFk], myOptions); - let changes = ''; - const url = await models.Url.getUrl(); - const $t = ctx.req.__; - for (let sale of sales) { - changes += `\r\n-` + $t('Changes in sales', { - itemId: sale.itemFk, - concept: sale.concept, - oldQuantity: sale.oldQuantity, - newQuantity: sale.newQuantity, - itemUrl: `${url}item/${sale.itemFk}/summary` - }); - const currentSale = await models.Sale.findById(sale.id, null, myOptions); - await currentSale.updateAttributes({ - originalQuantity: currentSale.quantity - }, myOptions); - } + if (sales.length) { + let changes = ''; + const url = await models.Url.getUrl(); + const $t = ctx.req.__; + for (let sale of sales) { + changes += `\r\n-` + $t('Changes in sales', { + itemId: sale.itemFk, + concept: sale.concept, + oldQuantity: sale.oldQuantity, + newQuantity: sale.newQuantity, + itemUrl: `${url}item/${sale.itemFk}/summary` + }); + const currentSale = await models.Sale.findById(sale.id, null, myOptions); + await currentSale.updateAttributes({ + originalQuantity: currentSale.quantity + }, myOptions); + } - const message = $t('Changed sale quantity', { - ticketId: ticket.id, - changes: changes, - ticketUrl: `${url}ticket/${ticket.id}/sale` - }); - await models.Chat.sendCheckingPresence(ctx, salesPersonFk, message, myOptions); + const message = $t('Changed sale quantity', { + ticketId: ticket.id, + changes: changes, + ticketUrl: `${url}ticket/${ticket.id}/sale` + }); + await models.Chat.sendCheckingPresence(ctx, salesPersonFk, message, myOptions); + } } await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticket.id, params.code], myOptions); -- 2.40.1 From d9b0a1a75c585f357413c358d95ef31e44c81015 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 12 Jun 2024 09:59:58 +0200 Subject: [PATCH 186/413] fix(updateQuantity): fix rocket translation --- modules/ticket/back/methods/sale/updateQuantity.js | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index 610826283..36d75ffed 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -72,16 +72,20 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { const url = await Self.app.models.Url.getUrl(); - const message = $t('Changed sale quantity', { - ticketId: sale.ticket().id, + const change = $t('Changes in sales', { itemId: sale.itemFk, concept: sale.concept, oldQuantity: oldQuantity, newQuantity: newQuantity, - ticketUrl: `${url}ticket/${sale.ticket().id}/sale`, itemUrl: `${url}item/${sale.itemFk}/summary` }); + const message = $t('Changed sale quantity', { + ticketId: sale.ticket().id, + changes: change, + ticketUrl: `${url}ticket/${sale.ticket().id}/sale`, + }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); } -- 2.40.1 From dcb9d54105ecc500869ad3c8c1b3b07dbbac4ecb Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 12 Jun 2024 11:48:01 +0200 Subject: [PATCH 187/413] feat: refs #7545 Deleted hasIncoterms client column --- db/versions/11099-greenFern/00-firstScript.sql | 3 +++ modules/client/back/methods/client/updateFiscalData.js | 4 ---- modules/client/back/models/client.json | 3 --- modules/client/front/fiscal-data/index.html | 5 ----- 4 files changed, 3 insertions(+), 12 deletions(-) create mode 100644 db/versions/11099-greenFern/00-firstScript.sql diff --git a/db/versions/11099-greenFern/00-firstScript.sql b/db/versions/11099-greenFern/00-firstScript.sql new file mode 100644 index 000000000..7dd84d1b7 --- /dev/null +++ b/db/versions/11099-greenFern/00-firstScript.sql @@ -0,0 +1,3 @@ +ALTER TABLE vn.client + CHANGE hasIncoterms hasIncoterms__ tinyint(1) DEFAULT 0 NOT NULL + COMMENT '@deprecated 2024-06-12 refs #7545 Received incoterms authorization from client'; \ No newline at end of file diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 9a6255215..851648658 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -96,10 +96,6 @@ module.exports = Self => { arg: 'despiteOfClient', type: 'any' }, - { - arg: 'hasIncoterms', - type: 'boolean' - }, { arg: 'hasElectronicInvoice', type: 'boolean' diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index 510857595..f3eb9919b 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -97,9 +97,6 @@ "hasCoreVnh": { "type": "boolean" }, - "hasIncoterms": { - "type": "boolean" - }, "isTaxDataChecked":{ "type": "boolean" }, diff --git a/modules/client/front/fiscal-data/index.html b/modules/client/front/fiscal-data/index.html index c366c8ca3..979f45fcc 100644 --- a/modules/client/front/fiscal-data/index.html +++ b/modules/client/front/fiscal-data/index.html @@ -184,11 +184,6 @@ - - Date: Wed, 12 Jun 2024 11:58:07 +0200 Subject: [PATCH 188/413] hotfix claim --- db/dump/.dump/data.sql | 2 +- modules/claim/back/methods/claim/updateClaim.js | 14 +++++--------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index c0d0c34e6..632f3b4b0 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -1711,7 +1711,7 @@ INSERT INTO `ACL` VALUES (570,'InvoiceOut','canCreatePdf','WRITE','ALLOW','ROLE' INSERT INTO `ACL` VALUES (571,'Supplier','editPayMethodCheck','WRITE','ALLOW','ROLE','financial'); INSERT INTO `ACL` VALUES (572,'Worker','isTeamBoss','WRITE','ALLOW','ROLE','teamBoss'); INSERT INTO `ACL` VALUES (573,'Worker','forceIsSubordinate','READ','ALLOW','ROLE','hr'); -INSERT INTO `ACL` VALUES (574,'Claim','editState','WRITE','ALLOW','ROLE','claimManager'); +INSERT INTO `ACL` VALUES (574,'Claim','editPickup','WRITE','ALLOW','ROLE','claimManager'); INSERT INTO `ACL` VALUES (577,'Claim','findOne','READ','ALLOW','ROLE','salesPerson'); INSERT INTO `ACL` VALUES (579,'Claim','updateClaim','WRITE','ALLOW','ROLE','salesPerson'); INSERT INTO `ACL` VALUES (580,'Claim','regularizeClaim','WRITE','ALLOW','ROLE','claimManager'); diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index c99e0e2f1..326192385 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -69,30 +69,26 @@ module.exports = Self => { } } }, myOptions); - // Get sales person from claim client - const salesPerson = claim.client().salesPersonUser(); - const changedPickup = args.pickup != claim.pickup; + const changedPickup = args.pickup && args.pickup != claim.pickup; - // Validate when claimState has been changed if (args.claimStateFk) { const canEditOldState = await models.ClaimState.isEditable(ctx, claim.claimStateFk, myOptions); const canEditNewState = await models.ClaimState.isEditable(ctx, args.claimStateFk, myOptions); - const canEditState = await models.ACL.checkAccessAcl(ctx, 'Claim', 'editState', 'WRITE'); + const canEditPickup = await models.ACL.checkAccessAcl(ctx, 'Claim', 'editPickup', 'WRITE'); - if (!canEditOldState || !canEditNewState || changedPickup && !canEditState) + if (!canEditOldState || !canEditNewState || (changedPickup && !canEditPickup)) throw new UserError(`You don't have enough privileges to change that field`); } delete args.ctx; const updatedClaim = await claim.updateAttributes(args, myOptions); - // When pickup has been changed + const salesPerson = claim.client().salesPersonUser(); if (salesPerson) { if (changedPickup && updatedClaim.pickup) await notifyPickUp(ctx, salesPerson.id, claim); - // When claimState has been changed if (args.claimStateFk) { const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); await notifyStateChange(ctx, salesPerson.id, claim, newState.description); @@ -113,7 +109,7 @@ module.exports = Self => { async function notifyStateChange(ctx, workerId, claim, newState) { const models = Self.app.models; const url = await models.Url.getUrl(); - const $t = ctx.req.__; // $translate + const $t = ctx.req.__; const message = $t(`Claim state has changed to`, { claimId: claim.id, -- 2.40.1 From 84a51d3e8d0163ed7f83fa90d358922fc4366cc7 Mon Sep 17 00:00:00 2001 From: Jon Date: Wed, 12 Jun 2024 12:23:37 +0200 Subject: [PATCH 189/413] feat: refs #6436 changed tests --- back/methods/collection/spec/setSaleQuantity.spec.js | 6 +++--- back/tests.js | 11 +++++++++-- back/vn-jasmine.js | 2 ++ loopback/common/methods/vn-model/specs/crud.spec.js | 6 +++--- .../methods/vn-model/specs/rewriteDbError.spec.js | 6 +++--- .../back/methods/claim/specs/regularizeClaim.spec.js | 6 +++--- .../methods/claim/specs/updateClaimAction.spec.js | 6 +++--- .../methods/client/specs/addressesPropagateRe.spec.js | 9 +++++---- .../back/methods/client/specs/createAddress.spec.js | 6 +++--- .../back/methods/client/specs/createWithUser.spec.js | 6 +++--- .../back/methods/client/specs/updateAddress.spec.js | 6 +++--- modules/client/back/models/specs/address.spec.js | 6 +++--- .../back/methods/entry/specs/addFromPackaging.spec.js | 6 +++--- .../back/methods/entry/specs/editLatestBuys.spec.js | 6 +++--- .../methods/entry/specs/importBuysPreview.spec.js | 6 +++--- .../back/methods/invoice-in-due-day/specs/new.spec.js | 6 +++--- .../item-shelving/specs/getAlternative.spec.js | 6 +++--- modules/item/back/methods/item/specs/clone.spec.js | 6 +++--- .../item/back/methods/item/specs/regularize.spec.js | 6 +++--- .../item/back/methods/item/specs/updateTaxes.spec.js | 6 +++--- modules/item/back/methods/tag/specs/onSubmit.spec.js | 6 +++--- modules/order/back/methods/order/specs/filter.spec.js | 9 ++++----- .../methods/agency-term/specs/createInvoiceIn.spec.js | 1 - modules/route/back/methods/route/specs/clone.spec.js | 6 +++--- .../back/methods/route/specs/guessPriority.spec.js | 11 ----------- .../back/methods/route/specs/updateWorkCenter.spec.js | 6 +++--- .../expedition/specs/deleteExpeditions.spec.js | 1 - .../ticket/back/methods/sale/specs/canEdit.spec.js | 6 +++--- modules/ticket/back/methods/sale/specs/clone.spec.js | 1 - .../back/methods/sale/specs/deleteSales.spec.js | 6 +++--- .../ticket/back/methods/sale/specs/reserve.spec.js | 6 +++--- .../back/methods/ticket-request/specs/confirm.spec.js | 6 +++--- .../back/methods/ticket-request/specs/deny.spec.js | 6 +++--- .../back/methods/ticket/specs/updateDiscount.spec.js | 6 +++--- .../ticket/back/models/specs/ticket-packaging.spec.js | 6 +++--- .../methods/travel/specs/createThermograph.spec.js | 6 +++--- modules/worker/back/methods/worker/specs/new.spec.js | 6 +++--- modules/zone/back/methods/zone/specs/clone.spec.js | 6 +++--- .../zone/back/methods/zone/specs/exclusionGeo.spec.js | 6 +++--- .../back/methods/zone/specs/toggleIsIncluded.spec.js | 6 +++--- 40 files changed, 116 insertions(+), 121 deletions(-) diff --git a/back/methods/collection/spec/setSaleQuantity.spec.js b/back/methods/collection/spec/setSaleQuantity.spec.js index 7abcda36b..e26e25115 100644 --- a/back/methods/collection/spec/setSaleQuantity.spec.js +++ b/back/methods/collection/spec/setSaleQuantity.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('setSaleQuantity()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should change quantity sale', async() => { const tx = await models.Ticket.beginTransaction({}); diff --git a/back/tests.js b/back/tests.js index 2e89cfd05..bfbe9e681 100644 --- a/back/tests.js +++ b/back/tests.js @@ -84,7 +84,10 @@ async function test() { 'loopback/**/*[sS]pec.js', 'modules/*/back/**/*.[sS]pec.js' ], - helpers: [`back/vn-jasmine.js`] + helpers: [`back/vn-jasmine.js`], + asyncHelpers: {miHelperAsync + + } }; if (PARALLEL) { @@ -114,10 +117,14 @@ async function test() { if (opts.ci) runner.jasmine.DEFAULT_TIMEOUT_INTERVAL = SPEC_TIMEOUT; - // runner.loadConfigFile('back/jasmine.json'); runner.loadConfig(config); process.env.SPEC_IS_RUNNING = true; await runner.execute(); } test(); +function miHelperAsync() { + return new Promise((resolve, reject) => { + resolve('Resultado del helper'); + }); +} diff --git a/back/vn-jasmine.js b/back/vn-jasmine.js index 88dc55dc0..1c022637e 100644 --- a/back/vn-jasmine.js +++ b/back/vn-jasmine.js @@ -45,4 +45,6 @@ module.exports = { (function init() { vnBeforeAll(); + describe.$inject = () => { + }; })(); diff --git a/loopback/common/methods/vn-model/specs/crud.spec.js b/loopback/common/methods/vn-model/specs/crud.spec.js index d120db92a..a8923aed8 100644 --- a/loopback/common/methods/vn-model/specs/crud.spec.js +++ b/loopback/common/methods/vn-model/specs/crud.spec.js @@ -2,9 +2,9 @@ const app = require('vn-loopback/server/server'); const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Model crud()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); let insertId; const barcodeModel = app.models.ItemBarcode; diff --git a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js index e3c24e74a..d89508383 100644 --- a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js +++ b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Model rewriteDbError()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should extend rewriteDbError properties to any model passed', () => { const exampleModel = models.ItemTag; diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 224adc997..879979829 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -40,9 +40,9 @@ describe('claim regularizeClaim()', () => { return await models.ClaimEnd.create(claimEnds, options); } - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should send a chat message with value "Trash" and then change claim state to resolved', async() => { const tx = await models.Claim.beginTransaction({}); diff --git a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js index c939f59de..506c80abb 100644 --- a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js @@ -2,9 +2,9 @@ const app = require('vn-loopback/server/server'); const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Update Claim', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); const newDate = Date.vnNew(); const original = { ticketFk: 3, diff --git a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js index ec4ebe471..be2732bdb 100644 --- a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js +++ b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js @@ -2,11 +2,12 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Client addressesPropagateRe', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); - it('should propagate the isEqualizated on both addresses of Mr Wayne and set hasToInvoiceByAddress to false', async() => { + it('should propagate the isEqualizated on both addresses of Mr Wayne' + + ' and set hasToInvoiceByAddress to false', async() => { const tx = await models.Client.beginTransaction({}); try { diff --git a/modules/client/back/methods/client/specs/createAddress.spec.js b/modules/client/back/methods/client/specs/createAddress.spec.js index 0556ce2cf..9c827a40e 100644 --- a/modules/client/back/methods/client/specs/createAddress.spec.js +++ b/modules/client/back/methods/client/specs/createAddress.spec.js @@ -7,9 +7,9 @@ describe('Address createAddress', () => { const incotermsFk = 'FAS'; const customAgentOneId = 1; - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should throw a non uee member error if no incoterms is defined', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index cee8e0b38..47f2d34ce 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -16,9 +16,9 @@ describe('Client Create', () => { const newAccountWithoutEmail = JSON.parse(JSON.stringify(newAccount)); delete newAccountWithoutEmail.email; - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it(`should not find deadpool as he's not created yet`, async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/updateAddress.spec.js b/modules/client/back/methods/client/specs/updateAddress.spec.js index dd5142af0..d0c5e4d88 100644 --- a/modules/client/back/methods/client/specs/updateAddress.spec.js +++ b/modules/client/back/methods/client/specs/updateAddress.spec.js @@ -14,9 +14,9 @@ describe('Address updateAddress', () => { } }; - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should throw the non uee member error if no incoterms is defined', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/models/specs/address.spec.js b/modules/client/back/models/specs/address.spec.js index 4baa1bdca..d390d045c 100644 --- a/modules/client/back/models/specs/address.spec.js +++ b/modules/client/back/models/specs/address.spec.js @@ -5,9 +5,9 @@ describe('loopback model address', () => { let createdAddressId; const clientId = 1101; - beforeAll(() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); afterAll(async() => { const client = await models.Client.findById(clientId); diff --git a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js index 21940d57e..865e59bca 100644 --- a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js +++ b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js @@ -7,9 +7,9 @@ describe('entry addFromPackaging()', () => { const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should create an incoming travel', async() => { const ctx = {accessToken: {userId: 49}, args: {isTravelReception: true, supplier}}; diff --git a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js index bff758eea..04c38078b 100644 --- a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Buy editLatestsBuys()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should change the value of a given column for the selected buys', async() => { const tx = await models.Buy.beginTransaction({}); diff --git a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js index bab46ad59..57adaf2dd 100644 --- a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js +++ b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js @@ -3,9 +3,9 @@ const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('entry importBuysPreview()', () => { const entryId = 1; - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should return the buys with the calculated packagingFk', async() => { const tx = await models.Entry.beginTransaction({}); diff --git a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js index 02a43d4af..9a996d103 100644 --- a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('invoiceInDueDay new()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should correctly create a new due day', async() => { const userId = 9; 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 3082cabd1..006842eca 100644 --- a/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js @@ -2,9 +2,9 @@ const {models} = require('vn-loopback/server/server'); const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('itemShelving getAlternative()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should return a list of items without alternatives', async() => { const shelvingFk = 'HEJ'; diff --git a/modules/item/back/methods/item/specs/clone.spec.js b/modules/item/back/methods/item/specs/clone.spec.js index 1a479cd84..e252c910c 100644 --- a/modules/item/back/methods/item/specs/clone.spec.js +++ b/modules/item/back/methods/item/specs/clone.spec.js @@ -3,9 +3,9 @@ const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('item clone()', () => { let nextItemId; - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); beforeEach(async() => { let query = `SELECT i1.id + 1 as id FROM vn.item i1 diff --git a/modules/item/back/methods/item/specs/regularize.spec.js b/modules/item/back/methods/item/specs/regularize.spec.js index b61dec995..097d61d5c 100644 --- a/modules/item/back/methods/item/specs/regularize.spec.js +++ b/modules/item/back/methods/item/specs/regularize.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('regularize()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should create a new ticket and add a line', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/methods/item/specs/updateTaxes.spec.js b/modules/item/back/methods/item/specs/updateTaxes.spec.js index 49f95c1ed..3d0f1ce33 100644 --- a/modules/item/back/methods/item/specs/updateTaxes.spec.js +++ b/modules/item/back/methods/item/specs/updateTaxes.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('item updateTaxes()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should throw an error if the taxClassFk is blank', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/methods/tag/specs/onSubmit.spec.js b/modules/item/back/methods/tag/specs/onSubmit.spec.js index 1830aafcf..be77b0248 100644 --- a/modules/item/back/methods/tag/specs/onSubmit.spec.js +++ b/modules/item/back/methods/tag/specs/onSubmit.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('tag onSubmit()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should delete a tag', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/order/back/methods/order/specs/filter.spec.js b/modules/order/back/methods/order/specs/filter.spec.js index 68de7fe04..a2ec88577 100644 --- a/modules/order/back/methods/order/specs/filter.spec.js +++ b/modules/order/back/methods/order/specs/filter.spec.js @@ -1,11 +1,10 @@ +const {mockLoopBackContext} = require('../../../../../../back/vn-jasmine'); + const models = require('vn-loopback/server/server').models; describe('order filter()', () => { - const ctx = { - req: {accessToken: {userId: 9}}, - args: {}, - params: {} - }; + let ctx; + beforeAll(() => ctx = mockLoopBackContext()); it('should call the filter method with a basic search', async() => { const myCtx = Object.assign({}, ctx); diff --git a/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js b/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js index a625605d2..dbe9d0e1e 100644 --- a/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js +++ b/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js @@ -1,5 +1,4 @@ const models = require('vn-loopback/server/server').models; -// const LoopBackContext = require('loopback-context'); describe('AgencyTerm createInvoiceIn()', () => { const {ctx} = beforeAll; diff --git a/modules/route/back/methods/route/specs/clone.spec.js b/modules/route/back/methods/route/specs/clone.spec.js index 98240488c..b9ad7751c 100644 --- a/modules/route/back/methods/route/specs/clone.spec.js +++ b/modules/route/back/methods/route/specs/clone.spec.js @@ -2,9 +2,9 @@ const app = require('vn-loopback/server/server'); const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('route clone()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); const createdDate = Date.vnNew(); it('should throw an error if the amount of ids pased to the clone function do no match the database', async() => { diff --git a/modules/route/back/methods/route/specs/guessPriority.spec.js b/modules/route/back/methods/route/specs/guessPriority.spec.js index d73db6379..34fa510e1 100644 --- a/modules/route/back/methods/route/specs/guessPriority.spec.js +++ b/modules/route/back/methods/route/specs/guessPriority.spec.js @@ -1,18 +1,10 @@ const app = require('vn-loopback/server/server'); -// const LoopBackContext = require('loopback-context'); describe('route guessPriority()', () => { const targetRouteId = 7; let routeTicketsToRestore; - const {ctx} = beforeAll; - // beforeAll(() => { - // spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - // active: activeCtx - // }); - // }); - afterAll(async() => { let restoreFixtures = []; routeTicketsToRestore.forEach(ticket => { @@ -22,9 +14,6 @@ describe('route guessPriority()', () => { }); it('should call guessPriority() then check all tickets in that route have their priorities defined', async() => { - // const ctx = { - // req: activeCtx - // }; routeTicketsToRestore = await app.models.Ticket.find({where: {routeFk: targetRouteId}}); await app.models.Route.guessPriority(ctx, targetRouteId); diff --git a/modules/route/back/methods/route/specs/updateWorkCenter.spec.js b/modules/route/back/methods/route/specs/updateWorkCenter.spec.js index 315460d4a..4d5fbcbdc 100644 --- a/modules/route/back/methods/route/specs/updateWorkCenter.spec.js +++ b/modules/route/back/methods/route/specs/updateWorkCenter.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('route updateWorkCenter()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); const routeId = 1; it('should set the commission work center if the worker has workCenter', async() => { diff --git a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js index b72334142..4134b28b8 100644 --- a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js +++ b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js @@ -1,5 +1,4 @@ const models = require('vn-loopback/server/server').models; -// const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket deleteExpeditions()', () => { const {ctx} = beforeAll; diff --git a/modules/ticket/back/methods/sale/specs/canEdit.spec.js b/modules/ticket/back/methods/sale/specs/canEdit.spec.js index 3185b01e7..668b1c273 100644 --- a/modules/ticket/back/methods/sale/specs/canEdit.spec.js +++ b/modules/ticket/back/methods/sale/specs/canEdit.spec.js @@ -3,9 +3,9 @@ const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale canEdit()', () => { const employeeId = 1; - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); describe('sale not exists', () => { it('should return error if sale not exists', async() => { diff --git a/modules/ticket/back/methods/sale/specs/clone.spec.js b/modules/ticket/back/methods/sale/specs/clone.spec.js index e2220c028..8767c2857 100644 --- a/modules/ticket/back/methods/sale/specs/clone.spec.js +++ b/modules/ticket/back/methods/sale/specs/clone.spec.js @@ -14,7 +14,6 @@ describe('Ticket cloning - clone function', () => { }, args: {} }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ active: ctx.req }); diff --git a/modules/ticket/back/methods/sale/specs/deleteSales.spec.js b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js index 8d0e4bd4e..8dc261b13 100644 --- a/modules/ticket/back/methods/sale/specs/deleteSales.spec.js +++ b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale deleteSales()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should throw an error if the ticket of the given sales is not editable', async() => { const tx = await models.Sale.beginTransaction({}); diff --git a/modules/ticket/back/methods/sale/specs/reserve.spec.js b/modules/ticket/back/methods/sale/specs/reserve.spec.js index 37ebf10ab..009d7b711 100644 --- a/modules/ticket/back/methods/sale/specs/reserve.spec.js +++ b/modules/ticket/back/methods/sale/specs/reserve.spec.js @@ -10,9 +10,9 @@ describe('sale reserve()', () => { } }; - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should throw an error if the ticket can not be modified', async() => { const tx = await models.Sale.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js index 8a1130e7d..396834df2 100644 --- a/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket-request confirm()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it(`should throw an error if the item doesn't exist`, async() => { const tx = await models.TicketRequest.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket-request/specs/deny.spec.js b/modules/ticket/back/methods/ticket-request/specs/deny.spec.js index 1259f1284..aef07bd1b 100644 --- a/modules/ticket/back/methods/ticket-request/specs/deny.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/deny.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket-request deny()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should return the denied ticket request', async() => { const tx = await models.TicketRequest.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js index c0c5333ba..01e6e64bb 100644 --- a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js +++ b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale updateDiscount()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); const originalSaleId = 8; it('should throw an error if no sales were selected', async() => { diff --git a/modules/ticket/back/models/specs/ticket-packaging.spec.js b/modules/ticket/back/models/specs/ticket-packaging.spec.js index 97a936018..7ff863cff 100644 --- a/modules/ticket/back/models/specs/ticket-packaging.spec.js +++ b/modules/ticket/back/models/specs/ticket-packaging.spec.js @@ -2,9 +2,9 @@ const app = require('vn-loopback/server/server'); const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket model TicketTracking', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); let ticketTrackingId; afterAll(async() => { diff --git a/modules/travel/back/methods/travel/specs/createThermograph.spec.js b/modules/travel/back/methods/travel/specs/createThermograph.spec.js index 9c93d6d52..2b0ae48f4 100644 --- a/modules/travel/back/methods/travel/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/travel/specs/createThermograph.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Travel createThermograph()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); const travelId = 3; const currentUserId = 1102; const thermographId = '138350-0'; diff --git a/modules/worker/back/methods/worker/specs/new.spec.js b/modules/worker/back/methods/worker/specs/new.spec.js index b16efb16a..04540b9b7 100644 --- a/modules/worker/back/methods/worker/specs/new.spec.js +++ b/modules/worker/back/methods/worker/specs/new.spec.js @@ -10,9 +10,9 @@ describe('Worker new', () => { let tx; let opts; - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); describe('should return error', () => { beforeEach(async() => { diff --git a/modules/zone/back/methods/zone/specs/clone.spec.js b/modules/zone/back/methods/zone/specs/clone.spec.js index 465abdc9c..292aeb2ac 100644 --- a/modules/zone/back/methods/zone/specs/clone.spec.js +++ b/modules/zone/back/methods/zone/specs/clone.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('agency clone()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should clone a zone', async() => { const tx = await models.Zone.beginTransaction({}); diff --git a/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js b/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js index 746be502f..dc2eeb8a8 100644 --- a/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js +++ b/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('zone exclusionGeo()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); const zoneId = 1; const today = Date.vnNew(); diff --git a/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js b/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js index 39986498e..480c8b7ef 100644 --- a/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js +++ b/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js @@ -2,9 +2,9 @@ const models = require('vn-loopback/server/server').models; const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('zone toggleIsIncluded()', () => { - beforeAll(async() => { - mockLoopBackContext(); - }); + beforeAll(() => + mockLoopBackContext() + ); it('should return the created location with isIncluded true', async() => { const tx = await models.Zone.beginTransaction({}); -- 2.40.1 From d0b926b2c5176685324836649ba1ed4ed3936f38 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 12 Jun 2024 14:26:26 +0200 Subject: [PATCH 190/413] feat: refs #7490 Changes --- .../vn/procedures/duaInvoiceInBooking.sql | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index efaf29b41..1f026e96b 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -24,6 +24,16 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + UPDATE invoiceIn ii + JOIN entry e ON e.invoiceInFk = ii.id + JOIN duaEntry de ON de.entryFk = e.id + JOIN dua d ON d.id = de.duaFk + SET ii.booked = IFNULL(ii.booked, d.booked), + ii.operated = IFNULL(ii.operated, d.operated), + ii.issued = IFNULL(ii.issued, d.issued), + ii.bookEntried = IFNULL(ii.bookEntried, d.bookEntried) + WHERE d.id = vDuaFk; + SELECT ASIEN INTO vBookEntry FROM dua WHERE id = vDuaFk; IF vBookEntry IS NULL THEN @@ -65,21 +75,21 @@ BEGIN JOIN ( WITH entries AS ( SELECT e.id, de.duaFk - FROM `entry` e + FROM `entry` e JOIN duaEntry de ON de.entryFk = e.id WHERE de.duaFk = vDuaFk AND (NOT e.isBooked OR NOT e.isConfirmed) ), notBookedEntries AS ( SELECT e.id - FROM entries e - JOIN duaEntry de ON de.entryFk = e.id - JOIN dua d ON d.id = de.duaFk - WHERE d.ASIEN IS NULL) - SELECT e.id + FROM duaEntry + WHERE duaFk = vDuaFk + AND NOT customsValue + ) + SELECT e.id FROM entries e - LEFT JOIN notBookedEntries nbe ON nbe.id = e.id - WHERE nbe.id IS NULL + LEFT JOIN notBookedEntries nbe ON nbe.entryFk = e.id + WHERE nbe.entryFk IS NULL ) sub ON sub.id = e.id SET e.isBooked = TRUE, e.isConfirmed = TRUE; -- 2.40.1 From b72de3570a33419345c9969ed2d9e7435480d578 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 12 Jun 2024 14:41:35 +0200 Subject: [PATCH 191/413] refs #6897 fix redirection --- modules/entry/front/main/locale/es.yml | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 modules/entry/front/main/locale/es.yml diff --git a/modules/entry/front/main/locale/es.yml b/modules/entry/front/main/locale/es.yml new file mode 100644 index 000000000..e69de29bb -- 2.40.1 From 324d7ef7aecc40664e8808436c0224edde59bf94 Mon Sep 17 00:00:00 2001 From: Jon Date: Wed, 12 Jun 2024 14:54:43 +0200 Subject: [PATCH 192/413] refactor: refs #6436 changed test config --- back/tests.js | 8 -------- back/vn-jasmine.js | 2 -- 2 files changed, 10 deletions(-) diff --git a/back/tests.js b/back/tests.js index bfbe9e681..2527367c2 100644 --- a/back/tests.js +++ b/back/tests.js @@ -85,9 +85,6 @@ async function test() { 'modules/*/back/**/*.[sS]pec.js' ], helpers: [`back/vn-jasmine.js`], - asyncHelpers: {miHelperAsync - - } }; if (PARALLEL) { @@ -123,8 +120,3 @@ async function test() { } test(); -function miHelperAsync() { - return new Promise((resolve, reject) => { - resolve('Resultado del helper'); - }); -} diff --git a/back/vn-jasmine.js b/back/vn-jasmine.js index 1c022637e..88dc55dc0 100644 --- a/back/vn-jasmine.js +++ b/back/vn-jasmine.js @@ -45,6 +45,4 @@ module.exports = { (function init() { vnBeforeAll(); - describe.$inject = () => { - }; })(); -- 2.40.1 From 30caf79490e5ecdf3e10fe7204b62352e0efc468 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 12 Jun 2024 16:12:06 +0200 Subject: [PATCH 193/413] feat: previas con sitema de reservas refs #6861 --- ...mShelving_moveReserv.sql => itemShelvingSale_reallocate.sql} | 2 +- db/routines/vn/procedures/itemShelvingSale_setQuantity.sql | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename db/routines/vn/procedures/{itemShelving_moveReserv.sql => itemShelvingSale_reallocate.sql} (92%) diff --git a/db/routines/vn/procedures/itemShelving_moveReserv.sql b/db/routines/vn/procedures/itemShelvingSale_reallocate.sql similarity index 92% rename from db/routines/vn/procedures/itemShelving_moveReserv.sql rename to db/routines/vn/procedures/itemShelvingSale_reallocate.sql index cff8f6e92..ab898bdd4 100644 --- a/db/routines/vn/procedures/itemShelving_moveReserv.sql +++ b/db/routines/vn/procedures/itemShelvingSale_reallocate.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_moveReserv`( +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reallocate`( vItemShelvingFk INT(10), vItemFk INT(10) ) diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index aed4053bf..700821592 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -89,7 +89,7 @@ BEGIN COMMIT; IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN - CALL itemShelving_moveReserv(vItemShelvingFk, vQuantity); + CALL itemShelvingSale_reallocate(vItemShelvingFk, vQuantity); END IF; END$$ DELIMITER ; \ No newline at end of file -- 2.40.1 From d7317e4067cf187d4026744db3386b3cf329d90d Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 13 Jun 2024 07:09:48 +0200 Subject: [PATCH 194/413] hotfix: refs #7024 Modify booked entries --- db/dump/fixtures.before.sql | 12 ++++++++++++ db/routines/vn/triggers/buy_beforeUpdate.sql | 10 +++++++++- db/routines/vn/triggers/entry_beforeUpdate.sql | 15 +++++++++++++-- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 6818e7200..592297894 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3119,6 +3119,18 @@ INSERT INTO `vn`.`entryDms`(`entryFk`, `dmsFk`, `editorFk`) VALUES (1, 9, 9); +INSERT INTO vn.entryType (code,description,isInformal) + VALUES ('devaluation','Devaluation',0), + ('internal','Internal',1), + ('inventory','Inventory',1), + ('life','Life',1), + ('packaging','Packaging',0), + ('payment','Refund',0), + ('product','Product',0), + ('regularization','Regularization',1), + ('return','Return',0), + ('transport','Delivery',0); + INSERT INTO `vn`.`cmr` (id,truckPlate,observations,senderInstruccions,paymentInstruccions,specialAgreements,companyFk,addressToFk,addressFromFk,supplierFk,packagesList,merchandiseDetail,state) VALUES (1,'123456A','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',442,1,2,1,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'), (2,'123456N','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet',69,3,4,2,'Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet','Lorem ipsum dolor sit amet'), diff --git a/db/routines/vn/triggers/buy_beforeUpdate.sql b/db/routines/vn/triggers/buy_beforeUpdate.sql index dc999095b..1e2faecdc 100644 --- a/db/routines/vn/triggers/buy_beforeUpdate.sql +++ b/db/routines/vn/triggers/buy_beforeUpdate.sql @@ -13,7 +13,15 @@ trig:BEGIN LEAVE trig; END IF; - CALL entry_isEditable(OLD.entryFk); + IF NOT (NEW.entryFk <=> OLD.entryFk) OR + NOT (NEW.quantity <=> OLD.quantity) OR + NOT (NEW.buyingValue <=> OLD.buyingValue) OR + NOT (NEW.packing <=> OLD.packing) + THEN + + CALL entry_isEditable(OLD.entryFk); + END IF; + SET NEW.editorFk = account.myUser_getId(); SELECT defaultEntry INTO vDefaultEntry diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 4ce2eecc2..31c6f9bd6 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -7,10 +7,21 @@ BEGIN DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; DECLARE vTotalBuy INT; - - IF NEW.isBooked = OLD.isBooked THEN + + IF NEW.isBooked = OLD.isBooked AND ( + NOT (NEW.supplierFk <=> OLD.supplierFk) OR + NOT (NEW.dated <=> OLD.dated) OR + NOT (NEW.invoiceNumber <=> OLD.invoiceNumber) OR + NOT (NEW.travelFk <=> OLD.travelFk) OR + NOT (NEW.companyFk <=> OLD.companyFk) OR + NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) OR + NOT (NEW.invoiceAmount <=> OLD.invoiceAmount) OR + NOT (NEW.typeFk <=> OLD.typeFk) + ) THEN + CALL entry_isEditable(OLD.id); ELSE + IF NEW.isBooked THEN SELECT COUNT(*) INTO vTotalBuy FROM buy -- 2.40.1 From b5e139b7348a059436ea72998005ccd8247fe361 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 13 Jun 2024 08:43:11 +0200 Subject: [PATCH 195/413] fix: refs #7039 supplier search-panel country --- modules/supplier/front/search-panel/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/supplier/front/search-panel/index.html b/modules/supplier/front/search-panel/index.html index 161c8a98c..e67fa9083 100644 --- a/modules/supplier/front/search-panel/index.html +++ b/modules/supplier/front/search-panel/index.html @@ -35,7 +35,7 @@ label="Country" ng-model="filter.countryFk" url="countries" - show-field="country" + show-field="name" value-field="id"> -- 2.40.1 From 3c1544ac9dd79c1922599cc8232d8c024ea8e4dc Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 13 Jun 2024 09:20:43 +0200 Subject: [PATCH 196/413] refs #6897 fix es.yml --- modules/entry/front/main/locale/es.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/entry/front/main/locale/es.yml b/modules/entry/front/main/locale/es.yml index e69de29bb..de408b311 100644 --- a/modules/entry/front/main/locale/es.yml +++ b/modules/entry/front/main/locale/es.yml @@ -0,0 +1 @@ +entry: entry -- 2.40.1 From cfc5e327154fdc7e5a680395c7ccfce22bde4199 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 13 Jun 2024 13:11:50 +0200 Subject: [PATCH 197/413] feat: refs #6701 Fix error --- db/routines/vn/procedures/claimRatio_add.sql | 43 ++++++++++--------- .../11101-limeCordyline/00-firstScript.sql | 4 ++ 2 files changed, 26 insertions(+), 21 deletions(-) create mode 100644 db/versions/11101-limeCordyline/00-firstScript.sql diff --git a/db/routines/vn/procedures/claimRatio_add.sql b/db/routines/vn/procedures/claimRatio_add.sql index 7def0837f..8d94805db 100644 --- a/db/routines/vn/procedures/claimRatio_add.sql +++ b/db/routines/vn/procedures/claimRatio_add.sql @@ -44,7 +44,7 @@ BEGIN JOIN claimDestination cd ON cd.id = ce.claimDestinationFk JOIN claim c ON c.id = ce.claimFk JOIN claimState cs ON cs.id = c.claimStateFk - WHERE ce.claimDestinationFk NOT IN ('Bueno', 'Corregido') + WHERE cd.description NOT IN ('Bueno', 'Corregido') AND NOT ce.isGreuge AND cs.code = 'resolved'; @@ -86,20 +86,20 @@ BEGIN -- Recobros CREATE OR REPLACE TEMPORARY TABLE tTicketList - (PRIMARY KEY (ticketFk)) - SELECT DISTINCT s.ticketFk - FROM saleComponent sc - JOIN sale s ON sc.saleFk = s.id - JOIN ticket t ON t.id = s.ticketFk - JOIN ticketLastState ts ON ts.ticketFk = t.id - JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk - JOIN state st ON st.id = tt.stateFk - JOIN alertLevel al ON al.id = st.alertLevel - WHERE sc.componentFk = vDebtComponentType - AND NOT sc.isGreuge - AND t.shipped >= '2016-10-01' - AND t.shipped < util.VN_CURDATE() - AND al.code = 'DELIVERED'; + (PRIMARY KEY (ticketFk)) + SELECT DISTINCT s.ticketFk + FROM saleComponent sc + JOIN sale s ON sc.saleFk = s.id + JOIN ticket t ON t.id = s.ticketFk + JOIN ticketLastState ts ON ts.ticketFk = t.id + JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk + JOIN state st ON st.id = tt.stateFk + JOIN alertLevel al ON al.id = st.alertLevel + WHERE sc.componentFk = vDebtComponentType + AND NOT sc.isGreuge + AND t.shipped >= '2016-10-01' + AND t.shipped < util.VN_CURDATE() + AND al.code = 'DELIVERED'; DELETE g.* FROM greuge g @@ -133,20 +133,21 @@ BEGIN JOIN tTicketList tl ON tl.ticketFk = s.ticketFk SET sc.isGreuge = TRUE WHERE sc.componentFk = vDebtComponentType; - - INSERT INTO claimRatio( + + REPLACE claimRatio( clientFk, yearSale, claimAmount, claimingRate, priceIncreasing ) - SELECT cac.clientFk, + SELECT c.id, 12 * cac.invoiced, totalClaims, ROUND(totalClaims / (12 * cac.invoiced), 4), 0 - FROM bs.clientAnnualConsumption cac + FROM client c + LEFT JOIN bs.clientAnnualConsumption cac ON cac.clientFk = c.id LEFT JOIN ( SELECT c.clientFk, ROUND(SUM(-1 * ((c.responsibility - 1) / 4) * @@ -157,11 +158,11 @@ BEGIN JOIN claimDestination cd ON cd.id = ce.claimDestinationFk JOIN claim c ON c.id = ce.claimFk JOIN claimState cs ON cs.id = c.claimStateFk - WHERE ce.claimDestinationFk NOT IN ('Bueno', 'Corregido') + WHERE cd.description NOT IN ('Bueno', 'Corregido') AND cs.code = 'resolved' AND c.ticketCreated >= util.VN_CURDATE() - INTERVAL 1 YEAR GROUP BY c.clientFk - ) sub ON sub.clientFk = cac.clientFk; + ) sub ON sub.clientFk = c.id; -- Calculamos el porcentaje del recobro para añadirlo al precio de venta UPDATE claimRatio cr diff --git a/db/versions/11101-limeCordyline/00-firstScript.sql b/db/versions/11101-limeCordyline/00-firstScript.sql new file mode 100644 index 000000000..e9ffa1b12 --- /dev/null +++ b/db/versions/11101-limeCordyline/00-firstScript.sql @@ -0,0 +1,4 @@ +UPDATE IGNORE bs.nightTask + SET `schema` = 'vn', + `procedure` = 'claimRatio_add' + WHERE `procedure` = 'claim_ratio_routine'; -- 2.40.1 From 784bd91e041e889392ffcf16526dd2b688a1badd Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 13 Jun 2024 13:43:28 +0200 Subject: [PATCH 198/413] fix: refs #6286 update WorkerTimeControl permissions --- .../00-modifyTimeControlAcls.sql | 18 ++++++++ .../worker-time-control/getMailStates.js | 4 ++ .../resendWeeklyHourEmail.js | 4 ++ .../specs/getMailStates.spec.js | 42 +++++++++++-------- ...olMail.spec.js => updateMailState.spec.js} | 22 +++++----- ...rTimeControlMail.js => updateMailState.js} | 15 +++---- .../weeklyHourRecordEmail.js | 2 +- .../worker/back/models/worker-time-control.js | 2 +- .../back/models/worker-time-control.json | 21 +++++++--- 9 files changed, 87 insertions(+), 43 deletions(-) create mode 100644 db/versions/11100-silverGerbera/00-modifyTimeControlAcls.sql rename modules/worker/back/methods/worker-time-control/specs/{updateWorkerTimeControlMail.spec.js => updateMailState.spec.js} (82%) rename modules/worker/back/methods/worker-time-control/{updateWorkerTimeControlMail.js => updateMailState.js} (85%) diff --git a/db/versions/11100-silverGerbera/00-modifyTimeControlAcls.sql b/db/versions/11100-silverGerbera/00-modifyTimeControlAcls.sql new file mode 100644 index 000000000..473441a7e --- /dev/null +++ b/db/versions/11100-silverGerbera/00-modifyTimeControlAcls.sql @@ -0,0 +1,18 @@ +UPDATE salix.ACL + SET principalId = 'teamBoss' + WHERE property IN ('addTimeEntry', 'deleteTimeEntry', 'updateTimeEntry', 'weeklyHourRecordEmail'); + +UPDATE salix.ACL SET principalId = 'developer' WHERE property = 'sendMail'; + +UPDATE salix.ACL + SET property = 'updateMailState' + WHERE property = 'updateWorkerTimeControlMail'; + +INSERT INTO salix.ACL(model, property, accessType, permission, principalType, principalId) + VALUES + ('WorkerTimeControl', 'addTimeEntry', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'deleteTimeEntry', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'updateTimeEntry', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'weeklyHourRecordEmail', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'sendMail', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'updateMailState', 'WRITE', 'ALLOW', 'ROLE', 'hr'); \ No newline at end of file diff --git a/modules/worker/back/methods/worker-time-control/getMailStates.js b/modules/worker/back/methods/worker-time-control/getMailStates.js index 855b5adc3..d55c185a5 100644 --- a/modules/worker/back/methods/worker-time-control/getMailStates.js +++ b/modules/worker/back/methods/worker-time-control/getMailStates.js @@ -1,3 +1,5 @@ +const UserError = require('vn-loopback/util/user-error'); + module.exports = Self => { Self.remoteMethodCtx('getMailStates', { description: 'Get the states of a month about time control mail', @@ -36,6 +38,8 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); + if (!await models.Worker.isSubordinate(ctx, workerId)) throw new UserError(`You don't have enough privileges`); + const times = await models.Time.find({ fields: ['week'], where: { diff --git a/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js b/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js index 885637118..68d03f7e4 100644 --- a/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js +++ b/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js @@ -1,4 +1,5 @@ const moment = require('moment'); +const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('resendWeeklyHourEmail', { @@ -35,6 +36,9 @@ module.exports = Self => { const yearNumber = dated.getFullYear(); const weekNumber = moment(dated).isoWeek(); + if (!await models.Worker.isSubordinate(ctx, workerId) || workerId === ctx.req.accessToken.userId) + throw new UserError(`You don't have enough privileges`); + const workerTimeControlMail = await models.WorkerTimeControlMail.findOne({ where: { workerFk: workerId, diff --git a/modules/worker/back/methods/worker-time-control/specs/getMailStates.spec.js b/modules/worker/back/methods/worker-time-control/specs/getMailStates.spec.js index cbad32323..083236ec6 100644 --- a/modules/worker/back/methods/worker-time-control/specs/getMailStates.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/getMailStates.spec.js @@ -1,28 +1,36 @@ const models = require('vn-loopback/server/server').models; describe('workerTimeControl getMailStates()', () => { - const workerId = 9; - const ctx = {args: { - month: 12, - year: 2000 - }}; + const developerId = 9; + const developerBossId = 120; + const employeeId = 1; + + let ctx; + let tx; + let opts; + + beforeEach(async() => { + ctx = {req: {accessToken: {userId: developerBossId}}, args: {month: 12, year: 2000}}; + tx = await models.WorkerTimeControl.beginTransaction({}); + opts = {transaction: tx}; + }); + + afterEach(async() => await tx.rollback()); it('should get the states of a month about time control mail', async() => { - const tx = await models.WorkerTimeControl.beginTransaction({}); + const response = await models.WorkerTimeControl.getMailStates(ctx, developerId, opts); + expect(response[0].state).toEqual('REVISE'); + expect(response[1].state).toEqual('SENDED'); + expect(response[2].state).toEqual('CONFIRMED'); + }); + + it('should throw an error if they are not subordinates', async() => { + ctx.req.accessToken.userId = employeeId; try { - const options = {transaction: tx}; - - const response = await models.WorkerTimeControl.getMailStates(ctx, workerId, options); - - expect(response[0].state).toEqual('REVISE'); - expect(response[1].state).toEqual('SENDED'); - expect(response[2].state).toEqual('CONFIRMED'); - - await tx.rollback(); + await models.WorkerTimeControl.getMailStates(ctx, developerId, opts); } catch (e) { - await tx.rollback(); - throw e; + expect(e.message).toEqual('You don\'t have enough privileges'); } }); }); diff --git a/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js b/modules/worker/back/methods/worker-time-control/specs/updateMailState.spec.js similarity index 82% rename from modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js rename to modules/worker/back/methods/worker-time-control/specs/updateMailState.spec.js index 3b5b2b73f..151b6ca94 100644 --- a/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/updateMailState.spec.js @@ -1,10 +1,11 @@ const models = require('vn-loopback/server/server').models; -describe('updateWorkerTimeControlMail()', () => { +describe('updateMailState()', () => { + const developerId = 9; + const employeeId = 1; it('should update WorkerTimeControlMail if exist record', async() => { const tx = await models.WorkerTimeControlMail.beginTransaction({}); const args = { - workerId: 9, week: 50, year: 2000, state: 'CONFIRMED' @@ -15,15 +16,15 @@ describe('updateWorkerTimeControlMail()', () => { const options = {transaction: tx}; const beforeMail = await models.WorkerTimeControlMail.findOne({ where: { - workerFk: args.workerId, + workerFk: developerId, year: args.year, week: args.week, } }, options); - await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, options); + await models.WorkerTimeControl.updateMailState(ctx, developerId, options); const afterMail = await models.WorkerTimeControlMail.findOne({ where: { - workerFk: args.workerId, + workerFk: developerId, year: args.year, week: args.week, } @@ -42,7 +43,6 @@ describe('updateWorkerTimeControlMail()', () => { it('should insert WorkerTimeControlMail if exist record', async() => { const tx = await models.WorkerTimeControlMail.beginTransaction({}); const args = { - workerId: 1, week: 51, year: 2000, state: 'SENDED' @@ -53,15 +53,15 @@ describe('updateWorkerTimeControlMail()', () => { const options = {transaction: tx}; const beforeMail = await models.WorkerTimeControlMail.find({ where: { - workerFk: args.workerId, + workerFk: employeeId, year: args.year, week: args.week, } }, options); - await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, options); + await models.WorkerTimeControl.updateMailState(ctx, employeeId, options); const afterMail = await models.WorkerTimeControlMail.find({ where: { - workerFk: args.workerId, + workerFk: employeeId, year: args.year, week: args.week, } @@ -80,7 +80,7 @@ describe('updateWorkerTimeControlMail()', () => { it('should throw error if not exist any record in this week', async() => { const tx = await models.WorkerTimeControlMail.beginTransaction({}); const ctx = {args: { - workerId: 1, + workerId: employeeId, week: 1, year: 0, state: 'SENDED' @@ -89,7 +89,7 @@ describe('updateWorkerTimeControlMail()', () => { let error; try { const options = {transaction: tx}; - await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, options); + await models.WorkerTimeControl.updateMailState(ctx, employeeId, options); await tx.rollback(); } catch (e) { diff --git a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js b/modules/worker/back/methods/worker-time-control/updateMailState.js similarity index 85% rename from modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js rename to modules/worker/back/methods/worker-time-control/updateMailState.js index 3fd743fe3..c3bacaac0 100644 --- a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js +++ b/modules/worker/back/methods/worker-time-control/updateMailState.js @@ -1,12 +1,13 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethodCtx('updateWorkerTimeControlMail', { + Self.remoteMethodCtx('updateMailState', { description: 'Updates the state of WorkerTimeControlMail', accessType: 'WRITE', accepts: [{ - arg: 'workerId', + arg: 'id', type: 'number', - required: true + description: 'The worker id', + http: {source: 'path'} }, { arg: 'year', @@ -32,12 +33,12 @@ module.exports = Self => { root: true }, http: { - path: `/updateWorkerTimeControlMail`, + path: `/:id/updateMailState`, verb: 'POST' } }); - Self.updateWorkerTimeControlMail = async(ctx, options) => { + Self.updateMailState = async(ctx, id, options) => { const models = Self.app.models; const args = ctx.args; const myOptions = {}; @@ -59,14 +60,14 @@ module.exports = Self => { { year: args.year, week: args.week, - workerFk: args.workerId + workerFk: id }, { state: args.state, reason: args.reason, year: args.year, week: args.week, - workerFk: args.workerId + workerFk: id }, myOptions); diff --git a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js index 53bc8d022..f19ab17e1 100644 --- a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js +++ b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js @@ -61,7 +61,7 @@ module.exports = Self => { const url = `${salix.url}worker/${args.workerId}/time-control?timestamp=${timestamp}`; ctx.args.url = url; - await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, myOptions); + await models.WorkerTimeControl.updateMailState(ctx, ctx.workerId, myOptions); return Self.sendTemplate(ctx, 'weekly-hour-record'); }; diff --git a/modules/worker/back/models/worker-time-control.js b/modules/worker/back/models/worker-time-control.js index 1457c7a46..92f1bacf0 100644 --- a/modules/worker/back/models/worker-time-control.js +++ b/modules/worker/back/models/worker-time-control.js @@ -6,7 +6,7 @@ module.exports = Self => { require('../methods/worker-time-control/deleteTimeEntry')(Self); require('../methods/worker-time-control/updateTimeEntry')(Self); require('../methods/worker-time-control/sendMail')(Self); - require('../methods/worker-time-control/updateWorkerTimeControlMail')(Self); + require('../methods/worker-time-control/updateMailState')(Self); require('../methods/worker-time-control/weeklyHourRecordEmail')(Self); require('../methods/worker-time-control/getMailStates')(Self); require('../methods/worker-time-control/resendWeeklyHourEmail')(Self); diff --git a/modules/worker/back/models/worker-time-control.json b/modules/worker/back/models/worker-time-control.json index e2b74875a..3d408c18f 100644 --- a/modules/worker/back/models/worker-time-control.json +++ b/modules/worker/back/models/worker-time-control.json @@ -36,15 +36,24 @@ "model": "VnUser", "foreignKey": "userFk" }, - "worker": { - "type": "hasOne", - "model": "Worker", - "foreignKey": "id" + "worker": { + "type": "hasOne", + "model": "Worker", + "foreignKey": "id" }, "warehouse": { "type": "belongsTo", "model": "Warehouse", "foreignKey": "warehouseFk" } - } -} + }, + "acls": [ + { + "property": "updateMailState", + "accessType": "WRITE", + "permission": "ALLOW", + "principalType": "ROLE", + "principalId": "$owner" + } + ] +} \ No newline at end of file -- 2.40.1 From c2e4e187d689333e43b353269707383937bf93b8 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 13 Jun 2024 14:21:59 +0200 Subject: [PATCH 199/413] feat itemShelvingSale refs #6861 --- db/routines/vn/procedures/itemShelvingSale_setQuantity.sql | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index 700821592..6c556f1ff 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -70,7 +70,7 @@ BEGIN FROM itemShelvingSale WHERE saleFk = vSaleFk; - IF vRemainingQuantity = 0 THEN + IF vRemainingQuantity = 0 AND NOT vIsItemShelvingSaleEmpty THEN CALL saleTracking_new( vSaleFk, TRUE, @@ -89,7 +89,9 @@ BEGIN COMMIT; IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN - CALL itemShelvingSale_reallocate(vItemShelvingFk, vQuantity); + INSERT INTO itemShelvingSaleReserv (saleFk) + SELECT vSaleFk; + CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk); END IF; END$$ DELIMITER ; \ No newline at end of file -- 2.40.1 From 615fd3e97bfbc9f38a8fc82e1f1d2473ec6284d3 Mon Sep 17 00:00:00 2001 From: ivanm Date: Thu, 13 Jun 2024 15:10:04 +0200 Subject: [PATCH 200/413] refs #7530 delete trigger deviceProductionConfig_afterUpdate --- .../triggers/deviceProductionConfig_afterUpdate.sql | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 db/routines/vn/triggers/deviceProductionConfig_afterUpdate.sql diff --git a/db/routines/vn/triggers/deviceProductionConfig_afterUpdate.sql b/db/routines/vn/triggers/deviceProductionConfig_afterUpdate.sql deleted file mode 100644 index 98e4f844f..000000000 --- a/db/routines/vn/triggers/deviceProductionConfig_afterUpdate.sql +++ /dev/null @@ -1,13 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`deviceProductionConfig_afterUpdate` - AFTER UPDATE ON `deviceProductionConfig` - FOR EACH ROW -BEGIN - IF NEW.isAllUsersAllowed = 1 OR NEW.isAllUsersAllowed = -1 THEN - SET @username := (SELECT account.myUser_getName()); - INSERT INTO vn.mail (receiver, subject, body) - VALUES ('cau@verdnatura.es', 'Se ha activado la autenticación sin restricciones en la app', - CONCAT('El usuario ', @username,' ha habilitado la opción para que todos los usuarios puedan acceder a la app sin restricciones')); - END IF; -END$$ -DELIMITER ; -- 2.40.1 From 61a588b57c35264508078ca61d5cc4bd04675678 Mon Sep 17 00:00:00 2001 From: Jon Date: Fri, 14 Jun 2024 08:39:57 +0200 Subject: [PATCH 201/413] refactor: refs #6436 fixed test --- back/methods/collection/spec/getSales.spec.js | 2 +- .../collection/spec/getTickets.spec.js | 2 +- .../collection/spec/setSaleQuantity.spec.js | 5 +- .../specs/getStarredModules.spec.js | 2 +- .../starred-module/specs/setPosition.spec.js | 2 +- .../specs/toggleStarredModule.spec.js | 2 +- .../user-config/specs/getUserConfig.spec.js | 2 +- back/models/specs/mailAliasAccount.spec.js | 5 +- back/vn-jasmine.js | 50 ++++++++------- .../methods/application/spec/execute.spec.js | 2 +- .../methods/vn-model/specs/crud.spec.js | 5 +- .../vn-model/specs/rewriteDbError.spec.js | 5 +- .../back/methods/claim/specs/filter.spec.js | 2 +- .../claim/specs/regularizeClaim.spec.js | 13 +--- .../methods/claim/specs/updateClaim.spec.js | 3 +- .../claim/specs/updateClaimAction.spec.js | 5 +- .../client/specs/addressesPropagateRe.spec.js | 5 +- .../client/specs/createAddress.spec.js | 5 +- .../client/specs/createWithUser.spec.js | 6 +- .../back/methods/client/specs/getCard.spec.js | 2 +- .../back/methods/client/specs/getDebt.spec.js | 2 +- .../back/methods/client/specs/sendSms.spec.js | 2 +- .../back/methods/client/specs/summary.spec.js | 2 +- .../client/specs/updateAddress.spec.js | 6 +- .../client/back/models/specs/address.spec.js | 5 +- .../entry/specs/addFromPackaging.spec.js | 5 +- .../entry/specs/editLatestBuys.spec.js | 5 +- .../entry/specs/importBuysPreview.spec.js | 5 +- .../invoice-in-due-day/specs/new.spec.js | 5 +- .../methods/invoice-in/specs/clone.spec.js | 2 +- .../invoice-in/specs/corrective.spec.js | 2 +- .../methods/invoiceOut/specs/book.spec.js | 2 +- .../specs/upsertFixedPrice.spec.js | 3 +- .../specs/getAlternative.spec.js | 5 +- .../item-shelving/specs/upsertItem.spec.js | 2 +- .../back/methods/item/specs/clone.spec.js | 5 +- .../methods/item/specs/getBalance.spec.js | 2 +- .../item/back/methods/item/specs/new.spec.js | 2 +- .../methods/item/specs/regularize.spec.js | 6 +- .../methods/item/specs/updateTaxes.spec.js | 5 +- .../back/methods/tag/specs/onSubmit.spec.js | 5 +- .../order-row/specs/addToOrder.spec.js | 2 +- .../back/methods/order/specs/filter.spec.js | 5 +- .../back/methods/order/specs/new.spec.js | 2 +- .../methods/order/specs/newFromTicket.spec.js | 2 +- .../agency-term/specs/createInvoiceIn.spec.js | 2 +- .../back/methods/route/specs/clone.spec.js | 5 +- .../methods/route/specs/guessPriority.spec.js | 2 +- .../route/specs/updateWorkCenter.spec.js | 5 +- .../supplier/specs/consumption.spec.js | 2 +- .../back/models/specs/supplier.spec.js | 3 +- .../specs/addExpeditionState.spec.js | 2 +- .../specs/deleteExpeditions.spec.js | 2 +- .../expedition/specs/moveExpeditions.spec.js | 2 +- .../back/methods/sale/specs/canEdit.spec.js | 5 +- .../back/methods/sale/specs/clone.spec.js | 16 +---- .../methods/sale/specs/deleteSales.spec.js | 21 +------ .../sale/specs/recalculatePrice.spec.js | 2 +- .../back/methods/sale/specs/reserve.spec.js | 5 +- .../methods/sale/specs/updateConcept.spec.js | 2 +- .../ticket-request/specs/confirm.spec.js | 6 +- .../methods/ticket-request/specs/deny.spec.js | 20 +----- .../back/methods/ticket/specs/clone.spec.js | 2 +- .../ticket/specs/componentUpdate.spec.js | 63 +++---------------- .../back/methods/ticket/specs/filter.spec.js | 51 ++++++++++----- .../ticket/specs/getTicketsAdvance.spec.js | 11 ++-- .../ticket/specs/getTicketsFuture.spec.js | 25 ++++---- .../ticket/specs/isEditableOrThrow.spec.js | 2 +- .../back/methods/ticket/specs/merge.spec.js | 6 +- .../specs/recalculateComponents.spec.js | 2 +- .../back/methods/ticket/specs/sendSms.spec.js | 2 +- .../methods/ticket/specs/setDeleted.spec.js | 42 +------------ .../back/methods/ticket/specs/state.spec.js | 22 +++---- .../ticket/specs/transferClient.spec.js | 2 +- .../ticket/specs/updateDiscount.spec.js | 50 ++------------- .../models/specs/ticket-packaging.spec.js | 5 +- modules/ticket/back/models/ticket-request.js | 2 +- .../specs/createThermograph.spec.js | 2 +- .../travel/specs/createThermograph.spec.js | 5 +- .../methods/calendar/specs/absences.spec.js | 2 +- .../department/specs/getLeaves.spec.js | 2 +- .../worker/specs/createAbsence.spec.js | 3 +- .../worker/specs/mySubordinates.spec.js | 2 +- .../back/methods/worker/specs/new.spec.js | 5 +- .../specs/getAgenciesWithWarehouse.spec.js | 2 +- .../methods/agency/specs/landsThatDay.spec.js | 2 +- .../back/methods/zone/specs/clone.spec.js | 5 +- .../methods/zone/specs/exclusionGeo.spec.js | 5 +- .../back/methods/zone/specs/getEvents.spec.js | 2 +- .../back/methods/zone/specs/getLeaves.spec.js | 2 +- .../zone/specs/getUpcomingDeliveries.spec.js | 2 +- .../zone/specs/toggleIsIncluded.spec.js | 5 +- 92 files changed, 197 insertions(+), 452 deletions(-) diff --git a/back/methods/collection/spec/getSales.spec.js b/back/methods/collection/spec/getSales.spec.js index f276d07d0..520657ec1 100644 --- a/back/methods/collection/spec/getSales.spec.js +++ b/back/methods/collection/spec/getSales.spec.js @@ -4,7 +4,7 @@ describe('collection getSales()', () => { const collectionOrTicketFk = 999999; const print = true; const source = 'CHECKER'; - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should return a collection with tickets, placements and barcodes settled correctly', async() => { const tx = await models.Collection.beginTransaction({}); diff --git a/back/methods/collection/spec/getTickets.spec.js b/back/methods/collection/spec/getTickets.spec.js index c066ead8c..646f44223 100644 --- a/back/methods/collection/spec/getTickets.spec.js +++ b/back/methods/collection/spec/getTickets.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('collection getTickets()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should get tickets, sales and barcodes from collection', async() => { const tx = await models.Collection.beginTransaction({}); diff --git a/back/methods/collection/spec/setSaleQuantity.spec.js b/back/methods/collection/spec/setSaleQuantity.spec.js index e26e25115..00ddae0fe 100644 --- a/back/methods/collection/spec/setSaleQuantity.spec.js +++ b/back/methods/collection/spec/setSaleQuantity.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('setSaleQuantity()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should change quantity sale', async() => { const tx = await models.Ticket.beginTransaction({}); diff --git a/back/methods/starred-module/specs/getStarredModules.spec.js b/back/methods/starred-module/specs/getStarredModules.spec.js index cce353f93..afe1dd9c2 100644 --- a/back/methods/starred-module/specs/getStarredModules.spec.js +++ b/back/methods/starred-module/specs/getStarredModules.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('getStarredModules()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it(`should return the starred modules for a given user`, async() => { const newStarred = await models.StarredModule.create({workerFk: 9, moduleFk: 'customer', position: 1}); diff --git a/back/methods/starred-module/specs/setPosition.spec.js b/back/methods/starred-module/specs/setPosition.spec.js index 495bc8384..c99206e56 100644 --- a/back/methods/starred-module/specs/setPosition.spec.js +++ b/back/methods/starred-module/specs/setPosition.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('setPosition()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should increase the orders module position by replacing it with clients and vice versa', async() => { const tx = await models.StarredModule.beginTransaction({}); diff --git a/back/methods/starred-module/specs/toggleStarredModule.spec.js b/back/methods/starred-module/specs/toggleStarredModule.spec.js index d5a5c8ab3..d506abc33 100644 --- a/back/methods/starred-module/specs/toggleStarredModule.spec.js +++ b/back/methods/starred-module/specs/toggleStarredModule.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('toggleStarredModule()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should create a new starred module and then remove it by calling the method again with same args', async() => { const starredModule = await models.StarredModule.toggleStarredModule(ctx, 'order'); diff --git a/back/methods/user-config/specs/getUserConfig.spec.js b/back/methods/user-config/specs/getUserConfig.spec.js index c27018b07..bbfb98ef7 100644 --- a/back/methods/user-config/specs/getUserConfig.spec.js +++ b/back/methods/user-config/specs/getUserConfig.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('userConfig getUserConfig()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it(`should return the configuration data of a given user`, async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; diff --git a/back/models/specs/mailAliasAccount.spec.js b/back/models/specs/mailAliasAccount.spec.js index 8f0278a50..0f4cbdbb1 100644 --- a/back/models/specs/mailAliasAccount.spec.js +++ b/back/models/specs/mailAliasAccount.spec.js @@ -1,12 +1,13 @@ const models = require('vn-loopback/server/server').models; describe('loopback model MailAliasAccount', () => { + const ctx = beforeAll.getCtx(); it('should add a mail Alias', async() => { const tx = await models.MailAliasAccount.beginTransaction({}); let error; try { - const options = {transaction: tx, accessToken: {userId: 9}}; + const options = {transaction: tx, ctx}; await models.MailAliasAccount.create({mailAlias: 2, account: 5}, options); await tx.rollback(); @@ -23,7 +24,7 @@ describe('loopback model MailAliasAccount', () => { let error; try { - const options = {transaction: tx, accessToken: {userId: 9}}; + const options = {transaction: tx, ctx}; await models.MailAliasAccount.create({mailAlias: 3, account: 5}, options); await tx.rollback(); diff --git a/back/vn-jasmine.js b/back/vn-jasmine.js index 88dc55dc0..c2d8a497c 100644 --- a/back/vn-jasmine.js +++ b/back/vn-jasmine.js @@ -1,41 +1,47 @@ const LoopBackContext = require('loopback-context'); -const DEFAULT_ACCESS_TOKEN = {accessToken: {userId: 9}}; +const getAccessToken = (userId = 9) => { + return {accessToken: {userId}}; +}; const DEFAULT_HEADERS = {headers: {origin: 'http://localhost'}}; -const DEFAULT_BEFORE_ALL = { - ctx: { +const default_before_all = userId => { + return { req: { - ...DEFAULT_ACCESS_TOKEN, - ...DEFAULT_HEADERS + ...getAccessToken(userId), + ...DEFAULT_HEADERS, + ...{__: value => value} }, args: {} - } + }; }; -const DEFAULT_LOOPBACK_CTX = { - ...DEFAULT_ACCESS_TOKEN, - http: { - req: { - ...DEFAULT_HEADERS - } - }, - args: {} +const default_loopback_ctx = userId => { + return { + ...getAccessToken(userId), + ...default_before_all(userId), + http: { + ...default_before_all(userId) + }, + args: {} + }; }; -function vnBeforeAll(value = DEFAULT_BEFORE_ALL) { - Object.assign(beforeAll, value); +function vnBeforeAll() { + Object.assign(beforeAll, {getCtx: default_before_all}); + Object.assign(beforeAll, {mockLoopBackContext}); } -function mockBeforeAll(value = DEFAULT_BEFORE_ALL) { +function mockBeforeAll(value = default_before_all) { const origin = beforeAll.ctx; Object.assign(origin, value); return origin; } -const mockLoopBackContext = (value = DEFAULT_LOOPBACK_CTX) => { - const activeCtx = value; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx +const mockLoopBackContext = userId => { + const activeCtx = default_loopback_ctx(userId); + beforeAll(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); }); return activeCtx; }; diff --git a/loopback/common/methods/application/spec/execute.spec.js b/loopback/common/methods/application/spec/execute.spec.js index b697dbef9..ca4efd9cc 100644 --- a/loopback/common/methods/application/spec/execute.spec.js +++ b/loopback/common/methods/application/spec/execute.spec.js @@ -4,7 +4,7 @@ describe('Application execute()/executeProc()/executeFunc()', () => { const userWithoutPrivileges = 1; const userWithInheritedPrivileges = 120; let tx; - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); beforeEach(async() => { tx = await models.Application.beginTransaction({}); diff --git a/loopback/common/methods/vn-model/specs/crud.spec.js b/loopback/common/methods/vn-model/specs/crud.spec.js index a8923aed8..28b256ad8 100644 --- a/loopback/common/methods/vn-model/specs/crud.spec.js +++ b/loopback/common/methods/vn-model/specs/crud.spec.js @@ -1,10 +1,7 @@ const app = require('vn-loopback/server/server'); -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Model crud()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); let insertId; const barcodeModel = app.models.ItemBarcode; diff --git a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js index d89508383..84c0784c9 100644 --- a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js +++ b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Model rewriteDbError()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should extend rewriteDbError properties to any model passed', () => { const exampleModel = models.ItemTag; diff --git a/modules/claim/back/methods/claim/specs/filter.spec.js b/modules/claim/back/methods/claim/specs/filter.spec.js index b55e554b9..1ef808e9d 100644 --- a/modules/claim/back/methods/claim/specs/filter.spec.js +++ b/modules/claim/back/methods/claim/specs/filter.spec.js @@ -2,7 +2,7 @@ const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models; describe('claim filter()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should return 1 result filtering by id', async() => { const tx = await app.models.Claim.beginTransaction({}); diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 879979829..55d76ed7a 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -1,18 +1,11 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('claim regularizeClaim()', () => { const userId = 18; - const ctx = { - req: { - accessToken: {userId: userId}, - headers: {origin: 'http://localhost'} - } - }; + const ctx = beforeAll.mockLoopBackContext(userId); ctx.req.__ = (value, params) => { return params.nickname; }; - const chatModel = models.Chat; const claimId = 1; const ticketId = 1; @@ -40,10 +33,6 @@ describe('claim regularizeClaim()', () => { return await models.ClaimEnd.create(claimEnds, options); } - beforeAll(() => - mockLoopBackContext() - ); - it('should send a chat message with value "Trash" and then change claim state to resolved', async() => { const tx = await models.Claim.beginTransaction({}); diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index 5c8f08132..e1eec59d1 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -1,11 +1,10 @@ const app = require('vn-loopback/server/server'); -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); const i18n = require('i18n'); describe('Update Claim', () => { let url; let claimStatesMap = {}; + beforeAll.mockLoopBackContext(); beforeAll(async() => { - mockLoopBackContext(); const claimStates = await app.models.ClaimState.find(); claimStatesMap = claimStates.reduce((acc, state) => ({...acc, [state.code]: state.id}), {}); }); diff --git a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js index 506c80abb..bc081ed08 100644 --- a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js @@ -1,10 +1,7 @@ const app = require('vn-loopback/server/server'); -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Update Claim', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); const newDate = Date.vnNew(); const original = { ticketFk: 3, diff --git a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js index be2732bdb..1a186f93c 100644 --- a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js +++ b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Client addressesPropagateRe', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should propagate the isEqualizated on both addresses of Mr Wayne' + ' and set hasToInvoiceByAddress to false', async() => { diff --git a/modules/client/back/methods/client/specs/createAddress.spec.js b/modules/client/back/methods/client/specs/createAddress.spec.js index 9c827a40e..f4901ff93 100644 --- a/modules/client/back/methods/client/specs/createAddress.spec.js +++ b/modules/client/back/methods/client/specs/createAddress.spec.js @@ -1,5 +1,4 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Address createAddress', () => { const clientFk = 1101; @@ -7,9 +6,7 @@ describe('Address createAddress', () => { const incotermsFk = 'FAS'; const customAgentOneId = 1; - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should throw a non uee member error if no incoterms is defined', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 47f2d34ce..5b1ff5da9 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -1,6 +1,4 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); - describe('Client Create', () => { const newAccount = { userName: 'deadpool', @@ -16,9 +14,7 @@ describe('Client Create', () => { const newAccountWithoutEmail = JSON.parse(JSON.stringify(newAccount)); delete newAccountWithoutEmail.email; - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it(`should not find deadpool as he's not created yet`, async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/getCard.spec.js b/modules/client/back/methods/client/specs/getCard.spec.js index 1082b4009..49e5ed5a4 100644 --- a/modules/client/back/methods/client/specs/getCard.spec.js +++ b/modules/client/back/methods/client/specs/getCard.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('Client getCard()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should receive a formated card of Bruce Wayne', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/getDebt.spec.js b/modules/client/back/methods/client/specs/getDebt.spec.js index 7fc76ee94..d89d671a3 100644 --- a/modules/client/back/methods/client/specs/getDebt.spec.js +++ b/modules/client/back/methods/client/specs/getDebt.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('client getDebt()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should return the client debt', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/sendSms.spec.js b/modules/client/back/methods/client/specs/sendSms.spec.js index b6cb55062..bba9f83ce 100644 --- a/modules/client/back/methods/client/specs/sendSms.spec.js +++ b/modules/client/back/methods/client/specs/sendSms.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('client sendSms()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should now send a message and log it', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/summary.spec.js b/modules/client/back/methods/client/specs/summary.spec.js index d15d183c6..fe2af8028 100644 --- a/modules/client/back/methods/client/specs/summary.spec.js +++ b/modules/client/back/methods/client/specs/summary.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('client summary()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should return a summary object containing data', async() => { const clientId = 1101; const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/updateAddress.spec.js b/modules/client/back/methods/client/specs/updateAddress.spec.js index d0c5e4d88..68981f8b7 100644 --- a/modules/client/back/methods/client/specs/updateAddress.spec.js +++ b/modules/client/back/methods/client/specs/updateAddress.spec.js @@ -1,6 +1,4 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); - describe('Address updateAddress', () => { const clientId = 1101; const addressId = 1; @@ -14,9 +12,7 @@ describe('Address updateAddress', () => { } }; - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should throw the non uee member error if no incoterms is defined', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/models/specs/address.spec.js b/modules/client/back/models/specs/address.spec.js index d390d045c..3eae1b1bf 100644 --- a/modules/client/back/models/specs/address.spec.js +++ b/modules/client/back/models/specs/address.spec.js @@ -1,13 +1,10 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('loopback model address', () => { let createdAddressId; const clientId = 1101; - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); afterAll(async() => { const client = await models.Client.findById(clientId); diff --git a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js index 865e59bca..0c8d2729b 100644 --- a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js +++ b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js @@ -1,5 +1,4 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('entry addFromPackaging()', () => { const supplier = 442; @@ -7,9 +6,7 @@ describe('entry addFromPackaging()', () => { const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should create an incoming travel', async() => { const ctx = {accessToken: {userId: 49}, args: {isTravelReception: true, supplier}}; diff --git a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js index 04c38078b..f319c112a 100644 --- a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Buy editLatestsBuys()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should change the value of a given column for the selected buys', async() => { const tx = await models.Buy.beginTransaction({}); diff --git a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js index 57adaf2dd..fb3268901 100644 --- a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js +++ b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js @@ -1,11 +1,8 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('entry importBuysPreview()', () => { const entryId = 1; - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should return the buys with the calculated packagingFk', async() => { const tx = await models.Entry.beginTransaction({}); diff --git a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js index 9a996d103..2105cd9c0 100644 --- a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('invoiceInDueDay new()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should correctly create a new due day', async() => { const userId = 9; diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js index 9fef506d4..cf1e0ac2d 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('invoiceIn clone()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); let options; let tx; diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js index ff547f1c8..c63f02439 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('invoiceIn corrective()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); let options; let tx; diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index 29e21a27c..bebc9a8e4 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('invoiceOut book()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); const invoiceOutId = 5; it('should update the booked property', async() => { diff --git a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js index 36a15849c..335159de5 100644 --- a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js +++ b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js @@ -1,14 +1,13 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('upsertFixedPrice()', () => { const now = Date.vnNew(); const fixedPriceId = 1; let originalFixedPrice; + beforeAll.mockLoopBackContext(); beforeAll(async() => { originalFixedPrice = await models.FixedPrice.findById(fixedPriceId); - mockLoopBackContext(); }); it(`should toggle the hasMinPrice boolean if there's a minPrice and update the rest of the data`, async() => { 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 006842eca..3b0a65e61 100644 --- a/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js @@ -1,10 +1,7 @@ const {models} = require('vn-loopback/server/server'); -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('itemShelving getAlternative()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should return a list of items without alternatives', async() => { const shelvingFk = 'HEJ'; diff --git a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js index 18a8a6e0e..f01cb985d 100644 --- a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js +++ b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js @@ -3,7 +3,7 @@ const {models} = require('vn-loopback/server/server'); describe('ItemShelving upsertItem()', () => { const warehouseFk = 1; - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); let options; let tx; diff --git a/modules/item/back/methods/item/specs/clone.spec.js b/modules/item/back/methods/item/specs/clone.spec.js index e252c910c..5bb5fe560 100644 --- a/modules/item/back/methods/item/specs/clone.spec.js +++ b/modules/item/back/methods/item/specs/clone.spec.js @@ -1,11 +1,8 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('item clone()', () => { let nextItemId; - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); beforeEach(async() => { let query = `SELECT i1.id + 1 as id FROM vn.item i1 diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js index d1bb65b75..bae0997bb 100644 --- a/modules/item/back/methods/item/specs/getBalance.spec.js +++ b/modules/item/back/methods/item/specs/getBalance.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('item getBalance()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should return the balance lines of a client type loses in which one has highlighted true', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js index 5611b28ab..11570ffb9 100644 --- a/modules/item/back/methods/item/specs/new.spec.js +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('item new()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should create a new item, adding the name as a tag', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/methods/item/specs/regularize.spec.js b/modules/item/back/methods/item/specs/regularize.spec.js index 097d61d5c..4e94d5d6d 100644 --- a/modules/item/back/methods/item/specs/regularize.spec.js +++ b/modules/item/back/methods/item/specs/regularize.spec.js @@ -1,17 +1,13 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('regularize()', () => { - beforeAll(() => - mockLoopBackContext() - ); + const ctx = beforeAll.mockLoopBackContext(18); it('should create a new ticket and add a line', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const ctx = {req: {accessToken: {userId: 18}}}; const itemId = 1; const warehouseId = 1; const quantity = 11; diff --git a/modules/item/back/methods/item/specs/updateTaxes.spec.js b/modules/item/back/methods/item/specs/updateTaxes.spec.js index 3d0f1ce33..828a5fec9 100644 --- a/modules/item/back/methods/item/specs/updateTaxes.spec.js +++ b/modules/item/back/methods/item/specs/updateTaxes.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('item updateTaxes()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should throw an error if the taxClassFk is blank', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/methods/tag/specs/onSubmit.spec.js b/modules/item/back/methods/tag/specs/onSubmit.spec.js index be77b0248..e92a5fcdf 100644 --- a/modules/item/back/methods/tag/specs/onSubmit.spec.js +++ b/modules/item/back/methods/tag/specs/onSubmit.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('tag onSubmit()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should delete a tag', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/order/back/methods/order-row/specs/addToOrder.spec.js b/modules/order/back/methods/order-row/specs/addToOrder.spec.js index 327c86db0..2bc78ffef 100644 --- a/modules/order/back/methods/order-row/specs/addToOrder.spec.js +++ b/modules/order/back/methods/order-row/specs/addToOrder.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order addToOrder()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); const orderId = 8; it('should add a row to a given order', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/back/methods/order/specs/filter.spec.js b/modules/order/back/methods/order/specs/filter.spec.js index a2ec88577..9e644bb2d 100644 --- a/modules/order/back/methods/order/specs/filter.spec.js +++ b/modules/order/back/methods/order/specs/filter.spec.js @@ -1,10 +1,7 @@ -const {mockLoopBackContext} = require('../../../../../../back/vn-jasmine'); - const models = require('vn-loopback/server/server').models; describe('order filter()', () => { - let ctx; - beforeAll(() => ctx = mockLoopBackContext()); + const ctx = beforeAll.getCtx(); it('should call the filter method with a basic search', async() => { const myCtx = Object.assign({}, ctx); diff --git a/modules/order/back/methods/order/specs/new.spec.js b/modules/order/back/methods/order/specs/new.spec.js index 6ed1fa4ae..779de6ada 100644 --- a/modules/order/back/methods/order/specs/new.spec.js +++ b/modules/order/back/methods/order/specs/new.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; const UserError = require('vn-loopback/util/user-error'); describe('order new()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should throw an error if the client isnt active', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/back/methods/order/specs/newFromTicket.spec.js b/modules/order/back/methods/order/specs/newFromTicket.spec.js index a592877cf..d927a0338 100644 --- a/modules/order/back/methods/order/specs/newFromTicket.spec.js +++ b/modules/order/back/methods/order/specs/newFromTicket.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order newFromTicket()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should create a new order from an existing ticket', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js b/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js index dbe9d0e1e..24ffa9cd7 100644 --- a/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js +++ b/modules/route/back/methods/agency-term/specs/createInvoiceIn.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('AgencyTerm createInvoiceIn()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); const rows = [ { routeFk: 2, diff --git a/modules/route/back/methods/route/specs/clone.spec.js b/modules/route/back/methods/route/specs/clone.spec.js index b9ad7751c..a064e35ba 100644 --- a/modules/route/back/methods/route/specs/clone.spec.js +++ b/modules/route/back/methods/route/specs/clone.spec.js @@ -1,10 +1,7 @@ const app = require('vn-loopback/server/server'); -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('route clone()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); const createdDate = Date.vnNew(); it('should throw an error if the amount of ids pased to the clone function do no match the database', async() => { diff --git a/modules/route/back/methods/route/specs/guessPriority.spec.js b/modules/route/back/methods/route/specs/guessPriority.spec.js index 34fa510e1..522801f43 100644 --- a/modules/route/back/methods/route/specs/guessPriority.spec.js +++ b/modules/route/back/methods/route/specs/guessPriority.spec.js @@ -3,7 +3,7 @@ const app = require('vn-loopback/server/server'); describe('route guessPriority()', () => { const targetRouteId = 7; let routeTicketsToRestore; - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); afterAll(async() => { let restoreFixtures = []; diff --git a/modules/route/back/methods/route/specs/updateWorkCenter.spec.js b/modules/route/back/methods/route/specs/updateWorkCenter.spec.js index 4d5fbcbdc..b4b9253f8 100644 --- a/modules/route/back/methods/route/specs/updateWorkCenter.spec.js +++ b/modules/route/back/methods/route/specs/updateWorkCenter.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('route updateWorkCenter()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); const routeId = 1; it('should set the commission work center if the worker has workCenter', async() => { diff --git a/modules/supplier/back/methods/supplier/specs/consumption.spec.js b/modules/supplier/back/methods/supplier/specs/consumption.spec.js index 0b4d6f82c..4c729f64a 100644 --- a/modules/supplier/back/methods/supplier/specs/consumption.spec.js +++ b/modules/supplier/back/methods/supplier/specs/consumption.spec.js @@ -1,8 +1,8 @@ const app = require('vn-loopback/server/server'); describe('supplier consumption() filter', () => { + const ctx = beforeAll.getCtx(); it('should return a list of entries from the supplier 2', async() => { - const ctx = {req: {accessToken: {userId: 9}}, args: {}}; const filter = { where: { supplierFk: 2 diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index 2c0d1910f..4e9bd3253 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -1,14 +1,13 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('loopback model Supplier', () => { let supplierOne; let supplierTwo; + beforeAll.mockLoopBackContext(); beforeAll(async() => { supplierOne = await models.Supplier.findById(1); supplierTwo = await models.Supplier.findById(442); - mockLoopBackContext(); }); describe('payMethodFk', () => { diff --git a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js index ce9049a95..747352286 100644 --- a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js +++ b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('expeditionState addExpeditionState()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should update the expedition states', async() => { const tx = await models.ExpeditionState.beginTransaction({}); try { diff --git a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js index 4134b28b8..4b17f98b7 100644 --- a/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js +++ b/modules/ticket/back/methods/expedition/specs/deleteExpeditions.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('ticket deleteExpeditions()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should delete the selected expeditions', async() => { const tx = await models.Expedition.beginTransaction({}); diff --git a/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js index 621992c5d..c1c7c2c12 100644 --- a/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js +++ b/modules/ticket/back/methods/expedition/specs/moveExpeditions.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('ticket moveExpeditions()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should move the selected expeditions to new ticket', async() => { const tx = await models.Expedition.beginTransaction({}); diff --git a/modules/ticket/back/methods/sale/specs/canEdit.spec.js b/modules/ticket/back/methods/sale/specs/canEdit.spec.js index 668b1c273..168bd28fb 100644 --- a/modules/ticket/back/methods/sale/specs/canEdit.spec.js +++ b/modules/ticket/back/methods/sale/specs/canEdit.spec.js @@ -1,11 +1,8 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale canEdit()', () => { const employeeId = 1; - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); describe('sale not exists', () => { it('should return error if sale not exists', async() => { diff --git a/modules/ticket/back/methods/sale/specs/clone.spec.js b/modules/ticket/back/methods/sale/specs/clone.spec.js index 8767c2857..5b0dc84a7 100644 --- a/modules/ticket/back/methods/sale/specs/clone.spec.js +++ b/modules/ticket/back/methods/sale/specs/clone.spec.js @@ -1,23 +1,11 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); - describe('Ticket cloning - clone function', () => { - let ctx; + const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.Sale.beginTransaction({}); options.transaction = tx; diff --git a/modules/ticket/back/methods/sale/specs/deleteSales.spec.js b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js index 8dc261b13..ba14310a1 100644 --- a/modules/ticket/back/methods/sale/specs/deleteSales.spec.js +++ b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js @@ -1,10 +1,8 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale deleteSales()', () => { - beforeAll(() => - mockLoopBackContext() - ); + const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); it('should throw an error if the ticket of the given sales is not editable', async() => { const tx = await models.Sale.beginTransaction({}); @@ -13,14 +11,6 @@ describe('sale deleteSales()', () => { try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - const sales = [{id: 1, instance: 0}, {id: 2, instance: 1}]; const ticketId = 2; @@ -41,13 +31,6 @@ describe('sale deleteSales()', () => { try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; const sale = await models.Sale.findOne({where: {id: 9}}, options); sale.id = null; const newSale = await models.Sale.create(sale, options); diff --git a/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js b/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js index 3c871dd6c..b97060a3d 100644 --- a/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/recalculatePrice.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('sale recalculatePrice()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should update the sale price', async() => { const tx = await models.Sale.beginTransaction({}); const sales = [ diff --git a/modules/ticket/back/methods/sale/specs/reserve.spec.js b/modules/ticket/back/methods/sale/specs/reserve.spec.js index 009d7b711..e39f636cc 100644 --- a/modules/ticket/back/methods/sale/specs/reserve.spec.js +++ b/modules/ticket/back/methods/sale/specs/reserve.spec.js @@ -1,5 +1,4 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale reserve()', () => { const ctx = { @@ -10,9 +9,7 @@ describe('sale reserve()', () => { } }; - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should throw an error if the ticket can not be modified', async() => { const tx = await models.Sale.beginTransaction({}); diff --git a/modules/ticket/back/methods/sale/specs/updateConcept.spec.js b/modules/ticket/back/methods/sale/specs/updateConcept.spec.js index be6ad77a3..8e3538fc3 100644 --- a/modules/ticket/back/methods/sale/specs/updateConcept.spec.js +++ b/modules/ticket/back/methods/sale/specs/updateConcept.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('sale updateConcept()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); const saleId = 25; it('should throw if ID was undefined', async() => { diff --git a/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js index 396834df2..3fe174e46 100644 --- a/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js @@ -1,10 +1,8 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket-request confirm()', () => { - beforeAll(() => - mockLoopBackContext() - ); + const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); it(`should throw an error if the item doesn't exist`, async() => { const tx = await models.TicketRequest.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket-request/specs/deny.spec.js b/modules/ticket/back/methods/ticket-request/specs/deny.spec.js index aef07bd1b..9920bd4d3 100644 --- a/modules/ticket/back/methods/ticket-request/specs/deny.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/deny.spec.js @@ -1,29 +1,15 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket-request deny()', () => { - beforeAll(() => - mockLoopBackContext() - ); + const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); it('should return the denied ticket request', async() => { const tx = await models.TicketRequest.beginTransaction({}); try { const options = {transaction: tx}; - - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {id: 4, observation: 'my observation'}, - }; - - ctx.req.__ = value => { - return value; - }; - + ctx.args = {id: 4, observation: 'my observation'}; const result = await models.TicketRequest.deny(ctx, options); expect(result.id).toEqual(4); diff --git a/modules/ticket/back/methods/ticket/specs/clone.spec.js b/modules/ticket/back/methods/ticket/specs/clone.spec.js index cf222ab8d..ccc0dcdf3 100644 --- a/modules/ticket/back/methods/ticket/specs/clone.spec.js +++ b/modules/ticket/back/methods/ticket/specs/clone.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('Ticket cloning - clone function', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); let options; let tx; const ticketId = 1; diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index b138b88ea..15dd5e4ce 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -1,8 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket componentUpdate()', () => { - const userID = 1101; + const ctx = beforeAll.getCtx(1101); const ticketID = 11; const today = Date.vnNew(); const tomorrow = Date.vnNew(); @@ -16,8 +15,8 @@ describe('ticket componentUpdate()', () => { let componentOfSaleEight; let componentValue; + beforeAll.mockLoopBackContext(); beforeAll(async() => { - mockLoopBackContext(); const deliveryComponenet = await models.Component.findOne({where: {code: 'delivery'}}); deliveryComponentId = deliveryComponenet.id; componentOfSaleSeven = `SELECT value @@ -54,16 +53,7 @@ describe('ticket componentUpdate()', () => { isWithoutNegatives: false }; - let ctx = { - args: args, - req: { - accessToken: {userId: userID}, - headers: {origin: 'http://localhost'}, - __: value => { - return value; - } - } - }; + ctx.args = args; await models.Ticket.componentUpdate(ctx, options); [componentValue] = await models.SaleComponent.rawSql(componentOfSaleSeven, null, options); @@ -103,16 +93,7 @@ describe('ticket componentUpdate()', () => { isWithoutNegatives: false }; - const ctx = { - args: args, - req: { - accessToken: {userId: userID}, - headers: {origin: 'http://localhost'}, - __: value => { - return value; - } - } - }; + ctx.args = args; const observationTypeDelivery = await models.ObservationType.findOne({ where: {code: 'delivery'} }, options); @@ -142,6 +123,7 @@ describe('ticket componentUpdate()', () => { }); it('should change warehouse and without negatives', async() => { + const ctx = beforeAll.getCtx(9); const tx = await models.SaleComponent.beginTransaction({}); try { @@ -168,17 +150,7 @@ describe('ticket componentUpdate()', () => { option: 'renewPrices', isWithoutNegatives: true }; - - const ctx = { - args: args, - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'}, - __: value => { - return value; - } - } - }; + ctx.args = args; const oldTicket = await models.Ticket.findById(ticketID, null, options); @@ -200,6 +172,7 @@ describe('ticket componentUpdate()', () => { }); describe('componentUpdate() keepPrice', () => { + const ctx = beforeAll.getCtx(); it('should change shipped and keep price', async() => { const tx = await models.Ticket.beginTransaction({}); @@ -229,16 +202,7 @@ describe('ticket componentUpdate()', () => { keepPrice: true }; - const ctx = { - args: args, - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'}, - __: value => { - return value; - } - } - }; + ctx.args = args; const beforeSale = await models.Sale.findById(saleId, null, options); await models.Ticket.componentUpdate(ctx, options); @@ -282,16 +246,7 @@ describe('ticket componentUpdate()', () => { keepPrice: false }; - const ctx = { - args: args, - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'}, - __: value => { - return value; - } - } - }; + ctx.args = args; const beforeSale = await models.Sale.findById(saleId, null, options); await models.Ticket.componentUpdate(ctx, options); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index 8008acfaf..b162ce81f 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -1,13 +1,13 @@ const models = require('vn-loopback/server/server').models; describe('ticket filter()', () => { + const ctx = beforeAll.getCtx(); it('should return the tickets matching the filter', async() => { const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {}}; const filter = {order: 'id DESC'}; const result = await models.Ticket.filter(ctx, filter, options); @@ -31,11 +31,12 @@ describe('ticket filter()', () => { const today = Date.vnNew(); today.setHours(23, 59, 59, 59); - const ctx = {req: {accessToken: {userId: 9}}, args: { + const args = { problems: true, from: yesterday, to: today - }}; + }; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -60,11 +61,12 @@ describe('ticket filter()', () => { const today = Date.vnNew(); today.setHours(23, 59, 59, 59); - const ctx = {req: {accessToken: {userId: 9}}, args: { + const args = { problems: false, from: yesterday, to: today - }}; + }; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -83,7 +85,8 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {problems: null}}; + const args = {problems: null}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -102,7 +105,8 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {orderFk: 11}}; + const args = {orderFk: 11}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); const firstRow = result[0]; @@ -123,7 +127,8 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {pending: true}}; + const args = {pending: true}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -146,7 +151,8 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {pending: false}}; + const args = {pending: false}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); const firstRow = result[0]; @@ -167,11 +173,13 @@ describe('ticket filter()', () => { it('should return the tickets from the worker team', async() => { const tx = await models.Ticket.beginTransaction({}); + const ctx = beforeAll.getCtx(18); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: true}}; + const args = {myTeam: true}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -185,12 +193,14 @@ describe('ticket filter()', () => { }); it('should return the tickets that are not from the worker team', async() => { + const ctx = beforeAll.getCtx(18); const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 18}}, args: {myTeam: false}}; + const args = {myTeam: false}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -204,12 +214,14 @@ describe('ticket filter()', () => { }); it('should return the tickets belonging to the collection id 1', async() => { + const ctx = beforeAll.getCtx(18); const tx = await models.Ticket.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 18}}, args: {collectionFk: 1}}; + const args = {collectionFk: 1}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -228,7 +240,8 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {hasRoute: true}}; + const args = {hasRoute: true}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -247,7 +260,8 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {hasRoute: false}}; + const args = {hasRoute: false}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -266,7 +280,8 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {hasRoute: null}}; + const args = {hasRoute: null}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -285,7 +300,8 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {hasInvoice: true}}; + const args = {hasInvoice: true}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); @@ -304,7 +320,8 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}, args: {hasInvoice: null}}; + const args = {hasInvoice: null}; + ctx.args = args; const filter = {}; const result = await models.Ticket.filter(ctx, filter, options); diff --git a/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js b/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js index 5a3209a6d..488cd1fc2 100644 --- a/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getTicketsAdvance.spec.js @@ -1,6 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('TicketFuture getTicketsAdvance()', () => { + const ctx = beforeAll.getCtx(); const today = Date.vnNew(); today.setHours(0, 0, 0, 0); let tomorrow = Date.vnNew(); @@ -18,7 +19,7 @@ describe('TicketFuture getTicketsAdvance()', () => { warehouseFk: 1, }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsAdvance(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -42,7 +43,7 @@ describe('TicketFuture getTicketsAdvance()', () => { isFullMovable: true }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsAdvance(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -67,7 +68,7 @@ describe('TicketFuture getTicketsAdvance()', () => { isFullMovable: false }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsAdvance(ctx, options); expect(result.length).toEqual(0); @@ -92,7 +93,7 @@ describe('TicketFuture getTicketsAdvance()', () => { ipt: 'V' }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsAdvance(ctx, options); expect(result.length).toBeGreaterThan(5); @@ -117,7 +118,7 @@ describe('TicketFuture getTicketsAdvance()', () => { tfIpt: 'V' }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsAdvance(ctx, options); expect(result.length).toBeGreaterThan(5); diff --git a/modules/ticket/back/methods/ticket/specs/getTicketsFuture.spec.js b/modules/ticket/back/methods/ticket/specs/getTicketsFuture.spec.js index 44896493f..4b28f34ea 100644 --- a/modules/ticket/back/methods/ticket/specs/getTicketsFuture.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getTicketsFuture.spec.js @@ -1,6 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('ticket getTicketsFuture()', () => { + const ctx = beforeAll.getCtx(); const today = Date.vnNew(); today.setHours(0, 0, 0, 0); @@ -16,7 +17,7 @@ describe('ticket getTicketsFuture()', () => { warehouseFk: 1, }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -40,7 +41,7 @@ describe('ticket getTicketsFuture()', () => { problems: true }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -65,7 +66,7 @@ describe('ticket getTicketsFuture()', () => { problems: false }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toEqual(0); @@ -90,7 +91,7 @@ describe('ticket getTicketsFuture()', () => { problems: null }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -115,7 +116,7 @@ describe('ticket getTicketsFuture()', () => { state: 'OK' }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -140,7 +141,7 @@ describe('ticket getTicketsFuture()', () => { futureState: 'OK' }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -165,7 +166,7 @@ describe('ticket getTicketsFuture()', () => { ipt: null }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -190,7 +191,7 @@ describe('ticket getTicketsFuture()', () => { ipt: 'H' }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -215,7 +216,7 @@ describe('ticket getTicketsFuture()', () => { futureIpt: null }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -240,7 +241,7 @@ describe('ticket getTicketsFuture()', () => { futureIpt: 'H' }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -265,7 +266,7 @@ describe('ticket getTicketsFuture()', () => { id: 13 }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); @@ -290,7 +291,7 @@ describe('ticket getTicketsFuture()', () => { futureId: 12 }; - const ctx = {req: {accessToken: {userId: 9}}, args}; + ctx.args = args; const result = await models.Ticket.getTicketsFuture(ctx, options); expect(result.length).toBeGreaterThan(0); diff --git a/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js b/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js index e78812bfe..883b0de2e 100644 --- a/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js +++ b/modules/ticket/back/methods/ticket/specs/isEditableOrThrow.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('ticket isEditableOrThrow()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should throw an error as the ticket does not exist', async() => { const tx = await models.Ticket.beginTransaction({}); let error; diff --git a/modules/ticket/back/methods/ticket/specs/merge.spec.js b/modules/ticket/back/methods/ticket/specs/merge.spec.js index 21d4e5c75..68f9d3393 100644 --- a/modules/ticket/back/methods/ticket/specs/merge.spec.js +++ b/modules/ticket/back/methods/ticket/specs/merge.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('ticket merge()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); const tickets = { originId: 13, destinationId: 12, @@ -10,10 +10,6 @@ describe('ticket merge()', () => { workerFk: 1 }; - ctx.req.__ = value => { - return value; - }; - it('should merge two tickets', async() => { const tx = await models.Ticket.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js b/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js index 5c3811583..f9c7284f5 100644 --- a/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js +++ b/modules/ticket/back/methods/ticket/specs/recalculateComponents.spec.js @@ -3,7 +3,7 @@ const ForbiddenError = require('vn-loopback/util/forbiddenError'); describe('ticket recalculateComponents()', () => { const ticketId = 11; - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should update the ticket components', async() => { const tx = await models.Ticket.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js index b79e41d37..2a7b82ea0 100644 --- a/modules/ticket/back/methods/ticket/specs/sendSms.spec.js +++ b/modules/ticket/back/methods/ticket/specs/sendSms.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('ticket sendSms()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should send a message and log it', async() => { const tx = await models.Ticket.beginTransaction({}); diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js index cb2a21d91..ed9347714 100644 --- a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js @@ -1,17 +1,8 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('ticket setDeleted()', () => { - const userId = 1106; - const activeCtx = { - accessToken: {userId: userId}, - }; - - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); it('should throw an error if the given ticket has a claim', async() => { const tx = await models.Ticket.beginTransaction({}); @@ -20,7 +11,6 @@ describe('ticket setDeleted()', () => { try { const options = {transaction: tx}; - const ctx = {req: activeCtx}; const ticketId = 16; await models.Ticket.setDeleted(ctx, ticketId, options); @@ -40,15 +30,6 @@ describe('ticket setDeleted()', () => { try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost:5000'}, - } - }; - ctx.req.__ = value => { - return value; - }; const ticketId = 24; const [sectorCollectionBefore] = await models.Ticket.rawSql( `SELECT COUNT(*) numberRows @@ -75,15 +56,6 @@ describe('ticket setDeleted()', () => { try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost:5000'}, - } - }; - ctx.req.__ = value => { - return value; - }; const [ticketCollectionOld] = await models.Ticket.rawSql( `SELECT COUNT(*) numberRows FROM vn.ticketCollection`, [], options); @@ -110,16 +82,6 @@ describe('ticket setDeleted()', () => { try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost:5000'}, - } - }; - ctx.req.__ = value => { - return value; - }; - const ticketId = 8; await models.Ticket.setDeleted(ctx, ticketId, options); diff --git a/modules/ticket/back/methods/ticket/specs/state.spec.js b/modules/ticket/back/methods/ticket/specs/state.spec.js index d908aa2ef..3042633c6 100644 --- a/modules/ticket/back/methods/ticket/specs/state.spec.js +++ b/modules/ticket/back/methods/ticket/specs/state.spec.js @@ -2,14 +2,10 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('ticket state()', () => { + const ctx = beforeAll.getCtx(); const salesPersonId = 18; const employeeId = 1; const productionId = 49; - const activeCtx = { - accessToken: {userId: 9}, - __: value => value - }; - const ctx = {req: activeCtx}; const now = Date.vnNew(); const sampleTicket = { shipped: now, @@ -33,7 +29,7 @@ describe('ticket state()', () => { beforeAll(async() => { spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx + active: ctx }); }); @@ -45,7 +41,7 @@ describe('ticket state()', () => { try { const options = {transaction: tx}; - activeCtx.accessToken.userId = salesPersonId; + ctx.req.accessToken.userId = salesPersonId; await models.Ticket.state(ctx, {ticketFk: 2, stateFk: 3}, options); @@ -66,7 +62,7 @@ describe('ticket state()', () => { try { const options = {transaction: tx}; - activeCtx.accessToken.userId = employeeId; + ctx.req.accessToken.userId = employeeId; await models.Ticket.state(ctx, {ticketFk: 11, stateFk: 13}, options); @@ -88,7 +84,7 @@ describe('ticket state()', () => { const ticket = await models.Ticket.create(sampleTicket, options); - activeCtx.accessToken.userId = productionId; + ctx.req.accessToken.userId = productionId; const stateOk = await models.State.findOne({where: {code: 'OK'}}, options); const params = {ticketFk: ticket.id, stateFk: stateOk.id}; @@ -114,7 +110,7 @@ describe('ticket state()', () => { const options = {transaction: tx}; const ticket = await models.Ticket.create(sampleTicket, options); - activeCtx.accessToken.userId = salesPersonId; + ctx.req.accessToken.userId = salesPersonId; const assignedState = await models.State.findOne({where: {code: 'PICKER_DESIGNED'}}, options); const paramsAssigned = {ticketFk: ticket.id, stateFk: assignedState.id, userFk: 1}; const resAssigned = await models.Ticket.state(ctx, paramsAssigned, options); @@ -125,7 +121,7 @@ describe('ticket state()', () => { expect(resAssigned.userFk).toBe(1); expect(resAssigned.id).toBeDefined(); - activeCtx.accessToken.userId = productionId; + ctx.req.accessToken.userId = productionId; const packedState = await models.State.findOne({where: {code: 'PACKED'}}, options); const paramsPacked = {ticketFk: ticket.id, stateFk: packedState.id, userFk: salesPersonId}; const resPacked = await models.Ticket.state(ctx, paramsPacked, options); @@ -147,7 +143,7 @@ describe('ticket state()', () => { const options = {transaction: tx}; const ticket = await models.Ticket.create(sampleTicket, options); - activeCtx.accessToken.userId = salesPersonId; + ctx.req.accessToken.userId = salesPersonId; const sampleSale = { ticketFk: ticket.id, @@ -167,7 +163,7 @@ describe('ticket state()', () => { expect(resAssigned.userFk).toBe(1); expect(resAssigned.id).toBeDefined(); - activeCtx.accessToken.userId = productionId; + ctx.req.accessToken.userId = productionId; const packedState = await models.State.findOne({where: {code: 'PACKED'}}, options); const paramsPacked = {ticketFk: ticket.id, stateFk: packedState.id, userFk: salesPersonId}; const resPacked = await models.Ticket.state(ctx, paramsPacked, options); diff --git a/modules/ticket/back/methods/ticket/specs/transferClient.spec.js b/modules/ticket/back/methods/ticket/specs/transferClient.spec.js index 4aac0833a..01fd8fcbe 100644 --- a/modules/ticket/back/methods/ticket/specs/transferClient.spec.js +++ b/modules/ticket/back/methods/ticket/specs/transferClient.spec.js @@ -5,7 +5,7 @@ describe('Ticket transferClient()', () => { const refundTicketId = 24; const clientId = 1; - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); let options; let tx; beforeEach(async() => { diff --git a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js index 01e6e64bb..272387a30 100644 --- a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js +++ b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js @@ -1,10 +1,8 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('sale updateDiscount()', () => { - beforeAll(() => - mockLoopBackContext() - ); + const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); const originalSaleId = 8; it('should throw an error if no sales were selected', async() => { @@ -14,13 +12,6 @@ describe('sale updateDiscount()', () => { try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; const ticketId = 11; const sales = []; const newDiscount = 10; @@ -43,13 +34,6 @@ describe('sale updateDiscount()', () => { try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; const ticketId = 11; const sales = [1, 14]; const newDiscount = 10; @@ -72,13 +56,6 @@ describe('sale updateDiscount()', () => { try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; const ticketId = 1; const sales = [1]; const newDiscount = 100; @@ -96,17 +73,11 @@ describe('sale updateDiscount()', () => { it('should update the discount if the salesPerson has mana and manaCode = "mana"', async() => { const tx = await models.Ticket.beginTransaction({}); + const ctx = beforeAll.getCtx(18); try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 18}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; const ticketId = 11; const sales = [originalSaleId]; const newDiscount = 100; @@ -141,17 +112,11 @@ describe('sale updateDiscount()', () => { it('should update the discount if the salesPerson has mana and manaCode = "manaClaim"', async() => { const tx = await models.Ticket.beginTransaction({}); + const ctx = beforeAll.getCtx(18); try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 18}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; const ticketId = 11; const sales = [originalSaleId]; const newDiscount = 100; @@ -190,13 +155,6 @@ describe('sale updateDiscount()', () => { try { const options = {transaction: tx}; - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; const ticketId = 11; const sales = [originalSaleId]; const newDiscount = 100; diff --git a/modules/ticket/back/models/specs/ticket-packaging.spec.js b/modules/ticket/back/models/specs/ticket-packaging.spec.js index 7ff863cff..5e0ca82db 100644 --- a/modules/ticket/back/models/specs/ticket-packaging.spec.js +++ b/modules/ticket/back/models/specs/ticket-packaging.spec.js @@ -1,10 +1,7 @@ const app = require('vn-loopback/server/server'); -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('ticket model TicketTracking', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); let ticketTrackingId; afterAll(async() => { diff --git a/modules/ticket/back/models/ticket-request.js b/modules/ticket/back/models/ticket-request.js index 622cd7696..30d6a5454 100644 --- a/modules/ticket/back/models/ticket-request.js +++ b/modules/ticket/back/models/ticket-request.js @@ -19,7 +19,7 @@ module.exports = function(Self) { instance.requesterFk = worker.id; const httpCtx = {req: loopBackContext.active}; - const httpRequest = httpCtx.req.http .req; + const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; if (attenderFk) { diff --git a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js index 49eeb86c2..71b9fcccb 100644 --- a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js @@ -5,7 +5,7 @@ describe('Termograph createThermograph()', () => { const model = 'DISPOSABLE'; const temperatureFk = 'COOL'; const warehouseId = 1; - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it(`should create a thermograph which is saved in both thermograph and travelThermograph`, async() => { const tx = await models.Thermograph.beginTransaction({}); diff --git a/modules/travel/back/methods/travel/specs/createThermograph.spec.js b/modules/travel/back/methods/travel/specs/createThermograph.spec.js index 2b0ae48f4..f70e27368 100644 --- a/modules/travel/back/methods/travel/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/travel/specs/createThermograph.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Travel createThermograph()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); const travelId = 3; const currentUserId = 1102; const thermographId = '138350-0'; diff --git a/modules/worker/back/methods/calendar/specs/absences.spec.js b/modules/worker/back/methods/calendar/specs/absences.spec.js index 0e6f21a5f..f369d1dca 100644 --- a/modules/worker/back/methods/calendar/specs/absences.spec.js +++ b/modules/worker/back/methods/calendar/specs/absences.spec.js @@ -1,7 +1,7 @@ const app = require('vn-loopback/server/server'); describe('Worker absences()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should get the absence calendar for a full year contract', async() => { const ctx = {req: {accessToken: {userId: 1106}}}; const workerId = 1106; diff --git a/modules/worker/back/methods/department/specs/getLeaves.spec.js b/modules/worker/back/methods/department/specs/getLeaves.spec.js index d7e934d20..2feb6b461 100644 --- a/modules/worker/back/methods/department/specs/getLeaves.spec.js +++ b/modules/worker/back/methods/department/specs/getLeaves.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('department getLeaves()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should return the department and the childs containing the search value', async() => { let result = await models.Department.getLeaves(ctx, null, 'INFORMATICA'); diff --git a/modules/worker/back/methods/worker/specs/createAbsence.spec.js b/modules/worker/back/methods/worker/specs/createAbsence.spec.js index aadaca99b..fcb1c1633 100644 --- a/modules/worker/back/methods/worker/specs/createAbsence.spec.js +++ b/modules/worker/back/methods/worker/specs/createAbsence.spec.js @@ -133,7 +133,8 @@ describe('Worker createAbsence()', () => { expect(error.message).toEqual(`Cannot add holidays on this day`); }); - it(`should throw an error when adding a absence if the worker has hours recorded that day and not is a half absence`, async() => { + it(`should throw an error when adding a absence if the worker ` + + `has hours recorded that day and not is a half absence`, async() => { const ctx = { req: {accessToken: {userId: 19}}, args: { diff --git a/modules/worker/back/methods/worker/specs/mySubordinates.spec.js b/modules/worker/back/methods/worker/specs/mySubordinates.spec.js index ecd668603..7443827ce 100644 --- a/modules/worker/back/methods/worker/specs/mySubordinates.spec.js +++ b/modules/worker/back/methods/worker/specs/mySubordinates.spec.js @@ -1,7 +1,7 @@ const app = require('vn-loopback/server/server'); describe('worker mySubordinates()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should return an array of subordinates greather than 1', async() => { let result = await app.models.Worker.mySubordinates(ctx); diff --git a/modules/worker/back/methods/worker/specs/new.spec.js b/modules/worker/back/methods/worker/specs/new.spec.js index 04540b9b7..d9e843064 100644 --- a/modules/worker/back/methods/worker/specs/new.spec.js +++ b/modules/worker/back/methods/worker/specs/new.spec.js @@ -1,5 +1,4 @@ const {models} = require('vn-loopback/server/server'); -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('Worker new', () => { const developerId = 9; @@ -10,9 +9,7 @@ describe('Worker new', () => { let tx; let opts; - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); describe('should return error', () => { beforeEach(async() => { diff --git a/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js b/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js index 27a48a848..931a5c707 100644 --- a/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js +++ b/modules/zone/back/methods/agency/specs/getAgenciesWithWarehouse.spec.js @@ -1,7 +1,7 @@ const app = require('vn-loopback/server/server'); describe('Agency getAgenciesWithWarehouse()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); const today = Date.vnNew(); it('should return the agencies that can handle the given delivery request', async() => { const tx = await app.models.Zone.beginTransaction({}); diff --git a/modules/zone/back/methods/agency/specs/landsThatDay.spec.js b/modules/zone/back/methods/agency/specs/landsThatDay.spec.js index 27e71bc6f..cd587a329 100644 --- a/modules/zone/back/methods/agency/specs/landsThatDay.spec.js +++ b/modules/zone/back/methods/agency/specs/landsThatDay.spec.js @@ -1,7 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('Agency landsThatDay()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); const today = Date.vnNew(); it('should return a list of agencies that can land a shipment on a day for an address', async() => { const tx = await models.Agency.beginTransaction({}); diff --git a/modules/zone/back/methods/zone/specs/clone.spec.js b/modules/zone/back/methods/zone/specs/clone.spec.js index 292aeb2ac..3a8783f21 100644 --- a/modules/zone/back/methods/zone/specs/clone.spec.js +++ b/modules/zone/back/methods/zone/specs/clone.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('agency clone()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should clone a zone', async() => { const tx = await models.Zone.beginTransaction({}); diff --git a/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js b/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js index dc2eeb8a8..bd4438204 100644 --- a/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js +++ b/modules/zone/back/methods/zone/specs/exclusionGeo.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('zone exclusionGeo()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); const zoneId = 1; const today = Date.vnNew(); diff --git a/modules/zone/back/methods/zone/specs/getEvents.spec.js b/modules/zone/back/methods/zone/specs/getEvents.spec.js index 3c9dd76f2..80388d009 100644 --- a/modules/zone/back/methods/zone/specs/getEvents.spec.js +++ b/modules/zone/back/methods/zone/specs/getEvents.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('zone getEvents()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should return all events for the specified geo and agency mode', async() => { const tx = await models.Zone.beginTransaction({}); diff --git a/modules/zone/back/methods/zone/specs/getLeaves.spec.js b/modules/zone/back/methods/zone/specs/getLeaves.spec.js index 4b8ab926c..fde56be35 100644 --- a/modules/zone/back/methods/zone/specs/getLeaves.spec.js +++ b/modules/zone/back/methods/zone/specs/getLeaves.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('zone getLeaves()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should return the country and the childs containing the search value', async() => { const tx = await models.Zone.beginTransaction({}); diff --git a/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js b/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js index cf2a070f3..08d8601bc 100644 --- a/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js +++ b/modules/zone/back/methods/zone/specs/getUpcomingDeliveries.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('zone getUpcomingDeliveries()', () => { - const {ctx} = beforeAll; + const ctx = beforeAll.getCtx(); it('should check returns data', async() => { const tx = await models.Zone.beginTransaction({}); diff --git a/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js b/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js index 480c8b7ef..81d02193e 100644 --- a/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js +++ b/modules/zone/back/methods/zone/specs/toggleIsIncluded.spec.js @@ -1,10 +1,7 @@ const models = require('vn-loopback/server/server').models; -const {mockLoopBackContext} = require('vn-loopback/../../back/vn-jasmine'); describe('zone toggleIsIncluded()', () => { - beforeAll(() => - mockLoopBackContext() - ); + beforeAll.mockLoopBackContext(); it('should return the created location with isIncluded true', async() => { const tx = await models.Zone.beginTransaction({}); -- 2.40.1 From ee75068e9c0eaadc3b2c09f61600d522f8658992 Mon Sep 17 00:00:00 2001 From: Jon Date: Fri, 14 Jun 2024 08:57:11 +0200 Subject: [PATCH 202/413] refactor: refs #6436 fixed test --- back/methods/starred-module/specs/setPosition.spec.js | 1 + 1 file changed, 1 insertion(+) diff --git a/back/methods/starred-module/specs/setPosition.spec.js b/back/methods/starred-module/specs/setPosition.spec.js index c99206e56..63addeffc 100644 --- a/back/methods/starred-module/specs/setPosition.spec.js +++ b/back/methods/starred-module/specs/setPosition.spec.js @@ -2,6 +2,7 @@ const {models} = require('vn-loopback/server/server'); describe('setPosition()', () => { const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); it('should increase the orders module position by replacing it with clients and vice versa', async() => { const tx = await models.StarredModule.beginTransaction({}); -- 2.40.1 From d3f23a6d7a97d4288863200550733484f28e3c87 Mon Sep 17 00:00:00 2001 From: Jon Date: Fri, 14 Jun 2024 09:04:18 +0200 Subject: [PATCH 203/413] fix: refs #6436 fix filter test --- modules/ticket/back/methods/ticket/specs/filter.spec.js | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index b162ce81f..1d050931b 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -8,6 +8,7 @@ describe('ticket filter()', () => { try { const options = {transaction: tx}; + const ctx = {req: {accessToken: {userId: 9}}, args: {}}; const filter = {order: 'id DESC'}; const result = await models.Ticket.filter(ctx, filter, options); -- 2.40.1 From 189c67bd2d9eccbe2ea6cd9c27d981c64d9da720 Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 14 Jun 2024 09:43:10 +0200 Subject: [PATCH 204/413] warmFix change if --- db/dump/fixtures.before.sql | 38 +++++++++++++++++-- loopback/locale/en.json | 8 ++-- .../back/methods/worker/createAbsence.js | 3 +- 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 592297894..591716a83 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -767,7 +767,7 @@ INSERT INTO `vn`.`ticket`(`id`, `priority`, `agencyModeFk`,`warehouseFk`,`routeF (35, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Somewhere in Philippines', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), (36, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1102, 'Ant-Man Adventure', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL), (37, 1, 1, 1, 3, util.VN_CURDATE(), util.VN_CURDATE(), 1110, 'Deadpool swords', 123, NULL, 0, 1, 16, 0, util.VN_CURDATE(), NULL, NULL); - + INSERT INTO `vn`.`ticketObservation`(`id`, `ticketFk`, `observationTypeFk`, `description`) VALUES (1, 11, 1, 'ready'), @@ -3841,7 +3841,7 @@ INSERT INTO `vn`.`ledgerConfig` SET INSERT INTO vn.sectorCollection SET id = 2, userFk = 18, - sectorFk = 1; + sectorFk = 1; INSERT INTO vn.sectorCollectionSaleGroup SET id = 8, @@ -3855,9 +3855,39 @@ INSERT INTO vn.saleGroup (userFk, parkingFk, sectorFk, ticketFk) INSERT INTO vn.sectorCollection SET id = 3, userFk = 18, - sectorFk = 1; + sectorFk = 1; INSERT INTO vn.sectorCollectionSaleGroup SET id = 9, sectorCollectionFk = 3, - saleGroupFk = 6; \ No newline at end of file + saleGroupFk = 6; + + +INSERT INTO vn.calendarHolidays +(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) +VALUES(2, 1, '2001-05-08', 1, 1); +INSERT INTO vn.calendarHolidays +(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) +VALUES(3, 1, '2001-05-09', 1, 1); +INSERT INTO vn.calendarHolidays +(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) +VALUES(4, 1, '2001-05-10', 1, 1); +INSERT INTO vn.calendarHolidays +(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) +VALUES(5, 1, '2001-05-11', 1, 1); +INSERT INTO vn.calendarHolidays +(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) +VALUES(6, 1, '2001-05-14', 1, 5); +INSERT INTO vn.calendarHolidays +(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) +VALUES(7, 1, '2001-05-15', 1, 5); +INSERT INTO vn.calendarHolidays +(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) +VALUES(8, 1, '2001-05-16', 1, 5); +INSERT INTO vn.calendarHolidays +(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) +VALUES(9, 1, '2001-05-17', 1, 5); +INSERT INTO vn.calendarHolidays +(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) +VALUES(10, 1, '2001-05-18', 1, 5); + diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 740b50bcd..a2332fdca 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -229,8 +229,8 @@ "InvoiceIn is already booked": "InvoiceIn is already booked", "This workCenter is already assigned to this agency": "This workCenter is already assigned to this agency", "You can only have one PDA": "You can only have one PDA", - "Incoterms and Customs agent are required for a non UEE member": "Incoterms and Customs agent are required for a non UEE member", + "Incoterms and Customs agent are required for a non UEE member": "Incoterms and Customs agent are required for a non UEE member", "It has been invoiced but the PDF could not be generated": "It has been invoiced but the PDF could not be generated", - "It has been invoiced but the PDF of refund not be generated": "It has been invoiced but the PDF of refund not be generated" - -} + "It has been invoiced but the PDF of refund not be generated": "It has been invoiced but the PDF of refund not be generated", + "Cannot add holidays on this day": "Cannot add holidays on this day" +} \ No newline at end of file diff --git a/modules/worker/back/methods/worker/createAbsence.js b/modules/worker/back/methods/worker/createAbsence.js index 2de1d6e4d..0397886cf 100644 --- a/modules/worker/back/methods/worker/createAbsence.js +++ b/modules/worker/back/methods/worker/createAbsence.js @@ -110,8 +110,7 @@ module.exports = Self => { workCenterFk: workCenter.workCenterFk } }); - - if (holiday && isFestive) + if ((holiday && isFestive) && (workCenter.workcenterFk === holiday.workCenterFk)) throw new UserError(`Cannot add holidays on this day`); const absence = await models.Calendar.create({ -- 2.40.1 From e3e9706fb86b95de180471178b277fee467b1d3c Mon Sep 17 00:00:00 2001 From: carlossa Date: Fri, 14 Jun 2024 09:53:50 +0200 Subject: [PATCH 205/413] fix fixtures --- db/dump/fixtures.before.sql | 38 +++++++++++-------------------------- 1 file changed, 11 insertions(+), 27 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 591716a83..b1fe01cb3 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3863,31 +3863,15 @@ INSERT INTO vn.sectorCollectionSaleGroup saleGroupFk = 6; -INSERT INTO vn.calendarHolidays -(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) -VALUES(2, 1, '2001-05-08', 1, 1); -INSERT INTO vn.calendarHolidays -(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) -VALUES(3, 1, '2001-05-09', 1, 1); -INSERT INTO vn.calendarHolidays -(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) -VALUES(4, 1, '2001-05-10', 1, 1); -INSERT INTO vn.calendarHolidays -(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) -VALUES(5, 1, '2001-05-11', 1, 1); -INSERT INTO vn.calendarHolidays -(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) -VALUES(6, 1, '2001-05-14', 1, 5); -INSERT INTO vn.calendarHolidays -(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) -VALUES(7, 1, '2001-05-15', 1, 5); -INSERT INTO vn.calendarHolidays -(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) -VALUES(8, 1, '2001-05-16', 1, 5); -INSERT INTO vn.calendarHolidays -(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) -VALUES(9, 1, '2001-05-17', 1, 5); -INSERT INTO vn.calendarHolidays -(id, calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) -VALUES(10, 1, '2001-05-18', 1, 5); +INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHolidaysNameFk, workCenterFk) + VALUES + (1, '2001-05-08', 1, 1), + (1, '2001-05-09', 1, 1), + (1, '2001-05-10', 1, 1), + (1, '2001-05-11', 1, 1), + (1, '2001-05-14', 1, 5), + (1, '2001-05-15', 1, 5), + (1, '2001-05-16', 1, 5), + (1, '2001-05-17', 1, 5), + (1, '2001-05-18', 1, 5); -- 2.40.1 From 798bf6d0288246c24ac015ac38f377879cbaf462 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 14 Jun 2024 12:41:46 +0200 Subject: [PATCH 206/413] hotfix: refs #6281 itemShelving_add buy is required --- db/routines/vn/procedures/itemShelving_add.sql | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/db/routines/vn/procedures/itemShelving_add.sql b/db/routines/vn/procedures/itemShelving_add.sql index 9395f5d80..c308304ef 100644 --- a/db/routines/vn/procedures/itemShelving_add.sql +++ b/db/routines/vn/procedures/itemShelving_add.sql @@ -1,7 +1,14 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`( + vShelvingFk VARCHAR(8), + vBarcode VARCHAR(22), + vQuantity INT, + vPackagingFk VARCHAR(10), + vGrouping INT, + vPacking INT, + vWarehouseFk INT +) BEGIN - /** * Añade registro o lo actualiza si ya existe. * @@ -23,12 +30,7 @@ BEGIN SELECT barcodeToItem(vBarcode) INTO vItemFk; IF vBuyFk IS NULL THEN - CALL cache.last_buy_refresh(FALSE); - - SELECT buy_id INTO vBuyFk - FROM cache.last_buy - WHERE item_id = vItemFk - AND warehouse_id = vWarehouseFk; + CALL util.throw('The buy is required'); END IF; IF vPacking IS NULL -- 2.40.1 From 8dea9598e885b3327f6e51c855ef029568dc3f23 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 14 Jun 2024 13:54:43 +0200 Subject: [PATCH 207/413] fix: refs #194195 item_getAtp --- db/routines/vn/procedures/item_getAtp.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/item_getAtp.sql b/db/routines/vn/procedures/item_getAtp.sql index bbf13d396..8266e58da 100644 --- a/db/routines/vn/procedures/item_getAtp.sql +++ b/db/routines/vn/procedures/item_getAtp.sql @@ -1,5 +1,5 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getAtp`(vDated DATE) +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getAtp`(vDated DATE) BEGIN /** * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y @@ -33,7 +33,7 @@ BEGIN FROM ( SELECT itemFk, - IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, + IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk OR wareHouseFk IS NULL, @lastQuantity := quantity, @lastQuantity := @lastQuantity + quantity) quantityAccumulated, wareHouseFk, @@ -44,5 +44,5 @@ BEGIN GROUP BY itemFk, wareHouseFk; DROP TEMPORARY TABLE tItemOrdered; -END$$ -DELIMITER ; +END$$ +DELIMITER ; -- 2.40.1 From 202884fdce1ccbf984cb1fcf49e2a16be971dd34 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 14 Jun 2024 14:25:15 +0200 Subject: [PATCH 208/413] feat: refs #6238 add travelKgPercentage table and model --- .../00-createTravelKgPercentage.sql | 17 +++++++++++++++ .../methods/travel/extraCommunityFilter.js | 14 ++++++++++++- modules/travel/back/model-config.json | 5 ++++- .../back/models/travel-kg-percentage.json | 21 +++++++++++++++++++ 4 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql create mode 100644 modules/travel/back/models/travel-kg-percentage.json diff --git a/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql b/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql new file mode 100644 index 000000000..9df89d869 --- /dev/null +++ b/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql @@ -0,0 +1,17 @@ +CREATE TABLE IF NOT EXISTS travelKgPercentage ( + value INT(3) PRIMARY KEY, + className VARCHAR(50) +); + +INSERT INTO travelKgPercentage (value, className) + VALUES + (80, 'primary'), + (100, 'alert'); + +INSERT INTO salix.ACL + SET model = 'TravelKgPercentage', + property = '*', + accessType = 'READ', + permission = 'ALLOW', + principalType = 'ROLE', + principalId = 'employee'; \ No newline at end of file diff --git a/modules/travel/back/methods/travel/extraCommunityFilter.js b/modules/travel/back/methods/travel/extraCommunityFilter.js index 488297318..107bf6f39 100644 --- a/modules/travel/back/methods/travel/extraCommunityFilter.js +++ b/modules/travel/back/methods/travel/extraCommunityFilter.js @@ -138,7 +138,19 @@ module.exports = Self => { b.stickers * IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000 ) as DECIMAL(10,0) - ) as volumeKg + ) as volumeKg, + ROUND(GREATEST( + CAST(SUM(b.weight * b.stickers) AS INT), + CAST( + SUM(vc.aerealVolumetricDensity * + b.stickers * + IF(pkg.volume, + pkg.volume, + pkg.width * pkg.depth * pkg.height + ) / 1000000 + ) AS INT + ) + ) / t.kg * 100, 0) percentageKg FROM travel t LEFT JOIN supplier s ON s.id = t.cargoSupplierFk LEFT JOIN entry e ON e.travelFk = t.id diff --git a/modules/travel/back/model-config.json b/modules/travel/back/model-config.json index ed5c071b3..952ce0d20 100644 --- a/modules/travel/back/model-config.json +++ b/modules/travel/back/model-config.json @@ -11,6 +11,9 @@ "Thermograph": { "dataSource": "vn" }, + "TravelKgPercentage": { + "dataSource": "vn" + }, "TravelThermograph": { "dataSource": "vn" }, @@ -20,4 +23,4 @@ "Temperature": { "dataSource": "vn" } -} +} \ No newline at end of file diff --git a/modules/travel/back/models/travel-kg-percentage.json b/modules/travel/back/models/travel-kg-percentage.json new file mode 100644 index 000000000..e99a88999 --- /dev/null +++ b/modules/travel/back/models/travel-kg-percentage.json @@ -0,0 +1,21 @@ +{ + "name": "TravelKgPercentage", + "base": "VnModel", + "mixins": { + "Loggable": true + }, + "options": { + "mysql": { + "table": "travelKgPercentage" + } + }, + "properties": { + "value": { + "type": "number", + "id": true + }, + "className": { + "type": "string" + } + } +} \ No newline at end of file -- 2.40.1 From df6de7e74c34e861bda3e5fb4750a837fc499773 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 14 Jun 2024 14:55:03 +0200 Subject: [PATCH 209/413] fix: refs #194195 item_getAtp --- db/routines/vn/procedures/item_getAtp.sql | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/item_getAtp.sql b/db/routines/vn/procedures/item_getAtp.sql index 8266e58da..d02d7cc90 100644 --- a/db/routines/vn/procedures/item_getAtp.sql +++ b/db/routines/vn/procedures/item_getAtp.sql @@ -20,12 +20,11 @@ BEGIN SELECT itemFk, warehouseFk, vDated, 0 FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 ) t1 - GROUP BY itemFk, warehouseFk, dated - ORDER BY itemFk, warehouseFk, dated; + GROUP BY itemFk, warehouseFk, dated; - SET @lastItemFk := 0; - SET @lastWareHouseFk := 0; - SET @lastQuantity := 0; + SET @lastItemFk = 0; + SET @lastWareHouseFk = 0; + SET @lastQuantity = 0; CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp (INDEX (itemFk, wareHouseFk)) @@ -40,6 +39,8 @@ BEGIN @lastItemFk := itemFk, @lastWareHouseFk := wareHouseFk FROM tItemOrdered + ORDER BY itemFk, warehouseFk, dated + LIMIT 10000000000000000000 )sub GROUP BY itemFk, wareHouseFk; -- 2.40.1 From 5473f7a3080441aea25c68c738c91cbf5a27eb13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 14 Jun 2024 16:01:27 +0200 Subject: [PATCH 210/413] Hotfix Ticket #194195 Error radar negativos --- db/routines/vn/procedures/item_getAtp.sql | 14 +++++++------- db/routines/vn/procedures/item_getMinacum.sql | 5 +++-- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/db/routines/vn/procedures/item_getAtp.sql b/db/routines/vn/procedures/item_getAtp.sql index d02d7cc90..0cbb8ab06 100644 --- a/db/routines/vn/procedures/item_getAtp.sql +++ b/db/routines/vn/procedures/item_getAtp.sql @@ -20,11 +20,13 @@ BEGIN SELECT itemFk, warehouseFk, vDated, 0 FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 ) t1 - GROUP BY itemFk, warehouseFk, dated; + GROUP BY itemFk, warehouseFk, dated + HAVING warehouseFk + ORDER BY itemFk, warehouseFk, dated; - SET @lastItemFk = 0; - SET @lastWareHouseFk = 0; - SET @lastQuantity = 0; + SET @lastItemFk := 0; + SET @lastWareHouseFk := 0; + SET @lastQuantity := 0; CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp (INDEX (itemFk, wareHouseFk)) @@ -32,15 +34,13 @@ BEGIN FROM ( SELECT itemFk, - IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk OR wareHouseFk IS NULL, + IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, @lastQuantity := quantity, @lastQuantity := @lastQuantity + quantity) quantityAccumulated, wareHouseFk, @lastItemFk := itemFk, @lastWareHouseFk := wareHouseFk FROM tItemOrdered - ORDER BY itemFk, warehouseFk, dated - LIMIT 10000000000000000000 )sub GROUP BY itemFk, wareHouseFk; diff --git a/db/routines/vn/procedures/item_getMinacum.sql b/db/routines/vn/procedures/item_getMinacum.sql index ed987637c..7573759f7 100644 --- a/db/routines/vn/procedures/item_getMinacum.sql +++ b/db/routines/vn/procedures/item_getMinacum.sql @@ -30,6 +30,7 @@ BEGIN FROM sale s JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + AND t.warehouseFk AND s.quantity != 0 AND (vItemFk IS NULL OR s.itemFk = vItemFk) AND (vWarehouseFk IS NULL OR t.warehouseFk = vWarehouseFk) @@ -40,7 +41,7 @@ BEGIN t.warehouseInFk FROM buy b JOIN entry e ON e.id = b.entryFk - LEFT JOIN travel t ON t.id = e.travelFk + JOIN travel t ON t.id = e.travelFk WHERE t.landed BETWEEN vDatedFrom AND vDatedTo AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND !e.isExcludedFromAvailable @@ -53,7 +54,7 @@ BEGIN t.warehouseOutFk FROM buy b JOIN entry e ON e.id = b.entryFk - LEFT JOIN travel t ON t.id = e.travelFk + JOIN travel t ON t.id = e.travelFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND (vWarehouseFk IS NULL OR t.warehouseOutFk = vWarehouseFk) AND !e.isExcludedFromAvailable -- 2.40.1 From 51078c804b439d59eeabf77d38dd19a9b7f1521e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 14 Jun 2024 16:32:13 +0200 Subject: [PATCH 211/413] Ticket #194195 Recupero vn.item_getAtp --- db/routines/vn/procedures/item_getAtp.sql | 1 - 1 file changed, 1 deletion(-) diff --git a/db/routines/vn/procedures/item_getAtp.sql b/db/routines/vn/procedures/item_getAtp.sql index 0cbb8ab06..255e38867 100644 --- a/db/routines/vn/procedures/item_getAtp.sql +++ b/db/routines/vn/procedures/item_getAtp.sql @@ -21,7 +21,6 @@ BEGIN FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 ) t1 GROUP BY itemFk, warehouseFk, dated - HAVING warehouseFk ORDER BY itemFk, warehouseFk, dated; SET @lastItemFk := 0; -- 2.40.1 From a30ff44837588b8b6cf85012aaff07cef7c91943 Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 14 Jun 2024 17:40:08 +0200 Subject: [PATCH 212/413] fix: refs #6404 fix notification --- back/methods/mrw-config/createShipment.js | 12 ++-- .../mrw-config/specs/createShipment.spec.js | 62 ++++++++----------- back/models/mrw-config.js | 2 +- db/dump/fixtures.before.sql | 6 +- .../11086-grayCataractarum/00-firstScript.sql | 9 +++ .../assets/css/import.js | 0 .../locale/en.yml | 0 .../locale/es.yml | 0 .../mrw-deadline.html} | 0 .../mrw-deadline.js} | 2 +- 10 files changed, 45 insertions(+), 48 deletions(-) rename print/templates/email/{mrw-webService-deadline => mrw-deadline}/assets/css/import.js (100%) rename print/templates/email/{mrw-webService-deadline => mrw-deadline}/locale/en.yml (100%) rename print/templates/email/{mrw-webService-deadline => mrw-deadline}/locale/es.yml (100%) rename print/templates/email/{mrw-webService-deadline/mrw-webService-deadline.html => mrw-deadline/mrw-deadline.html} (100%) rename print/templates/email/{mrw-webService-deadline/mrw-webService-deadline.js => mrw-deadline/mrw-deadline.js} (83%) diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index ca155919f..a2fccb95b 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -1,4 +1,3 @@ -const {Email} = require('vn-print'); const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { @@ -21,19 +20,17 @@ module.exports = Self => { }); Self.createShipment = async expeditionFk => { - const mrwConfig = Self.app.models.MrwConfig; + const models = Self.app.models; const mrw = await Self.getConfig(); const today = Date.vnNew(); - const [hours, minutes] = mrw?.expeditionDeadLine ? mrw.expeditionDeadLine.split(':').map(Number) : [0, 0]; const deadLine = Date.vnNew(); deadLine.setHours(hours, minutes, 0); if (today > deadLine && (!mrw.notified || mrw.notified.setHours(0, 0, 0, 0) !== today.setHours(0, 0, 0, 0))) { - const email = new Email('mrw-webService-deadline', {recipient: 'agencias@verdnatura.es', lang: 'es'}); - await email.send(); + await models.NotificationQueue.create({notificationFk: 'mrw-deadline'}); await mrw.updateAttributes({notified: Date.vnNow()}); } @@ -88,10 +85,9 @@ module.exports = Self => { ); const shipmentId = Self.getTextByTag(shipmentResponse, 'NumeroEnvio'); - if (!shipmentId) - throw new UserError(Self.getTextByTag(shipmentResponse, 'Mensaje')); + if (!shipmentId) throw new UserError(Self.getTextByTag(shipmentResponse, 'Mensaje')); - const file = await mrwConfig.getLabel(shipmentId); + const file = await models.MrwConfig.getLabel(shipmentId); return {shipmentId, file}; }; diff --git a/back/methods/mrw-config/specs/createShipment.spec.js b/back/methods/mrw-config/specs/createShipment.spec.js index b96efeac4..ad168b139 100644 --- a/back/methods/mrw-config/specs/createShipment.spec.js +++ b/back/methods/mrw-config/specs/createShipment.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; const axios = require('axios'); const fs = require('fs'); -const filter = {subject: 'Superación de la Hora de Corte de MRW'}; +const filter = {notificationFk: 'mrw-deadline'}; const mockBase64Binary = 'base64BinaryString'; const ticket1 = { 'id': '44', @@ -53,15 +53,25 @@ describe('MRWConfig createShipment()', () => { await models.Expedition.create(expedition1); }); - beforeEach(() => { + afterAll(async() => { + await cleanFixtures(); + }); + + beforeEach(async() => { const mockPostResponses = [ {data: fs.readFileSync(__dirname + '/mockGetLabel.xml', 'utf-8')}, {data: fs.readFileSync(__dirname + '/mockCreateShipment.xml', 'utf-8')} ]; spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop())); + await cleanFixtures(); }); + async function cleanFixtures() { + await models.NotificationQueue.destroyAll(filter); + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: null, notified: null}); + } + async function createMrwConfig() { await models.MrwConfig.create( { @@ -75,6 +85,13 @@ describe('MRWConfig createShipment()', () => { ); } + async function getLastNotification() { + return models.NotificationQueue.findOne({ + order: 'id DESC', + where: filter + }); + } + it('should create a shipment and return a base64Binary label', async() => { const {file} = await models.MrwConfig.createShipment(expedition1.id); @@ -87,7 +104,7 @@ describe('MRWConfig createShipment()', () => { await models.MrwConfig.createShipment(expedition1.id).catch(e => { error = e; }).finally(async() => { - expect(error.message).toEqual(`Some mrwConfig parameters are not set`); + expect(error.message).toEqual(`MRW service is not configured`); }); await createMrwConfig(); @@ -118,53 +135,26 @@ describe('MRWConfig createShipment()', () => { }); it('should send mail if you are past the dead line and is not notified today', async() => { - await models.Mail.destroyAll(filter); - await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: null}); - await models.MrwConfig.createShipment(expedition1.id); + const notification = await getLastNotification(); - const mail = await models.Mail.findOne({ - order: 'id DESC', - where: filter - }); - - expect(mail.subject).toEqual(filter.subject); - - await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: null, notified: null}); + expect(notification.notificationFk).toEqual(filter.notificationFk); }); it('should send mail if you are past the dead line and it is notified from another day', async() => { - await models.Mail.destroyAll(filter); - await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: new Date()}); - await models.MrwConfig.createShipment(expedition1.id); + const notification = await getLastNotification(); - const mail = await models.Mail.findOne({ - order: 'id DESC', - where: filter - }); - - expect(mail.subject).toEqual(filter.subject); - - await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: null, notified: null}); + expect(notification.notificationFk).toEqual(filter.notificationFk); }); it('should not send mail if you are past the dead line and it is notified', async() => { - await models.Mail.destroyAll(filter); - await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: Date.vnNew()}); - await models.MrwConfig.createShipment(expedition1.id); + const notification = await getLastNotification(); - const mail = await models.Mail.findOne({ - order: 'id DESC', - where: filter - }); - - expect(mail).toEqual(null); - - await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: null, notified: null}); + expect(notification).toEqual(null); }); }); diff --git a/back/models/mrw-config.js b/back/models/mrw-config.js index 4496a9a56..c738c9c0e 100644 --- a/back/models/mrw-config.js +++ b/back/models/mrw-config.js @@ -11,7 +11,7 @@ module.exports = Self => { Self.getConfig = async function() { const mrw = await Self.app.models.MrwConfig.findOne(null); - if (!mrw) throw new UserError(`Some mrwConfig parameters are not set`); + if (!mrw) throw new UserError(`MRW service is not configured`); return mrw; }; diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 49cb17f0f..d973e94f8 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -2844,7 +2844,8 @@ INSERT INTO `util`.`notification` (`id`, `name`, `description`) (5, 'modified-entry', 'An entry has been modified'), (6, 'book-entry-deleted', 'accounting entries deleted'), (7, 'zone-included','An email to notify zoneCollisions'), - (8, 'backup-printer-selected','A backup printer has been selected'); + (8, 'backup-printer-selected','A backup printer has been selected'), + (9, 'mrw-deadline','The MRW deadline has passed'); TRUNCATE `util`.`notificationAcl`; INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) @@ -2857,7 +2858,8 @@ INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) (5, 9), (6, 9), (7, 9), - (8, 66); + (8, 66), + (9, 56); TRUNCATE `util`.`notificationQueue`; INSERT INTO `util`.`notificationQueue` (`id`, `notificationFk`, `params`, `authorFk`, `status`, `created`) diff --git a/db/versions/11086-grayCataractarum/00-firstScript.sql b/db/versions/11086-grayCataractarum/00-firstScript.sql index 20ed9d8f2..86107b159 100644 --- a/db/versions/11086-grayCataractarum/00-firstScript.sql +++ b/db/versions/11086-grayCataractarum/00-firstScript.sql @@ -1,3 +1,12 @@ -- Place your SQL code here ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS notified TIMESTAMP NULL COMMENT 'Date when it was notified that the web service deadline was exceeded'; + +INSERT IGNORE INTO util.notification + SET name = 'mrw-deadline', + description = 'The MRW deadline has passed'; + +INSERT IGNORE INTO util.notificationAcl (notificationFk, roleFK) + SELECT LAST_INSERT_ID(), r.id + FROM account.role r + WHERE r.name = 'delivery' \ No newline at end of file diff --git a/print/templates/email/mrw-webService-deadline/assets/css/import.js b/print/templates/email/mrw-deadline/assets/css/import.js similarity index 100% rename from print/templates/email/mrw-webService-deadline/assets/css/import.js rename to print/templates/email/mrw-deadline/assets/css/import.js diff --git a/print/templates/email/mrw-webService-deadline/locale/en.yml b/print/templates/email/mrw-deadline/locale/en.yml similarity index 100% rename from print/templates/email/mrw-webService-deadline/locale/en.yml rename to print/templates/email/mrw-deadline/locale/en.yml diff --git a/print/templates/email/mrw-webService-deadline/locale/es.yml b/print/templates/email/mrw-deadline/locale/es.yml similarity index 100% rename from print/templates/email/mrw-webService-deadline/locale/es.yml rename to print/templates/email/mrw-deadline/locale/es.yml diff --git a/print/templates/email/mrw-webService-deadline/mrw-webService-deadline.html b/print/templates/email/mrw-deadline/mrw-deadline.html similarity index 100% rename from print/templates/email/mrw-webService-deadline/mrw-webService-deadline.html rename to print/templates/email/mrw-deadline/mrw-deadline.html diff --git a/print/templates/email/mrw-webService-deadline/mrw-webService-deadline.js b/print/templates/email/mrw-deadline/mrw-deadline.js similarity index 83% rename from print/templates/email/mrw-webService-deadline/mrw-webService-deadline.js rename to print/templates/email/mrw-deadline/mrw-deadline.js index f010a861f..574d88a0d 100755 --- a/print/templates/email/mrw-webService-deadline/mrw-webService-deadline.js +++ b/print/templates/email/mrw-deadline/mrw-deadline.js @@ -2,7 +2,7 @@ const Component = require(`vn-print/core/component`); const emailBody = new Component('email-body'); module.exports = { - name: 'mrw-webService-deadline', + name: 'mrw-deadline', components: { 'email-body': emailBody.build(), } -- 2.40.1 From 9b118f83e5d952c0e029e2eef2b831f270f6c238 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Fri, 14 Jun 2024 17:56:24 +0200 Subject: [PATCH 213/413] fix: asociar ticketRefund refs #7586 --- modules/ticket/back/methods/sale/clone.js | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js index fa1079fbe..9185a6e75 100644 --- a/modules/ticket/back/methods/sale/clone.js +++ b/modules/ticket/back/methods/sale/clone.js @@ -145,15 +145,10 @@ module.exports = Self => { const newTicket = await models.Ticket.new(ctx, myOptions); - const ticketRefund = await models.TicketRefund.findOne({ - where: {refundTicketFk: ticketId} + await models.TicketRefund.create({ + originalTicketFk: ticketId, + refundTicketFk: newTicket.id }, myOptions); - if (negative && (withWarehouse || !ticketRefund?.id)) { - await models.TicketRefund.create({ - originalTicketFk: ticketId, - refundTicketFk: newTicket.id - }, myOptions); - } return newTicket; } -- 2.40.1 From 25afa80babc38fc421cda592c7eb05480977ecdd Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 17 Jun 2024 09:09:45 +0200 Subject: [PATCH 214/413] fix: refs #6404 remove fixtures after test --- back/methods/mrw-config/specs/createShipment.spec.js | 2 ++ modules/monitor/back/methods/sales-monitor/salesFilter.js | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/back/methods/mrw-config/specs/createShipment.spec.js b/back/methods/mrw-config/specs/createShipment.spec.js index ad168b139..883dd8f6f 100644 --- a/back/methods/mrw-config/specs/createShipment.spec.js +++ b/back/methods/mrw-config/specs/createShipment.spec.js @@ -55,6 +55,8 @@ describe('MRWConfig createShipment()', () => { afterAll(async() => { await cleanFixtures(); + await models.Ticket.destroyAll(ticket1); + await models.Expedition.destroyAll(ticket1); }); beforeEach(async() => { diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index 301e4ac35..33b37d8a4 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -162,7 +162,7 @@ module.exports = Self => { const stmts = []; let stmt; - + stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`); stmts.push(`SET SESSION optimizer_search_depth = 0`); -- 2.40.1 From 1d0b89ed526b03bf5f40b85705dcb0550b848b21 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 17 Jun 2024 09:42:16 +0200 Subject: [PATCH 215/413] refs #7519 Requested changes --- db/dump/fixtures.before.sql | 4 ++-- db/routines/vn/procedures/claimRatio_add.sql | 9 ++++++--- db/versions/11101-limeCordyline/00-firstScript.sql | 8 ++++++++ 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 60ef58861..eb165aeec 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1885,9 +1885,9 @@ INSERT INTO `vn`.`claimEnd`(`id`, `saleFk`, `claimFk`, `workerFk`, `claimDestina (1, 31, 4, 21, 2), (2, 32, 3, 21, 3); -INSERT INTO `vn`.`claimConfig`(`id`, `maxResponsibility`) +INSERT INTO `vn`.`claimConfig`(`id`, `maxResponsibility`, `monthsToRefund`, `minShipped`) VALUES - (1, 50); + (1, 5, 4, '2016-10-01'); INSERT INTO `vn`.`claimRatio`(`clientFk`, `yearSale`, `claimAmount`, `claimingRate`, `priceIncreasing`, `packingRate`) VALUES diff --git a/db/routines/vn/procedures/claimRatio_add.sql b/db/routines/vn/procedures/claimRatio_add.sql index 8d94805db..c375f8736 100644 --- a/db/routines/vn/procedures/claimRatio_add.sql +++ b/db/routines/vn/procedures/claimRatio_add.sql @@ -5,7 +5,8 @@ BEGIN * Añade a la tabla greuges todos los cargos necesario y * que luego lo utilizamos para calcular el recobro. */ - DECLARE vMonthToRefund INT DEFAULT 4; + DECLARE vMonthToRefund INT + DEFAULT (SELECT monthsToRefund FROM claimConfig); DECLARE vRecoveryGreugeType INT DEFAULT (SELECT id FROM greugeType WHERE code = 'recovery'); DECLARE vManaGreugeType INT @@ -15,7 +16,8 @@ BEGIN DECLARE vDebtComponentType INT DEFAULT (SELECT id FROM component WHERE code = 'debtCollection'); - IF vRecoveryGreugeType IS NULL + IF vMonthToRefund IS NULL + OR vRecoveryGreugeType IS NULL OR vManaGreugeType IS NULL OR vClaimGreugeType IS NULL OR vDebtComponentType IS NULL THEN @@ -87,6 +89,7 @@ BEGIN -- Recobros CREATE OR REPLACE TEMPORARY TABLE tTicketList (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY SELECT DISTINCT s.ticketFk FROM saleComponent sc JOIN sale s ON sc.saleFk = s.id @@ -97,7 +100,7 @@ BEGIN JOIN alertLevel al ON al.id = st.alertLevel WHERE sc.componentFk = vDebtComponentType AND NOT sc.isGreuge - AND t.shipped >= '2016-10-01' + AND t.shipped >= (SELECT minShipped FROM claimConfig) AND t.shipped < util.VN_CURDATE() AND al.code = 'DELIVERED'; diff --git a/db/versions/11101-limeCordyline/00-firstScript.sql b/db/versions/11101-limeCordyline/00-firstScript.sql index e9ffa1b12..d6f30ce3f 100644 --- a/db/versions/11101-limeCordyline/00-firstScript.sql +++ b/db/versions/11101-limeCordyline/00-firstScript.sql @@ -2,3 +2,11 @@ UPDATE IGNORE bs.nightTask SET `schema` = 'vn', `procedure` = 'claimRatio_add' WHERE `procedure` = 'claim_ratio_routine'; + +ALTER TABLE vn.claimConfig + ADD monthsToRefund int(11) DEFAULT NULL NULL, + ADD minShipped date DEFAULT NULL NULL; + +UPDATE IGNORE vn.claimConfig + SET monthsToRefund = 4, + minShipped = '2016-10-01'; -- 2.40.1 From 54b6ef491f02a3ff1c2d4b59e6084e06e1ac97e6 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 17 Jun 2024 10:23:30 +0200 Subject: [PATCH 216/413] refs #7409 back --- .../worker/back/models/payroll-component.json | 27 +++++++++++ modules/worker/back/models/worker-income.json | 45 +++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 modules/worker/back/models/payroll-component.json create mode 100644 modules/worker/back/models/worker-income.json diff --git a/modules/worker/back/models/payroll-component.json b/modules/worker/back/models/payroll-component.json new file mode 100644 index 000000000..92b6c3835 --- /dev/null +++ b/modules/worker/back/models/payroll-component.json @@ -0,0 +1,27 @@ +{ + "name": "PayrollComponent", + "base": "VnModel", + "options": { + "mysql": { + "table": "payrollComponent" + } + }, + "properties": { + "id": { + "id": true, + "type": "number" + }, + "name": { + "type": "string" + }, + "isSalaryAgreed": { + "type": "number" + }, + "isVariable": { + "type": "number" + }, + "isException": { + "type": "number" + } + } +} diff --git a/modules/worker/back/models/worker-income.json b/modules/worker/back/models/worker-income.json new file mode 100644 index 000000000..ae9f56604 --- /dev/null +++ b/modules/worker/back/models/worker-income.json @@ -0,0 +1,45 @@ +{ + "name": "WorkerIncome", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerIncome" + } + }, + "properties": { + "id": { + "id": true, + "type": "number" + }, + "debit": { + "type": "number" + }, + "credit": { + "type": "number" + }, + "incomeTypeFk": { + "type": "number" + }, + "paymentDate": { + "type": "date" + }, + "workerFk": { + "type": "number" + }, + "concept": { + "type": "string" + } + }, + "relations": { + "payrollComponent": { + "type": "belongsTo", + "model": "payrollComponent", + "foreignKey": "id" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "id" + } + } +} -- 2.40.1 From 4c345ffa938401daeb44b2ee20bc624e616791a5 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 17 Jun 2024 10:57:23 +0200 Subject: [PATCH 217/413] hotfix: refs #7552 item_getSimilar --- db/routines/vn/procedures/item_getSimilar.sql | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 762c25342..65407c2df 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -21,9 +21,6 @@ BEGIN CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); - -- Añadido temporalmente para que no se cuelgue la db - SET vShowType = TRUE; - WITH itemTags AS ( SELECT i.id, typeFk, @@ -38,7 +35,7 @@ BEGIN t.name, it.value FROM vn.item i - LEFT JOIN vn.itemTag it ON it.itemFk = i.id + LEFT JOIN vn.itemTag it FORCE INDEX(itemTagItemPriority) ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk WHERE i.id = vSelf @@ -68,7 +65,7 @@ BEGIN iss.visible located, b.price2 FROM vn.item i - JOIN cache.available a ON a.item_id = i.id + JOIN cache.available a FORCE INDEX (calc_id) ON a.item_id = i.id AND a.calc_id = vCalcFk LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf -- 2.40.1 From cfa0b8789859e73beef2336567325f04b75f6e39 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 17 Jun 2024 11:50:25 +0200 Subject: [PATCH 218/413] feat: refs #7296 RoutesMonitor --- modules/route/back/models/routesMonitor.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/route/back/models/routesMonitor.json b/modules/route/back/models/routesMonitor.json index a14680b5c..c5fe4c1ce 100644 --- a/modules/route/back/models/routesMonitor.json +++ b/modules/route/back/models/routesMonitor.json @@ -48,6 +48,9 @@ "priority": { "type": "number" }, + "roadmapStopFk": { + "type": "number" + }, "m3boxes": { "type": "number" }, -- 2.40.1 From 89ea931d9c964e553d332c4b67e8891dd5baf515 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 17 Jun 2024 12:19:59 +0200 Subject: [PATCH 219/413] feat: refs #6744 add locale & drop verification --- loopback/locale/es.json | 6 +++--- modules/account/back/models/account.js | 6 +++++- modules/worker/front/descriptor/index.html | 2 +- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index e876c1bbb..188f33631 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -351,7 +351,7 @@ "You are not allowed to modify the alias": "No estás autorizado a modificar el alias", "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", "The line could not be marked": "La linea no puede ser marcada", - "This password can only be changed by the user themselves": "Esta contraseña solo puede ser modificada por el propio usuario", + "Through this procedure, it is not possible to modify the password of users with verified email": "Mediante este procedimiento, no es posible modificar la contraseña de usuarios con correo verificado", "They're not your subordinate": "No es tu subordinado/a.", "No results found": "No se han encontrado resultados", "InvoiceIn is already booked": "La factura recibida está contabilizada", @@ -359,10 +359,10 @@ "Select ticket or client": "Elija un ticket o un client", "It was not able to create the invoice": "No se pudo crear la factura", "ticketCommercial": "El ticket {{ ticket }} para el vendedor {{ salesMan }} está en preparación. (mensaje generado automáticamente)", - "Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE", + "Incoterms and Customs agent are required for a non UEE member": "Se requieren Incoterms y agente de aduanas para un no miembro de la UEE", "You can not use the same password": "No puedes usar la misma contraseña", "This PDA is already assigned to another user": "Este PDA ya está asignado a otro usuario", "You can only have one PDA": "Solo puedes tener un PDA", "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono" -} +} \ No newline at end of file diff --git a/modules/account/back/models/account.js b/modules/account/back/models/account.js index ceb26053c..7800d3e44 100644 --- a/modules/account/back/models/account.js +++ b/modules/account/back/models/account.js @@ -13,7 +13,11 @@ module.exports = Self => { Self.setUnverifiedPassword = async(id, pass, options) => { const {emailVerified} = await models.VnUser.findById(id, {fields: ['emailVerified']}, options); - if (emailVerified) throw new ForbiddenError('This password can only be changed by the user themselves'); + if (emailVerified) { + throw new ForbiddenError( + 'Through this procedure, it is not possible to modify the password of users with verified email' + ); + } await models.VnUser.setPassword(id, pass, options); }; diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index 73332efac..a77f986ed 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -11,7 +11,7 @@ ? 'Click to allow the user to be disabled' : 'Click to exclude the user from getting disabled'}} - + Change password -- 2.40.1 From 4bc62a30bdb8a2e3e530de88cabea13918e77d53 Mon Sep 17 00:00:00 2001 From: jorgep Date: Mon, 17 Jun 2024 12:23:01 +0200 Subject: [PATCH 220/413] fix: refs #6744 back test --- modules/worker/back/methods/worker/specs/setPassword.spec.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker/specs/setPassword.spec.js b/modules/worker/back/methods/worker/specs/setPassword.spec.js index 8d152bdd1..b9b20ce94 100644 --- a/modules/worker/back/methods/worker/specs/setPassword.spec.js +++ b/modules/worker/back/methods/worker/specs/setPassword.spec.js @@ -42,7 +42,9 @@ describe('worker setPassword()', () => { await tx.rollback(); } catch (e) { - expect(e.message).toEqual(`This password can only be changed by the user themselves`); + expect(e.message).toEqual( + 'Through this procedure, it is not possible to modify the password of users with verified email' + ); await tx.rollback(); } }); -- 2.40.1 From eaaf83561c8bf949cb4dcda8252ffcd4abed9d91 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 17 Jun 2024 13:03:02 +0200 Subject: [PATCH 221/413] fix: refs #5995 Optimized downloadCmrsZip --- modules/route/back/methods/route/downloadCmrsZip.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js index c6934edca..895ff7a16 100644 --- a/modules/route/back/methods/route/downloadCmrsZip.js +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -41,14 +41,16 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - ids = ids.split(','); - - for (const id of ids) { + const downloadAddZip = async id => { ctx.args = ctx.args || {}; ctx.args.id = Number(id); const [data] = await models.Route.cmr(ctx, myOptions); zip.file(`${id}.pdf`, data, {binary: true}); - } + }; + + ids = ids.split(','); + const promises = ids.map(id => downloadAddZip(id)); + await Promise.all(promises); const zipStream = zip.generateNodeStream({streamFiles: true}); return [zipStream, 'application/zip', `filename="cmrs.zip"`]; }; -- 2.40.1 From 131b44305daf3b7f89b81bb46e90538bffc5e958 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 17 Jun 2024 13:38:40 +0200 Subject: [PATCH 222/413] hotfix: refs #7552 item_getSimilar --- db/routines/vn/procedures/item_getSimilar.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 65407c2df..0bc84f8c0 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -65,7 +65,7 @@ BEGIN iss.visible located, b.price2 FROM vn.item i - JOIN cache.available a FORCE INDEX (calc_id) ON a.item_id = i.id + JOIN cache.available a FORCE INDEX (calc_id_4) ON a.item_id = i.id AND a.calc_id = vCalcFk LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf -- 2.40.1 From fa8c1b38797bae32a4d8fd926140b93a50e1b313 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 17 Jun 2024 13:50:07 +0200 Subject: [PATCH 223/413] acls, fixtures, models --- db/dump/fixtures.before.sql | 19 +++++++++++++++++++ .../11103-limeBirch/00-firstScript.sql | 8 ++++++++ modules/worker/back/model-config.json | 6 ++++++ modules/worker/back/models/worker-income.json | 2 +- 4 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 db/versions/11103-limeBirch/00-firstScript.sql diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 058c5cd2a..7890fb7e8 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3882,3 +3882,22 @@ INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHoli (1, '2001-05-17', 1, 5), (1, '2001-05-18', 1, 5); +INSERT INTO vn.payrollComponent +(id, name, isSalaryAgreed, isVariable, isException) +VALUES(1, 'Salario1', 1, 0, 0); +INSERT INTO vn.payrollComponent +(id, name, isSalaryAgreed, isVariable, isException) +VALUES(2, 'Salario2', 1, 1, 0); +INSERT INTO vn.payrollComponent +(id, name, isSalaryAgreed, isVariable, isException) +VALUES(3, 'Salario3', 1, 0, 1); + + +INSERT INTO vn.workerIncome +(debit, credit, incomeTypeFk, paymentDate, workerFk, concept) +VALUES(1000.00, 900.00, 2, '2000-01-01', 1106, NULL); +INSERT INTO vn.workerIncome +(debit, credit, incomeTypeFk, paymentDate, workerFk, concept) +VALUES(1001.00, 800.00, 2, '2000-01-01', 1106, NULL); + + diff --git a/db/versions/11103-limeBirch/00-firstScript.sql b/db/versions/11103-limeBirch/00-firstScript.sql new file mode 100644 index 000000000..5c55e4087 --- /dev/null +++ b/db/versions/11103-limeBirch/00-firstScript.sql @@ -0,0 +1,8 @@ +-- Place your SQL code here +INSERT INTO salix.ACL +(id, model, property, accessType, permission, principalType, principalId) +VALUES(872, 'WorkerIncome', '*', '*', 'ALLOW', 'ROLE', 'hr'); +INSERT INTO salix.ACL +(id, model, property, accessType, permission, principalType, principalId) +VALUES(873, 'PayrollComponent', '*', '*', 'ALLOW', 'ROLE', 'hr'); + diff --git a/modules/worker/back/model-config.json b/modules/worker/back/model-config.json index b7c355511..46c062775 100644 --- a/modules/worker/back/model-config.json +++ b/modules/worker/back/model-config.json @@ -124,6 +124,12 @@ }, "Locker": { "dataSource": "vn" + }, + "PayrollComponent": { + "dataSource": "vn" + }, + "WorkerIncome": { + "dataSource": "vn" } } diff --git a/modules/worker/back/models/worker-income.json b/modules/worker/back/models/worker-income.json index ae9f56604..1ba9c1738 100644 --- a/modules/worker/back/models/worker-income.json +++ b/modules/worker/back/models/worker-income.json @@ -37,7 +37,7 @@ "foreignKey": "id" }, "worker": { - "type": "belongsTo", + "type": "hasMany", "model": "Worker", "foreignKey": "id" } -- 2.40.1 From e8c7b55329c64c90e17ee8f5765d5059dfab711f Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 17 Jun 2024 14:17:43 +0200 Subject: [PATCH 224/413] fix(WorkerIncome): refs #7409 fix models --- modules/worker/back/models/worker-income.json | 10 +++++----- modules/worker/back/models/worker.json | 7 ++++++- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/modules/worker/back/models/worker-income.json b/modules/worker/back/models/worker-income.json index 1ba9c1738..3a7f3407a 100644 --- a/modules/worker/back/models/worker-income.json +++ b/modules/worker/back/models/worker-income.json @@ -33,13 +33,13 @@ "relations": { "payrollComponent": { "type": "belongsTo", - "model": "payrollComponent", + "model": "PayrollComponent", "foreignKey": "id" }, - "worker": { - "type": "hasMany", + "worker": { + "type": "belongsTo", "model": "Worker", - "foreignKey": "id" - } + "foreignKey": "workerFk" + } } } diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 4796c6373..4d3f57b9f 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -115,6 +115,11 @@ "type": "hasMany", "model": "Locker", "foreignKey": "workerFk" + }, + "incomes": { + "type": "hasMany", + "model": "WorkerIncome", + "foreignKey": "workerFk" } }, "acls": [ @@ -126,4 +131,4 @@ "principalId": "$owner" } ] -} \ No newline at end of file +} -- 2.40.1 From ce709798b4005d40d34dff94a9e2c2098b75873e Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 17 Jun 2024 14:51:04 +0200 Subject: [PATCH 225/413] hotfix: refs #7486 collection_new debug error --- db/routines/util/procedures/debugAdd.sql | 5 ++++- db/routines/vn/procedures/collection_new.sql | 16 ++++++++++++---- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/db/routines/util/procedures/debugAdd.sql b/db/routines/util/procedures/debugAdd.sql index 8c690376e..a8f7b3aa2 100644 --- a/db/routines/util/procedures/debugAdd.sql +++ b/db/routines/util/procedures/debugAdd.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`debugAdd`(vVariable VARCHAR(255), vValue VARCHAR(255)) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `util`.`debugAdd`( + vVariable VARCHAR(255), + vValue TEXT +) MODIFIES SQL DATA BEGIN /** diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index fa947ddef..b022d8dcc 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -28,6 +28,8 @@ BEGIN DECLARE vLockName VARCHAR(215); DECLARE vLockTime INT DEFAULT 30; DECLARE vFreeWagonFk INT; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; DECLARE c1 CURSOR FOR SELECT ticketFk, `lines`, m3 @@ -47,12 +49,18 @@ BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; + IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); - CALL util.debugAdd(JSON_OBJECT( - 'type', 'releaseLock', - 'userFk', vUserFk - ), vLockName); -- Tmp + CALL util.debugAdd('collection_new', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk + )); -- Tmp END IF; RESIGNAL; -- 2.40.1 From 3e25fff90fbf4cad5c93ffe4c5798276654a177c Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 17 Jun 2024 15:50:58 +0200 Subject: [PATCH 226/413] refs #7409 acl --- db/versions/11103-limeBirch/00-firstScript.sql | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/db/versions/11103-limeBirch/00-firstScript.sql b/db/versions/11103-limeBirch/00-firstScript.sql index 5c55e4087..9dcfb518c 100644 --- a/db/versions/11103-limeBirch/00-firstScript.sql +++ b/db/versions/11103-limeBirch/00-firstScript.sql @@ -1,8 +1,9 @@ -- Place your SQL code here INSERT INTO salix.ACL -(id, model, property, accessType, permission, principalType, principalId) -VALUES(872, 'WorkerIncome', '*', '*', 'ALLOW', 'ROLE', 'hr'); +(model, property, accessType, permission, principalType, principalId) +VALUES('WorkerIncome', '*', '*', 'ALLOW', 'ROLE', 'hr'); INSERT INTO salix.ACL -(id, model, property, accessType, permission, principalType, principalId) -VALUES(873, 'PayrollComponent', '*', '*', 'ALLOW', 'ROLE', 'hr'); - +(model, property, accessType, permission, principalType, principalId) +VALUES('PayrollComponent', '*', '*', 'ALLOW', 'ROLE', 'hr'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('WorkerIncome','__get__workerIncomes','*','ALLOW','ROLE','hr'); -- 2.40.1 From 671290b9a01fdb33115350fbd84ae602d4e03698 Mon Sep 17 00:00:00 2001 From: ivanm Date: Mon, 17 Jun 2024 16:45:51 +0200 Subject: [PATCH 227/413] refs #7313 delete vn.itemPackaging.workerFk --- db/versions/11104-wheatErica/00-firstScript.sql | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 db/versions/11104-wheatErica/00-firstScript.sql diff --git a/db/versions/11104-wheatErica/00-firstScript.sql b/db/versions/11104-wheatErica/00-firstScript.sql new file mode 100644 index 000000000..11811f399 --- /dev/null +++ b/db/versions/11104-wheatErica/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.ticketPackaging DROP FOREIGN KEY ticketPackaging_fk3; +ALTER TABLE vn.ticketPackaging DROP COLUMN workerFk; \ No newline at end of file -- 2.40.1 From eedcdb54fad2773fba8d4e3f5e985a327a894a6e Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 17 Jun 2024 19:50:51 +0200 Subject: [PATCH 228/413] feat hasItemOlder refs#6964 --- db/versions/11106-salmonPhormium/00-firstScript.sql | 9 +++++++++ .../item/back/methods/item-shelving/getListItemNewer.js | 9 ++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) create mode 100644 db/versions/11106-salmonPhormium/00-firstScript.sql diff --git a/db/versions/11106-salmonPhormium/00-firstScript.sql b/db/versions/11106-salmonPhormium/00-firstScript.sql new file mode 100644 index 000000000..b7cd5de4c --- /dev/null +++ b/db/versions/11106-salmonPhormium/00-firstScript.sql @@ -0,0 +1,9 @@ +-- Place your SQL code here + +USE vn; + +ALTER TABLE vn.productionConfig ADD sectorFromCode varchar(11) NULL COMMENT 'Sector origen que se revisa ítems más nuevos al parkinear'; +ALTER TABLE vn.productionConfig ADD sectorToCode varchar(11) NULL COMMENT 'Sector destino que se revisa ítems más nuevos al parkinear'; + +ALTER TABLE vn.productionConfig ADD CONSTRAINT productionConfig_sector_FK FOREIGN KEY (sectorFromCode) REFERENCES vn.sector(code) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE vn.productionConfig ADD CONSTRAINT productionConfig_sector_FK_1 FOREIGN KEY (sectorToCode) REFERENCES vn.sector(code) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/modules/item/back/methods/item-shelving/getListItemNewer.js b/modules/item/back/methods/item-shelving/getListItemNewer.js index a6ab0e5f1..3978fa26e 100644 --- a/modules/item/back/methods/item-shelving/getListItemNewer.js +++ b/modules/item/back/methods/item-shelving/getListItemNewer.js @@ -35,7 +35,8 @@ module.exports = Self => { SELECT COUNT(p.id) parkingToReview FROM vn.parking p JOIN vn.sector s ON s.id = p.sectorFk - WHERE p.code = ? AND s.code = "CAMARA SECTOR D";`, + JOIN vn.productionConfig pc + WHERE p.code = ? AND s.code = pc.sectorToCode;`, [parking], myOptions); if (isParkingToReview[0]['parkingToReview'] > 0) { @@ -46,15 +47,17 @@ module.exports = Self => { JOIN vn.shelving sh ON sh.code = is2.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk - WHERE is2.shelvingFk = ? AND s.code = "NAVE ALGEMESI" + JOIN vn.productionConfig pc + WHERE is2.shelvingFk = ? AND s.code = c.sectorFromCode ), tItemInSector AS ( SELECT is2.itemFk, is2.created, is2.shelvingFk FROM vn.itemShelving is2 JOIN vn.shelving sh ON sh.code = is2.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.productionConfig pc WHERE is2.shelvingFk <> ? - AND s.code = "NAVE ALGEMESI") + AND s.code = c.sectorFromCode) SELECT ti.itemFK, tis.shelvingFk FROM tItemShelving ti JOIN tItemInSector tis ON tis.itemFk = ti.itemFk -- 2.40.1 From 7566ca1acb65a23fa234fc8e2b8fccd67f90c725 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 18 Jun 2024 08:21:38 +0200 Subject: [PATCH 229/413] build: increase version 2428 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8b8281e0d..95d696fc3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.26.0", + "version": "24.28.0", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", -- 2.40.1 From 9fc027a3c646953b4f364e7df13512d082d76e1b Mon Sep 17 00:00:00 2001 From: Pako Date: Tue, 18 Jun 2024 08:24:06 +0200 Subject: [PATCH 230/413] tickets deleted excluded --- db/routines/vn/procedures/supplierPackaging_ReportSource.sql | 2 ++ 1 file changed, 2 insertions(+) diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index a3401843a..751ee58f0 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -99,6 +99,7 @@ BEGIN WHERE su.id = vSupplierFk AND t.shipped < vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY s.itemFk UNION ALL SELECT vSupplierFk, @@ -140,6 +141,7 @@ BEGIN WHERE su.id = vSupplierFk AND t.shipped >= vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY p.itemFk ORDER BY itemFk, landed, entryFk ) sub -- 2.40.1 From 46cd20a1fde5601fd9aa1642d5f1bfa79008d591 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 18 Jun 2024 08:24:15 +0200 Subject: [PATCH 231/413] feat hasItemOlder refs#6964 --- .../methods/item-shelving/getListItemNewer.js | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/modules/item/back/methods/item-shelving/getListItemNewer.js b/modules/item/back/methods/item-shelving/getListItemNewer.js index 3978fa26e..708b81108 100644 --- a/modules/item/back/methods/item-shelving/getListItemNewer.js +++ b/modules/item/back/methods/item-shelving/getListItemNewer.js @@ -17,7 +17,7 @@ module.exports = Self => { }, ], returns: { - type: 'Object', + type: 'Array', root: true }, http: { @@ -31,7 +31,7 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const isParkingToReview = await Self.rawSql(` + const [isParkingToReview] = await Self.rawSql(` SELECT COUNT(p.id) parkingToReview FROM vn.parking p JOIN vn.sector s ON s.id = p.sectorFk @@ -39,8 +39,9 @@ module.exports = Self => { WHERE p.code = ? AND s.code = pc.sectorToCode;`, [parking], myOptions); - if (isParkingToReview[0]['parkingToReview'] > 0) { - const result = await Self.rawSql(` + if (isParkingToReview['parkingToReview'] < 1) return []; + + const result = await Self.rawSql(` WITH tItemShelving AS( SELECT is2.itemFk, is2.created, p.sectorFK, is2.id FROM vn.itemShelving is2 @@ -63,9 +64,7 @@ module.exports = Self => { JOIN tItemInSector tis ON tis.itemFk = ti.itemFk JOIN vn.productionConfig pc WHERE ti.created > tis.created + INTERVAL pc.itemOlderReviewHours HOUR;`, - [shelvingFk, shelvingFk], myOptions); - return result; - } else - return []; + [shelvingFk, shelvingFk], myOptions); + return result; }; }; -- 2.40.1 From 52a34c8f2db156b773d66a0c80512fda504b314e Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 18 Jun 2024 09:18:09 +0200 Subject: [PATCH 232/413] refs #7409 fix acls --- db/versions/11103-limeBirch/00-firstScript.sql | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/db/versions/11103-limeBirch/00-firstScript.sql b/db/versions/11103-limeBirch/00-firstScript.sql index 9dcfb518c..2c0a396ce 100644 --- a/db/versions/11103-limeBirch/00-firstScript.sql +++ b/db/versions/11103-limeBirch/00-firstScript.sql @@ -1,9 +1,6 @@ -- Place your SQL code here -INSERT INTO salix.ACL -(model, property, accessType, permission, principalType, principalId) -VALUES('WorkerIncome', '*', '*', 'ALLOW', 'ROLE', 'hr'); -INSERT INTO salix.ACL -(model, property, accessType, permission, principalType, principalId) -VALUES('PayrollComponent', '*', '*', 'ALLOW', 'ROLE', 'hr'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('WorkerIncome','__get__workerIncomes','*','ALLOW','ROLE','hr'); +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) + VALUES + ('WorkerIncome', '*', '*', 'ALLOW', 'ROLE', 'hr'), + ('PayrollComponent', '*', '*', 'ALLOW', 'ROLE', 'hr'), + ('Worker', '__get__incomes', '*', 'ALLOW', 'ROLE', 'hr'); -- 2.40.1 From 3070d1ef0182b4e3d098cdd8c2b32bfd93176314 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 18 Jun 2024 10:04:21 +0200 Subject: [PATCH 233/413] refactor: refs #6238 drop useless round --- .../methods/travel/extraCommunityFilter.js | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/modules/travel/back/methods/travel/extraCommunityFilter.js b/modules/travel/back/methods/travel/extraCommunityFilter.js index 107bf6f39..dcb704ff5 100644 --- a/modules/travel/back/methods/travel/extraCommunityFilter.js +++ b/modules/travel/back/methods/travel/extraCommunityFilter.js @@ -139,18 +139,18 @@ module.exports = Self => { IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000 ) as DECIMAL(10,0) ) as volumeKg, - ROUND(GREATEST( - CAST(SUM(b.weight * b.stickers) AS INT), - CAST( - SUM(vc.aerealVolumetricDensity * - b.stickers * - IF(pkg.volume, - pkg.volume, - pkg.width * pkg.depth * pkg.height - ) / 1000000 - ) AS INT + GREATEST( + CAST(SUM(b.weight * b.stickers) AS INT), + CAST( + SUM(vc.aerealVolumetricDensity * + b.stickers * + IF(pkg.volume, + pkg.volume, + pkg.width * pkg.depth * pkg.height + ) / 1000000 + ) AS INT ) - ) / t.kg * 100, 0) percentageKg + / t.kg * 100, 0) percentageKg FROM travel t LEFT JOIN supplier s ON s.id = t.cargoSupplierFk LEFT JOIN entry e ON e.travelFk = t.id -- 2.40.1 From 239814e6b4315009f404a96457a41bd71766ddb3 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 18 Jun 2024 10:08:40 +0200 Subject: [PATCH 234/413] feat hasItemOlder refs#6964 --- back/models/production-config.json | 12 ++++-- .../11106-salmonPhormium/00-firstScript.sql | 8 ++-- .../methods/item-shelving/getListItemNewer.js | 4 +- .../specs/getListItemNewer.spec.js | 39 +++++++++++-------- 4 files changed, 37 insertions(+), 26 deletions(-) diff --git a/back/models/production-config.json b/back/models/production-config.json index 3800dbbf2..2fc6d71ff 100644 --- a/back/models/production-config.json +++ b/back/models/production-config.json @@ -3,17 +3,23 @@ "base": "VnModel", "options": { "mysql": { - "table": "productionConfig" + "table": "productionConfig" } - }, + }, "properties": { "id": { "type": "number", "required": true, "id": true }, + "sectorFromCode": { + "type": "string" + }, + "sectorToCode": { + "type": "string" + }, "backupPrinterNotificationDelay": { "type": "string" } } -} +} \ No newline at end of file diff --git a/db/versions/11106-salmonPhormium/00-firstScript.sql b/db/versions/11106-salmonPhormium/00-firstScript.sql index b7cd5de4c..9f63e6075 100644 --- a/db/versions/11106-salmonPhormium/00-firstScript.sql +++ b/db/versions/11106-salmonPhormium/00-firstScript.sql @@ -2,8 +2,8 @@ USE vn; -ALTER TABLE vn.productionConfig ADD sectorFromCode varchar(11) NULL COMMENT 'Sector origen que se revisa ítems más nuevos al parkinear'; -ALTER TABLE vn.productionConfig ADD sectorToCode varchar(11) NULL COMMENT 'Sector destino que se revisa ítems más nuevos al parkinear'; +ALTER TABLE vn.productionConfig ADD sectorFromCode varchar(15) NULL COMMENT 'Sector origen que se revisa ítems más nuevos al parkinear'; +ALTER TABLE vn.productionConfig ADD sectorToCode varchar(15) NULL COMMENT 'Sector destino que se revisa ítems más nuevos al parkinear'; -ALTER TABLE vn.productionConfig ADD CONSTRAINT productionConfig_sector_FK FOREIGN KEY (sectorFromCode) REFERENCES vn.sector(code) ON DELETE CASCADE ON UPDATE CASCADE; -ALTER TABLE vn.productionConfig ADD CONSTRAINT productionConfig_sector_FK_1 FOREIGN KEY (sectorToCode) REFERENCES vn.sector(code) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE vn.productionConfig ADD CONSTRAINT productionConfig_sector_FK FOREIGN KEY (sectorFromCode) REFERENCES vn.sector(code) ON DELETE RESTRICT ON UPDATE CASCADE; +ALTER TABLE vn.productionConfig ADD CONSTRAINT productionConfig_sector_FK_1 FOREIGN KEY (sectorToCode) REFERENCES vn.sector(code) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/modules/item/back/methods/item-shelving/getListItemNewer.js b/modules/item/back/methods/item-shelving/getListItemNewer.js index 708b81108..1702bb05b 100644 --- a/modules/item/back/methods/item-shelving/getListItemNewer.js +++ b/modules/item/back/methods/item-shelving/getListItemNewer.js @@ -49,7 +49,7 @@ module.exports = Self => { JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk JOIN vn.productionConfig pc - WHERE is2.shelvingFk = ? AND s.code = c.sectorFromCode + WHERE is2.shelvingFk = ? AND s.code = pc.sectorFromCode ), tItemInSector AS ( SELECT is2.itemFk, is2.created, is2.shelvingFk FROM vn.itemShelving is2 @@ -58,7 +58,7 @@ module.exports = Self => { JOIN vn.sector s ON s.id = p.sectorFk JOIN vn.productionConfig pc WHERE is2.shelvingFk <> ? - AND s.code = c.sectorFromCode) + AND s.code = pc.sectorFromCode) SELECT ti.itemFK, tis.shelvingFk FROM tItemShelving ti JOIN tItemInSector tis ON tis.itemFk = ti.itemFk diff --git a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js index 5f0f7d826..15c480992 100644 --- a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js @@ -2,31 +2,36 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getListItemNewer()', () => { - fit('should return true because there is an older item', async() => { + it('should return true because there is an older item', async() => { const shelving = 'NCC'; const parking = 'A-47-1'; - const sectorCam = 1; - const sectorCamCode = 'CAMARA SECTOR D'; - const sectorCamHigh = 9991; - const sectorCamHighCode = 'NAVE ALGEMESI'; + + const sectorCamHighCode = 'CAMARA SECTOR D'; + const sectorCamCode = 'NAVE ALGEMESI'; + + const sectorCamCodeHighId = 1; + const sectorCamCodeId = 9991; const tx = await models.Sector.beginTransaction({}); const myOptions = {transaction: tx}; - const filter = {where: {id: sectorCam}}; - const filterHigh = {where: {id: sectorCamHigh}}; - try { - const sectorCamBefore = await models.Sector.findOne(filter, myOptions); - - await sectorCamBefore.updateAttributes({ - code: sectorCamCode - }, myOptions); - - const sectorCamHighBefore = await models.Sector.findOne(filterHigh, myOptions); - await sectorCamHighBefore.updateAttributes({ + const sectorHighCam = await models.Sector.findById(sectorCamCodeHighId, null, myOptions); + await sectorHighCam.updateAttributes({ code: sectorCamHighCode - }, myOptions); + }); + + const sectorCam = await models.Sector.findById(sectorCamCodeId, null, myOptions); + await sectorCam.updateAttributes({ + code: sectorCamCode + }); + + const config = await models.ProductionConfig.findOne(); + + await config.updateAttributes({ + sectorToCode: sectorCamHighCode, + sectorFromCode: sectorCamCode + }); const result = await models.ItemShelving.getListItemNewer(shelving, parking, myOptions); -- 2.40.1 From 2b1de271a9d9b08813705466f931e7928e81b471 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 18 Jun 2024 11:03:30 +0200 Subject: [PATCH 235/413] refs #7552 Added force vShowType true --- db/routines/vn/procedures/item_getSimilar.sql | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 0bc84f8c0..762c25342 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -21,6 +21,9 @@ BEGIN CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); + -- Añadido temporalmente para que no se cuelgue la db + SET vShowType = TRUE; + WITH itemTags AS ( SELECT i.id, typeFk, @@ -35,7 +38,7 @@ BEGIN t.name, it.value FROM vn.item i - LEFT JOIN vn.itemTag it FORCE INDEX(itemTagItemPriority) ON it.itemFk = i.id + LEFT JOIN vn.itemTag it ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk WHERE i.id = vSelf @@ -65,7 +68,7 @@ BEGIN iss.visible located, b.price2 FROM vn.item i - JOIN cache.available a FORCE INDEX (calc_id_4) ON a.item_id = i.id + JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vCalcFk LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf -- 2.40.1 From 6cf7c5867124fdb21f24f5242a621b398bf7c1e0 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 18 Jun 2024 12:59:55 +0200 Subject: [PATCH 236/413] fix: refs #6238 use scheme --- .../11102-wheatCarnation/00-createTravelKgPercentage.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql b/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql index 9df89d869..6c8bb4784 100644 --- a/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql +++ b/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql @@ -1,9 +1,9 @@ -CREATE TABLE IF NOT EXISTS travelKgPercentage ( +CREATE TABLE IF NOT EXISTS vn.travelKgPercentage ( value INT(3) PRIMARY KEY, className VARCHAR(50) ); -INSERT INTO travelKgPercentage (value, className) +INSERT INTO vn.travelKgPercentage (value, className) VALUES (80, 'primary'), (100, 'alert'); -- 2.40.1 From ae01fb6440f987a442c5d511362722b57cfe267f Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 18 Jun 2024 17:00:15 +0200 Subject: [PATCH 237/413] hotFix delete unique refs #6281 --- .../11109-whiteCarnation/00-firstScript.sql | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 db/versions/11109-whiteCarnation/00-firstScript.sql diff --git a/db/versions/11109-whiteCarnation/00-firstScript.sql b/db/versions/11109-whiteCarnation/00-firstScript.sql new file mode 100644 index 000000000..a1ff19815 --- /dev/null +++ b/db/versions/11109-whiteCarnation/00-firstScript.sql @@ -0,0 +1,14 @@ +-- Place your SQL code here + +USE vn; + +ALTER TABLE vn.itemShelving DROP FOREIGN KEY itemShelvingBuy_FK; +ALTER TABLE vn.itemShelving DROP FOREIGN KEY itemShelving_fk2; +ALTER TABLE vn.itemShelving DROP INDEX itemShelving_UN; + +ALTER TABLE vn.itemShelving ADD CONSTRAINT itemShelving_fk2 FOREIGN KEY (shelvingFk) REFERENCES vn.shelving(code) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE vn.itemShelving ADD CONSTRAINT itemShelvingBuy_FK FOREIGN KEY (buyFk) REFERENCES vn.buy(id) ON DELETE RESTRICT ON UPDATE RESTRICT; + + + + -- 2.40.1 From bf62f40c87cb72d61981d1ae8a5c73b9a86ab172 Mon Sep 17 00:00:00 2001 From: Pako Date: Wed, 19 Jun 2024 07:17:25 +0200 Subject: [PATCH 238/413] actualizada la rama --- .../vn/procedures/supplierPackaging_ReportSource.sql | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index 751ee58f0..d12ba9d4e 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -5,10 +5,10 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplierPackaging_R ) BEGIN /** -* Selecciona los embalajes de un proveedor a partir de una fecha +* Create a report with packaging balance * -* @param vFromDated Fecha de la que partir -* @param vSupplierFk Id del proveedor +* @param vFromDated Starting date +* @param vSupplierFk Supplier ID */ SET @vBalance = 0; SET @vItemFk = NULL; -- 2.40.1 From 1fa0a841da97f7d56d0e097e348fba941403ab61 Mon Sep 17 00:00:00 2001 From: Pako Date: Wed, 19 Jun 2024 07:26:30 +0200 Subject: [PATCH 239/413] TP previous --- db/routines/vn/procedures/supplierPackaging_ReportSource.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index d12ba9d4e..7cc72848f 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -139,7 +139,7 @@ BEGIN JOIN client c ON c.id = t.clientFk JOIN supplier su ON su.nif = c.fi WHERE su.id = vSupplierFk - AND t.shipped >= vFromDated + AND t.shipped < vFromDated AND p.isPackageReturnable AND NOT t.isDeleted GROUP BY p.itemFk -- 2.40.1 From df4b3add8ddcea3596d66915d708cea5500754ca Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 19 Jun 2024 07:59:45 +0200 Subject: [PATCH 240/413] fix: refs #6408 quito state.js --- .../back/methods/ticket/specs/state.spec.js | 36 ++++++++++- modules/ticket/back/methods/ticket/state.js | 64 +------------------ 2 files changed, 38 insertions(+), 62 deletions(-) diff --git a/modules/ticket/back/methods/ticket/specs/state.spec.js b/modules/ticket/back/methods/ticket/specs/state.spec.js index d908aa2ef..58a407c4e 100644 --- a/modules/ticket/back/methods/ticket/specs/state.spec.js +++ b/modules/ticket/back/methods/ticket/specs/state.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -describe('ticket state()', () => { +xdescribe('ticket state()', () => { const salesPersonId = 18; const employeeId = 1; const productionId = 49; @@ -113,6 +113,7 @@ describe('ticket state()', () => { try { const options = {transaction: tx}; + spyOn(models.Chat, 'sendCheckingPresence').and.callThrough(); const ticket = await models.Ticket.create(sampleTicket, options); activeCtx.accessToken.userId = salesPersonId; const assignedState = await models.State.findOne({where: {code: 'PICKER_DESIGNED'}}, options); @@ -124,6 +125,7 @@ describe('ticket state()', () => { expect(resAssigned.userFk).toBe(paramsAssigned.userFk); expect(resAssigned.userFk).toBe(1); expect(resAssigned.id).toBeDefined(); + expect(models.Chat.sendCheckingPresence).not.toHaveBeenCalled(); activeCtx.accessToken.userId = productionId; const packedState = await models.State.findOne({where: {code: 'PACKED'}}, options); @@ -183,5 +185,37 @@ describe('ticket state()', () => { throw e; } }); + + it('should not call sendCheckingPresence if sales.length is 0 because quantities are equal', async() => { + const tx = await models.TicketTracking.beginTransaction({}); + spyOn(models.Chat, 'sendCheckingPresence').and.callThrough(); + + try { + const options = {transaction: tx}; + const ticket = await models.Ticket.create(sampleTicket, options); + activeCtx.accessToken.userId = productionId; + + const sampleSale = { + ticketFk: ticket.id, + itemFk: 1, + concept: 'Test', + quantity: 10, + originalQuantity: 10 + }; + await models.Sale.create(sampleSale, options); + + const packedState = await models.State.findOne({where: {code: 'PACKED'}}, options); + const params = {ticketFk: ticket.id, stateFk: packedState.id}; + + await models.Ticket.state(ctx, params, options); + + expect(models.Chat.sendCheckingPresence).not.toHaveBeenCalled(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); diff --git a/modules/ticket/back/methods/ticket/state.js b/modules/ticket/back/methods/ticket/state.js index 1e6069b79..fea9475f8 100644 --- a/modules/ticket/back/methods/ticket/state.js +++ b/modules/ticket/back/methods/ticket/state.js @@ -26,7 +26,6 @@ module.exports = Self => { const models = Self.app.models; const myOptions = {}; let tx; - let newStateOrder; if (typeof options == 'object') Object.assign(myOptions, options); @@ -41,16 +40,11 @@ module.exports = Self => { throw new UserError('State cannot be blank'); if (params.stateFk) { - const {code, order} = await models.State.findById( - params.stateFk, - {fields: ['code', 'order']}, - myOptions); + const {code} = await models.State.findById(params.stateFk, {fields: ['code']}, myOptions); params.code = code; - newStateOrder = order; } else { - const {id, order} = await models.State.findOne({where: {code: params.code}}, myOptions); + const {id} = await models.State.findOne({where: {code: params.code}}, myOptions); params.stateFk = id; - newStateOrder = order; } if (!params.userFk) { @@ -70,59 +64,7 @@ module.exports = Self => { if ((ticketState && !oldStateAllowed) || !newStateAllowed) throw new UserError(`You don't have enough privileges`, 'ACCESS_DENIED'); - const ticket = await models.Ticket.findById(params.ticketFk, { - include: [{ - relation: 'client', - scope: { - fields: ['salesPersonFk'] - } - }], - fields: ['id', 'clientFk'] - }, myOptions); - - const salesPersonFk = ticket.client().salesPersonFk; - const stateChecked = await models.State.findOne({fields: ['order'], where: {code: 'CHECKED'}}); - - if (salesPersonFk && newStateOrder >= stateChecked.order) { - const sales = await Self.rawSql(` - SELECT DISTINCT s.id, - s.itemFk, - s.concept, - s.originalQuantity AS oldQuantity, - s.quantity AS newQuantity - FROM vn.sale s - WHERE s.ticketFk = ? - AND s.originalQuantity IS NOT NULL - AND s.originalQuantity <> s.quantity - `, [params.ticketFk], myOptions); - - if (sales.length) { - let changes = ''; - const url = await models.Url.getUrl(); - const $t = ctx.req.__; - for (let sale of sales) { - changes += `\r\n-` + $t('Changes in sales', { - itemId: sale.itemFk, - concept: sale.concept, - oldQuantity: sale.oldQuantity, - newQuantity: sale.newQuantity, - itemUrl: `${url}item/${sale.itemFk}/summary` - }); - const currentSale = await models.Sale.findById(sale.id, null, myOptions); - await currentSale.updateAttributes({ - originalQuantity: currentSale.quantity - }, myOptions); - } - - const message = $t('Changed sale quantity', { - ticketId: ticket.id, - changes: changes, - ticketUrl: `${url}ticket/${ticket.id}/sale` - }); - await models.Chat.sendCheckingPresence(ctx, salesPersonFk, message, myOptions); - } - } - await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticket.id, params.code], myOptions); + await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [params.ticketFk, params.code], myOptions); const ticketTracking = await models.TicketTracking.findOne({ where: {ticketFk: params.ticketFk}, -- 2.40.1 From 637c6a9035e0b37907c5fc71e9cf239ae461a80e Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 19 Jun 2024 09:40:24 +0200 Subject: [PATCH 241/413] feat: refs #7216 logUnpaid --- modules/client/back/locale/client-unpaid/en.yml | 5 +++++ modules/client/back/locale/client-unpaid/es.yml | 5 +++++ modules/client/back/models/client-unpaid.json | 5 ++++- 3 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 modules/client/back/locale/client-unpaid/en.yml create mode 100644 modules/client/back/locale/client-unpaid/es.yml diff --git a/modules/client/back/locale/client-unpaid/en.yml b/modules/client/back/locale/client-unpaid/en.yml new file mode 100644 index 000000000..77a993671 --- /dev/null +++ b/modules/client/back/locale/client-unpaid/en.yml @@ -0,0 +1,5 @@ +name: uppaid +columns: + clientFk: client + dated: date + amount: amount diff --git a/modules/client/back/locale/client-unpaid/es.yml b/modules/client/back/locale/client-unpaid/es.yml new file mode 100644 index 000000000..e24236109 --- /dev/null +++ b/modules/client/back/locale/client-unpaid/es.yml @@ -0,0 +1,5 @@ +name: impagado +columns: + clientFk: cliente + dated: fecha + amount: cantidad diff --git a/modules/client/back/models/client-unpaid.json b/modules/client/back/models/client-unpaid.json index 0fc3a9195..6637c3940 100644 --- a/modules/client/back/models/client-unpaid.json +++ b/modules/client/back/models/client-unpaid.json @@ -1,6 +1,9 @@ { "name": "ClientUnpaid", "base": "VnModel", + "mixins": { + "Loggable": true + }, "options": { "mysql": { "table": "clientUnpaid" @@ -25,4 +28,4 @@ "foreignKey": "clientFk" } } -} \ No newline at end of file +} -- 2.40.1 From a42562b0ca1d572d8c9dca5d4864ec8eaee47b48 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 19 Jun 2024 10:01:32 +0200 Subject: [PATCH 242/413] fear: refs #5855 claim_ratio_routine --- db/routines/bi/procedures/claim_ratio_routine.sql | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/db/routines/bi/procedures/claim_ratio_routine.sql b/db/routines/bi/procedures/claim_ratio_routine.sql index e22162fff..bd273a2c9 100644 --- a/db/routines/bi/procedures/claim_ratio_routine.sql +++ b/db/routines/bi/procedures/claim_ratio_routine.sql @@ -55,8 +55,8 @@ BEGIN -- Recobros - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list + DROP TEMPORARY TABLE IF EXISTS tTicket_list; + CREATE TEMPORARY TABLE tTicket_list (PRIMARY KEY (Id_Ticket)) SELECT DISTINCT t.id Id_Ticket FROM vn.saleComponent sc @@ -74,7 +74,7 @@ BEGIN DELETE g.* FROM vn.greuge g - JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket + JOIN tTicket_list t ON g.ticketFk = t.Id_Ticket WHERE g.greugeTypeFk = 2; INSERT INTO vn.greuge(clientFk, description, amount,shipped, @@ -87,7 +87,7 @@ BEGIN ,tt.Id_Ticket FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.id + JOIN tTicket_list tt ON tt.Id_Ticket = t.id JOIN vn.saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = 17 GROUP BY t.id @@ -95,7 +95,7 @@ BEGIN UPDATE vn.saleComponent sc JOIN vn.sale s ON s.id = sc.saleFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = s.ticketFk + JOIN tTicket_list tt ON tt.Id_Ticket = s.ticketFk SET sc.isGreuge = 1 WHERE sc.componentFk = 17; @@ -164,6 +164,6 @@ BEGIN SET cr.recobro = sub.recobro WHERE Id_Cliente IN ( 5189,8942); - DROP TEMPORARY TABLE tmp.ticket_list; + DROP TEMPORARY TABLE tTicket_list; END$$ DELIMITER ; -- 2.40.1 From 49e01218e9d9dfffb71c9715339e482db6bf2759 Mon Sep 17 00:00:00 2001 From: Pako Date: Wed, 19 Jun 2024 10:45:37 +0200 Subject: [PATCH 243/413] Warehouse name --- .../vn/procedures/supplierPackaging_ReportSource.sql | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index 7cc72848f..a8e506244 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -68,7 +68,7 @@ BEGIN DATE(t.shipped), -LEAST(s.quantity,0) `in`, GREATEST(s.quantity,0) `out`, - t.warehouseFk, + w.name, s.price * (100 - s.discount) / 100 FROM sale s JOIN item i ON i.id = s.itemFk @@ -76,6 +76,7 @@ BEGIN JOIN ticket t ON t.id = s.ticketFk JOIN client c ON c.id = t.clientFk JOIN supplier su ON su.nif = c.fi + JOIN warehouse w ON w.id = t.warehouseFk WHERE su.id = vSupplierFk AND t.shipped >= vFromDated AND p.isPackageReturnable @@ -110,7 +111,7 @@ BEGIN DATE(t.shipped), -LEAST(tp.quantity,0) `in`, GREATEST(tp.quantity,0) `out`, - t.warehouseFk, + w.name, 0 FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk @@ -118,6 +119,7 @@ BEGIN JOIN ticket t ON t.id = tp.ticketFk JOIN client c ON c.id = t.clientFk JOIN supplier su ON su.nif = c.fi + JOIN warehouse w ON w.id = t.warehouseFk WHERE su.id = vSupplierFk AND t.shipped >= vFromDated AND p.isPackageReturnable -- 2.40.1 From 0128dfd967d6cebf6a0206c4ce4a064fa1638592 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 19 Jun 2024 11:30:50 +0200 Subject: [PATCH 244/413] feat: refs #5855 changes required --- db/routines/edi/procedures/floramondo_offerRefresh.sql | 3 +-- db/routines/vn/procedures/copyComponentsFromSaleList.sql | 8 ++++---- db/routines/vn/procedures/ticket_DelayTruck.sql | 8 ++++---- 3 files changed, 9 insertions(+), 10 deletions(-) diff --git a/db/routines/edi/procedures/floramondo_offerRefresh.sql b/db/routines/edi/procedures/floramondo_offerRefresh.sql index 312de7ffb..18d3f8b7e 100644 --- a/db/routines/edi/procedures/floramondo_offerRefresh.sql +++ b/db/routines/edi/procedures/floramondo_offerRefresh.sql @@ -484,8 +484,7 @@ proc: BEGIN DROP TEMPORARY TABLE edi.offer, - itemToInsert, - tmp.buyRecalc; + itemToInsert; SET @isTriggerDisabled = FALSE; diff --git a/db/routines/vn/procedures/copyComponentsFromSaleList.sql b/db/routines/vn/procedures/copyComponentsFromSaleList.sql index 13487af17..ab75486d1 100644 --- a/db/routines/vn/procedures/copyComponentsFromSaleList.sql +++ b/db/routines/vn/procedures/copyComponentsFromSaleList.sql @@ -16,9 +16,9 @@ BEGIN SET @order = 0; - DROP TEMPORARY TABLE IF EXISTS tmp.newSaleList; + DROP TEMPORARY TABLE IF EXISTS tNewSaleList; - CREATE TEMPORARY TABLE tmp.newSaleList + CREATE TEMPORARY TABLE tNewSaleList SELECT id as saleFk, @order := @order + 1 as orden FROM vn.sale WHERE ticketFk = vTargetTicketFk @@ -28,8 +28,8 @@ BEGIN SELECT ns.saleFk, sc.componentFk, sc.value FROM vn.saleComponent sc JOIN tmp.saleList s ON s.saleFk = sc.saleFk - JOIN tmp.newSaleList ns ON ns.orden = s.orden; + JOIN tNewSaleList ns ON ns.orden = s.orden; - DROP TEMPORARY TABLE IF EXISTS tmp.newSaleList; + DROP TEMPORARY TABLE IF EXISTS tNewSaleList; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_DelayTruck.sql b/db/routines/vn/procedures/ticket_DelayTruck.sql index 2fb98d07d..81896dd8e 100644 --- a/db/routines/vn/procedures/ticket_DelayTruck.sql +++ b/db/routines/vn/procedures/ticket_DelayTruck.sql @@ -3,14 +3,14 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruck`( BEGIN DECLARE done INT DEFAULT FALSE; DECLARE vTicketFk INT; - DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tmp.ticket; + DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tTicket; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; CALL vn.productionControl(vWarehouserFk,0) ; - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket + DROP TEMPORARY TABLE IF EXISTS tTicket; + CREATE TEMPORARY TABLE tTicket SELECT ticketFk FROM tmp.productionBuffer JOIN alertLevel al ON al.code = 'FREE' @@ -31,6 +31,6 @@ BEGIN END LOOP; CLOSE cur1; - DROP TEMPORARY TABLE tmp.ticket, tmp.productionBuffer; + DROP TEMPORARY TABLE tTicket, tmp.productionBuffer; END$$ DELIMITER ; -- 2.40.1 From 1a8df4d87c0a554bde7b55ac54dffdadc73c6555 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 19 Jun 2024 13:41:37 +0200 Subject: [PATCH 245/413] feat: refs #7216 triggers --- db/routines/vn/triggers/clientUnpaid_beforeInsert.sql | 8 ++++++++ db/routines/vn/triggers/clientUnpaid_beforeUpdate.sql | 8 ++++++++ db/versions/11110-grayGerbera/00-clientUnpaid.sql | 4 ++++ modules/client/back/locale/client-unpaid/en.yml | 2 +- 4 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 db/routines/vn/triggers/clientUnpaid_beforeInsert.sql create mode 100644 db/routines/vn/triggers/clientUnpaid_beforeUpdate.sql create mode 100644 db/versions/11110-grayGerbera/00-clientUnpaid.sql diff --git a/db/routines/vn/triggers/clientUnpaid_beforeInsert.sql b/db/routines/vn/triggers/clientUnpaid_beforeInsert.sql new file mode 100644 index 000000000..279a81b73 --- /dev/null +++ b/db/routines/vn/triggers/clientUnpaid_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`clientUnpaid_beforeInsert` + BEFORE INSERT ON `clientUnpaid` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/clientUnpaid_beforeUpdate.sql b/db/routines/vn/triggers/clientUnpaid_beforeUpdate.sql new file mode 100644 index 000000000..13cac3fa7 --- /dev/null +++ b/db/routines/vn/triggers/clientUnpaid_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`clientUnpaid_beforeUpdate` + BEFORE UPDATE ON `clientUnpaid` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/versions/11110-grayGerbera/00-clientUnpaid.sql b/db/versions/11110-grayGerbera/00-clientUnpaid.sql new file mode 100644 index 000000000..06fd51555 --- /dev/null +++ b/db/versions/11110-grayGerbera/00-clientUnpaid.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.clientUnpaid + ADD editorFk INT UNSIGNED NULL, + ADD CONSTRAINT ClientUnpaid_editorFk FOREIGN KEY (editorFk) + REFERENCES account.`user`(id); diff --git a/modules/client/back/locale/client-unpaid/en.yml b/modules/client/back/locale/client-unpaid/en.yml index 77a993671..10f797c97 100644 --- a/modules/client/back/locale/client-unpaid/en.yml +++ b/modules/client/back/locale/client-unpaid/en.yml @@ -1,4 +1,4 @@ -name: uppaid +name: unpaid columns: clientFk: client dated: date -- 2.40.1 From b2ad44980909fd2ecd7d3bc29cb2a0a25755b869 Mon Sep 17 00:00:00 2001 From: jgallego Date: Wed, 19 Jun 2024 14:38:56 +0200 Subject: [PATCH 246/413] feat: refs #7027 mailError managed --- loopback/locale/en.json | 5 +++-- loopback/locale/es.json | 5 +++-- loopback/locale/fr.json | 3 ++- print/core/email.js | 8 ++++++-- 4 files changed, 14 insertions(+), 7 deletions(-) diff --git a/loopback/locale/en.json b/loopback/locale/en.json index a2332fdca..1e5733442 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -232,5 +232,6 @@ "Incoterms and Customs agent are required for a non UEE member": "Incoterms and Customs agent are required for a non UEE member", "It has been invoiced but the PDF could not be generated": "It has been invoiced but the PDF could not be generated", "It has been invoiced but the PDF of refund not be generated": "It has been invoiced but the PDF of refund not be generated", - "Cannot add holidays on this day": "Cannot add holidays on this day" -} \ No newline at end of file + "Cannot add holidays on this day": "Cannot add holidays on this day", + "Cannot send mail": "Cannot send mail" +} diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 714475374..cf8133759 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -365,5 +365,6 @@ "You can only have one PDA": "Solo puedes tener un PDA", "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", - "Payment method is required": "El método de pago es obligatorio" -} \ No newline at end of file + "Payment method is required": "El método de pago es obligatorio", + "Cannot send mail": "Não é possível enviar o email" +} diff --git a/loopback/locale/fr.json b/loopback/locale/fr.json index 1dbd162d8..49584ef0e 100644 --- a/loopback/locale/fr.json +++ b/loopback/locale/fr.json @@ -359,5 +359,6 @@ "Select ticket or client": "Choisissez un ticket ou un client", "It was not able to create the invoice": "Il n'a pas été possible de créer la facture", "It has been invoiced but the PDF could not be generated": "La facture a été émise mais le PDF n'a pas pu être généré", - "It has been invoiced but the PDF of refund not be generated": "Il a été facturé mais le PDF de remboursement n'a pas été généré" + "It has been invoiced but the PDF of refund not be generated": "Il a été facturé mais le PDF de remboursement n'a pas été généré", + "Cannot send mail": "Impossible d'envoyer le mail" } diff --git a/print/core/email.js b/print/core/email.js index 5de13099a..a0bcf9122 100644 --- a/print/core/email.js +++ b/print/core/email.js @@ -2,6 +2,7 @@ const path = require('path'); const smtp = require('./smtp'); const Component = require('./component'); const Report = require('./report'); +const UserError = require('vn-loopback/util/user-error'); if (!process.env.OPENSSL_CONF) process.env.OPENSSL_CONF = '/etc/ssl/'; @@ -9,7 +10,6 @@ if (!process.env.OPENSSL_CONF) class Email extends Component { constructor(name, args) { super(name); - this.args = args; } @@ -88,7 +88,11 @@ class Email extends Component { force: options.force }; - return await smtp.send(mailOptions); + try { + return await smtp.send(mailOptions); + } catch (error) { + throw new UserError('Cannot send mail'); + } } } -- 2.40.1 From c87f060d5166807a93642ad8a9d3655a21269829 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 20 Jun 2024 09:21:27 +0200 Subject: [PATCH 247/413] feat boxPicking refs #7357 --- back/model-config.json | 5 ++++- back/models/expedition_PrintOut.json | 24 ++++++++++++++++++++++++ db/dump/fixtures.before.sql | 8 ++++++++ 3 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 back/models/expedition_PrintOut.json diff --git a/back/model-config.json b/back/model-config.json index b643ab54f..58fa86797 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -64,6 +64,9 @@ "EmailUser": { "dataSource": "vn" }, + "Expedition_PrintOut": { + "dataSource": "vn" + }, "Image": { "dataSource": "vn" }, @@ -190,4 +193,4 @@ "RouteConfig": { "dataSource": "vn" } -} +} \ No newline at end of file diff --git a/back/models/expedition_PrintOut.json b/back/models/expedition_PrintOut.json new file mode 100644 index 000000000..6f521cda3 --- /dev/null +++ b/back/models/expedition_PrintOut.json @@ -0,0 +1,24 @@ +{ + "name": "Expedition_PrintOut", + "base": "VnModel", + "options": { + "mysql": { + "table": "dipole.expedition_PrintOut" + } + }, + "properties": { + "expeditionFk": { + "type": "number", + "id": true, + "description": "id expeditionFk" + }, + "itemFk": { + "type": "number", + "required": true + }, + "shelvingFk": { + "type": "string", + "required": true + } + } +} \ No newline at end of file diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 058c5cd2a..dc9efacf1 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3882,3 +3882,11 @@ INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHoli (1, '2001-05-17', 1, 5), (1, '2001-05-18', 1, 5); + +INSERT INTO dipole.printer (id, description) + VALUES(1, ''); + + INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, street, postalCode, city, shopName, isPrinted, created, printerFk, routeFk, parkingCode, + truckName, clientFk, phone, province, agency, m3, workerCode, itemFk, quantity, longName, shelvingFk, comments) + VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, NULL, 'NCC', NULL); + -- 2.40.1 From 5a40952547c1bea9453dfcf9c45ec4004c5dce56 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 20 Jun 2024 09:34:13 +0200 Subject: [PATCH 248/413] fix: refs #195937 icoterms --- .../templates/reports/invoice-incoterms/sql/incoterms.sql | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/print/templates/reports/invoice-incoterms/sql/incoterms.sql b/print/templates/reports/invoice-incoterms/sql/incoterms.sql index 81c0ec189..363de0b16 100644 --- a/print/templates/reports/invoice-incoterms/sql/incoterms.sql +++ b/print/templates/reports/invoice-incoterms/sql/incoterms.sql @@ -1,7 +1,7 @@ SELECT pack.packages, a.incotermsFk, ic.name incotermsName, - t.weight, + wei.weight, ca.fiscalName customsAgentName, ca.street customsAgentStreet, ca.nif customsAgentNif, @@ -48,5 +48,10 @@ SELECT pack.packages, FROM ticket WHERE refFk = ? ) pack + JOIN ( + SELECT SUM(weight) weight + FROM ticket + WHERE refFk = ? + ) wei WHERE t.refFk = ? LIMIT 1 -- 2.40.1 From c1c01df3c3f05f5402335143e752d93809b1d595 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 20 Jun 2024 09:37:22 +0200 Subject: [PATCH 249/413] feat itemShelving_filterBuyer refs #7023 --- db/routines/vn/procedures/itemShelving_filterBuyer.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/itemShelving_filterBuyer.sql b/db/routines/vn/procedures/itemShelving_filterBuyer.sql index 7112aa48e..894a14464 100644 --- a/db/routines/vn/procedures/itemShelving_filterBuyer.sql +++ b/db/routines/vn/procedures/itemShelving_filterBuyer.sql @@ -15,7 +15,7 @@ proc:BEGIN SELECT * FROM (SELECT sub.itemFk, sub.longName, - CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, + CONCAT('Hoy quedan por sacar ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, CONCAT(IF(sub2.itemFk, IF(sub2.pendiente > (sub.upstairs + sub.downstairs),'(1) ','(2) '),'(3) ' ),sub.producer) producer, sub.upstairs, sub.downstairs, @@ -52,7 +52,7 @@ proc:BEGIN UNION ALL SELECT v.item_id, i.longName, - CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, + CONCAT('Hoy quedan por sacar ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, CONCAT(IF(sub5.pendiente,'(0) ','(3) ')) producer, 0, 0, -- 2.40.1 From 46792ba30e792441689df3f081e7495d957afc96 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 20 Jun 2024 11:04:42 +0200 Subject: [PATCH 250/413] fix: refs #195937 changes requerid --- .../reports/invoice-incoterms/sql/incoterms.sql | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/print/templates/reports/invoice-incoterms/sql/incoterms.sql b/print/templates/reports/invoice-incoterms/sql/incoterms.sql index 363de0b16..2a041fce0 100644 --- a/print/templates/reports/invoice-incoterms/sql/incoterms.sql +++ b/print/templates/reports/invoice-incoterms/sql/incoterms.sql @@ -1,7 +1,7 @@ -SELECT pack.packages, +SELECT calc.packages, a.incotermsFk, ic.name incotermsName, - wei.weight, + calc.weight, ca.fiscalName customsAgentName, ca.street customsAgentStreet, ca.nif customsAgentNif, @@ -44,14 +44,9 @@ SELECT pack.packages, WHERE t.refFk = ? ) intr JOIN ( - SELECT SUM(packages) packages + SELECT SUM(packages) packages, SUM(weight) weight FROM ticket WHERE refFk = ? - ) pack - JOIN ( - SELECT SUM(weight) weight - FROM ticket - WHERE refFk = ? - ) wei + ) calc WHERE t.refFk = ? LIMIT 1 -- 2.40.1 From 182cd3fa8e79423f5cf28c0b13931ee2ceb48e55 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 20 Jun 2024 11:34:51 +0200 Subject: [PATCH 251/413] feat boxPicking refs #7357 --- db/dump/fixtures.before.sql | 2 +- loopback/locale/es.json | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index dc9efacf1..9cd470dab 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3883,7 +3883,7 @@ INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHoli (1, '2001-05-18', 1, 5); -INSERT INTO dipole.printer (id, description) + INSERT INTO dipole.printer (id, description) VALUES(1, ''); INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, street, postalCode, city, shopName, isPrinted, created, printerFk, routeFk, parkingCode, diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 714475374..047774684 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -365,5 +365,6 @@ "You can only have one PDA": "Solo puedes tener un PDA", "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", - "Payment method is required": "El método de pago es obligatorio" + "Payment method is required": "El método de pago es obligatorio", + "CLIENT_NOT_ESPECIFIED": "CLIENT_NOT_ESPECIFIED" } \ No newline at end of file -- 2.40.1 From 7d3c07aaaecc61fd1caa83221af430185b235b42 Mon Sep 17 00:00:00 2001 From: Sergio De la torre Date: Thu, 20 Jun 2024 10:44:31 +0000 Subject: [PATCH 252/413] Actualizar README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b052bd8bf..2ad83c2e4 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Pull from repository. Run this commands on project root directory to install Node dependencies. ``` -$ npm install +$ pnpm install $ gulp install ``` -- 2.40.1 From 9a4ec460733faf283b6a31789bca1d7e5ebdc0de Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 20 Jun 2024 13:09:40 +0200 Subject: [PATCH 253/413] hotfix: refs #6820 Deleted km validation --- modules/route/back/models/route.js | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index bf1f26e74..0fde335b3 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -20,21 +20,4 @@ module.exports = Self => { require('../methods/route/cmrEmail')(Self); require('../methods/route/getExpeditionSummary')(Self); require('../methods/route/getByWorker')(Self); - - Self.validate('kmStart', validateDistance, { - message: 'Distance must be lesser than 4000' - }); - - Self.validate('kmEnd', validateDistance, { - message: 'Distance must be lesser than 4000' - }); - - function validateDistance(err) { - if (this.kmEnd) { - const routeTotalKm = this.kmEnd - this.kmStart; - const routeMaxKm = 4000; - if (routeTotalKm > routeMaxKm || this.kmStart > this.kmEnd) - err(); - } - } }; -- 2.40.1 From 852785b4c1ccb4aecc2efdc654a28f77bfc037ba Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 20 Jun 2024 13:45:38 +0200 Subject: [PATCH 254/413] fix: refs #195937 refactor incoterms --- .../invoice-incoterms/invoice-incoterms.js | 2 +- .../invoice-incoterms/sql/incoterms.sql | 89 ++++++++----------- 2 files changed, 38 insertions(+), 53 deletions(-) diff --git a/print/templates/reports/invoice-incoterms/invoice-incoterms.js b/print/templates/reports/invoice-incoterms/invoice-incoterms.js index cfe29169b..ebeaf4d7c 100755 --- a/print/templates/reports/invoice-incoterms/invoice-incoterms.js +++ b/print/templates/reports/invoice-incoterms/invoice-incoterms.js @@ -9,7 +9,7 @@ module.exports = { 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]); + await this.findOneFromDef('incoterms', [this.reference]); if (!this.incoterms) throw new UserError(`The address of the customer must have information about Incoterms and Customs Agent`); }, diff --git a/print/templates/reports/invoice-incoterms/sql/incoterms.sql b/print/templates/reports/invoice-incoterms/sql/incoterms.sql index 2a041fce0..b7c42a951 100644 --- a/print/templates/reports/invoice-incoterms/sql/incoterms.sql +++ b/print/templates/reports/invoice-incoterms/sql/incoterms.sql @@ -1,52 +1,37 @@ -SELECT calc.packages, - a.incotermsFk, - ic.name incotermsName, - calc.weight, - ca.fiscalName customsAgentName, - ca.street customsAgentStreet, - ca.nif customsAgentNif, - ca.phone customsAgentPhone, - ca.email customsAgentEmail, - CAST(vol.volume AS DECIMAL (10,2)) volume, - intr.intrastat - FROM vn.invoiceOut io - JOIN vn.supplier su ON su.id = io.companyFk - JOIN vn.client c ON c.id = io.clientFk - LEFT JOIN vn.province p ON p.id = c.provinceFk - JOIN vn.ticket t ON t.refFk = io.ref - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.incoterms ic ON ic.code = a.incotermsFk - LEFT JOIN vn.customsAgent ca ON ca.id = a.customsAgentFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN ( - SELECT SUM(volume) volume, COUNT(*) packages - FROM vn.invoiceOut io - JOIN vn.ticket t ON t.refFk = io.ref - JOIN vn.saleVolume sv ON sv.ticketFk = t.id - WHERE t.refFk = ? - ) vol - JOIN vn.itemTaxCountry itc ON itc.countryFk = su.countryFk - AND itc.itemFk = s.itemFk - JOIN vn.taxClass tc ON tc.id = itc.taxClassFk - JOIN vn.invoiceOutSerial ios ON ios.code = io.serial - AND ios.taxAreaFk = 'WORLD' - JOIN vn.country cty ON cty.id = c.countryFk - JOIN vn.payMethod pm ON pm.id = c .payMethodFk - JOIN vn.company co ON co.id=io.companyFk - JOIN vn.supplierAccount sa ON sa.id=co.supplierAccountFk - JOIN ( - SELECT GROUP_CONCAT(DISTINCT ir.description ORDER BY ir.description SEPARATOR '. ' ) intrastat - FROM vn.ticket t - JOIN vn.invoiceOut io ON io.ref = t.refFk - JOIN vn.sale s ON t.id = s.ticketFk - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.intrastat ir ON ir.id = i.intrastatFk - WHERE t.refFk = ? - ) intr - JOIN ( - SELECT SUM(packages) packages, SUM(weight) weight - FROM ticket - WHERE refFk = ? - ) calc - WHERE t.refFk = ? - LIMIT 1 +WITH tickets AS( +SELECT id, packages, addressFk, weight + FROM ticket + WHERE refFk='E12400228' +) , weight AS( +SELECT weight + FROM tickets + WHERE weight + LIMIT 1 +), volume AS( +SELECT SUM(volume) volume + FROM tickets t + JOIN vn.saleVolume sv ON sv.ticketFk = t.id +), intrastat AS( +SELECT GROUP_CONCAT(DISTINCT ir.description ORDER BY ir.description SEPARATOR '. ' ) intrastat + FROM tickets t + JOIN vn.sale s ON t.id = s.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.intrastat ir ON ir.id = i.intrastatFk +)SELECT SUM(t.packages), + a.incotermsFk, + ic.name incotermsName, + w.weight, + ca.fiscalName customsAgentName, + ca.street customsAgentStreet, + ca.nif customsAgentNif, + ca.phone customsAgentPhone, + ca.email customsAgentEmail, + CAST(v.volume AS DECIMAL (10,2)) volume, + i.intrastat + FROM tickets t + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.incoterms ic ON ic.code = a.incotermsFk + LEFT JOIN vn.customsAgent ca ON ca.id = a.customsAgentFk + JOIN volume v + JOIN intrastat i + LEFT JOIN weight w ON TRUE -- 2.40.1 From 8fc231da2ffefb8fa2c8ecc851217f068de34cef Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 20 Jun 2024 14:03:31 +0200 Subject: [PATCH 255/413] feat: refs #195937 --- print/templates/reports/invoice-incoterms/sql/incoterms.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/print/templates/reports/invoice-incoterms/sql/incoterms.sql b/print/templates/reports/invoice-incoterms/sql/incoterms.sql index b7c42a951..f3566ae30 100644 --- a/print/templates/reports/invoice-incoterms/sql/incoterms.sql +++ b/print/templates/reports/invoice-incoterms/sql/incoterms.sql @@ -1,7 +1,7 @@ WITH tickets AS( SELECT id, packages, addressFk, weight FROM ticket - WHERE refFk='E12400228' + WHERE refFk= ? ) , weight AS( SELECT weight FROM tickets -- 2.40.1 From e0d105313d4d34b2fb2b768efd8a601f86d1e095 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 20 Jun 2024 14:27:11 +0200 Subject: [PATCH 256/413] feat: sincro client supplier sage refs #7595 --- .../procedures/accountingMovements_add.sql | 73 ++++++++++++------- .../sage/procedures/clientSupplier_add.sql | 34 +++++---- .../vn/triggers/client_afterUpdate.sql | 25 ++++++- .../vn/triggers/client_beforeUpdate.sql | 4 +- .../vn/triggers/supplier_afterUpdate.sql | 26 +++++++ .../00-firstScript.sql | 9 +++ 6 files changed, 128 insertions(+), 43 deletions(-) create mode 100644 db/routines/vn/triggers/supplier_afterUpdate.sql create mode 100644 db/versions/11105-bronzeChrysanthemum/00-firstScript.sql diff --git a/db/routines/sage/procedures/accountingMovements_add.sql b/db/routines/sage/procedures/accountingMovements_add.sql index 575c63f6c..88c599b09 100644 --- a/db/routines/sage/procedures/accountingMovements_add.sql +++ b/db/routines/sage/procedures/accountingMovements_add.sql @@ -21,7 +21,8 @@ BEGIN DECLARE vTransactionExportTaxFreeFk INT; DECLARE vSerialDua VARCHAR(1) DEFAULT 'D'; DECLARE vInvoiceTypeInformativeCode VARCHAR(1); - DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2) ; + DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2); + DECLARE vCompanyCode INT; SELECT SiglaNacion INTO vCountryCanariasCode FROM Naciones @@ -31,9 +32,6 @@ BEGIN FROM Naciones WHERE Nacion ='CEUTA Y MELILLA'; - SELECT pendingServiceTransactionTypeFk INTO vDuaTransactionFk - FROM config; - SELECT id INTO vTaxImportFk FROM taxType WHERE code = 'import21'; @@ -46,10 +44,14 @@ BEGIN FROM taxType WHERE code = 'import4'; - SELECT definitiveExportTransactionTypeFk INTO vTransactionExportFk - FROM config; - - SELECT shipmentTransactionTypeFk INTO vTransactionExportTaxFreeFk + SELECT shipmentTransactionTypeFk, + definitiveExportTransactionTypeFk, + pendingServiceTransactionTypeFk, + company_getCode(vCompanyFk) + INTO vTransactionExportTaxFreeFk, + vTransactionExportFk, + vDuaTransactionFk, + vCompanyCode FROM config; SELECT codeSage INTO vInvoiceTypeInformativeCode @@ -64,8 +66,6 @@ BEGIN WHERE enlazadoSage = FALSE AND Asiento <> 1 ; - CALL clientSupplier_add(vCompanyFk); - CALL pgc_add(vCompanyFk); CALL invoiceOut_manager(vYear, vCompanyFk); CALL invoiceIn_manager(vYear, vCompanyFk); @@ -158,7 +158,7 @@ BEGIN ) SELECT 'EN' TipoEntrada, YEAR(x.FECHA) Ejercicio, - company_getCode(vCompanyFk) AS CodigoEmpresa, + vCompanyCode CodigoEmpresa, x.ASIEN Asiento, IF(EURODEBE <> 0 OR (EURODEBE = 0 AND EUROHABER IS NULL), 'D', 'H') CargoAbono, @@ -291,20 +291,6 @@ BEGIN WHERE m.CargoAbono = 'D' AND m.enlazadoSage = FALSE; --- Elimina cuentas de cliente/proveedor que no se utilizarán en la importación - DELETE cp - FROM clientesProveedores cp - LEFT JOIN movConta mc ON mc.codigoCuenta = cp.codigoCuenta - AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL; - --- Elimina cuentas contables que no se utilizarán en la importación - DELETE pc - FROM planCuentasPGC pc - LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta - AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL; - -- DUAS UPDATE movConta mci JOIN vn.XDiario x ON x.ASIEN = mci.Asiento @@ -411,5 +397,42 @@ BEGIN AND importeDivisa > 0 AND ImporteAsiento < 0; + CREATE OR REPLACE TEMPORARY TABLE tmp.clientSupplier + (INDEX(idClientSupplier, `type`)) + ENGINE = MEMORY + WITH client AS( + SELECT DISTINCT c.id + FROM sage.movConta mc + JOIN vn.client c ON c.accountingAccount = mc.CodigoCuenta + WHERE NOT enlazadoSage + ),supplier AS( + SELECT DISTINCT s.id + FROM sage.movConta mc + JOIN vn.supplier s ON s.account = mc.CodigoCuenta + WHERE NOT enlazadoSage + )SELECT idClientSupplier, `type` + FROM sage.clientSupplier cs + WHERE NOT isSync + UNION + SELECT id, 'C' + FROM client + UNION + SELECT id, 'P' + FROM supplier; + + CALL clientSupplier_add(vCompanyFk); + + INSERT IGNORE INTO sage.clientSupplier (companyFk, `type`, idClientSupplier, isSync) + SELECT vCompanyCode, `type`, idClientSupplier, FALSE + FROM tmp.clientSupplier; + + CALL pgc_add(vCompanyFk); +-- Elimina cuentas contables que no se utilizarán en la importación + DELETE pc + FROM planCuentasPGC pc + LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta + AND mc.enlazadoSage = FALSE + WHERE mc.codigoCuenta IS NULL; + END$$ DELIMITER ; diff --git a/db/routines/sage/procedures/clientSupplier_add.sql b/db/routines/sage/procedures/clientSupplier_add.sql index 70f3ef3d0..2c4b4db9d 100644 --- a/db/routines/sage/procedures/clientSupplier_add.sql +++ b/db/routines/sage/procedures/clientSupplier_add.sql @@ -1,11 +1,16 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `sage`.`clientSupplier_add`(vCompanyFk INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `sage`.`clientSupplier_add`( + vCompanyFk INT +) BEGIN /** - * Prepara los datos de clientes y proveedores para exportarlos a Sage - * @vCompanyFk Empresa dela que se quiere trasladar datos + * Inserta en la tabla sage.clientesProveedores los datos de clientes y proveedores + * que se actualizaran o se daran de alta en Sage + * @vCompanyFk Id de empresa + * @table tmp.clientSupplier(idClientSupplier, `type`) */ DECLARE vCountryCeutaMelillaFk INT; + DECLARE vCompanyCode INT DEFAULT company_getCode(vCompanyFk); DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2); SELECT SiglaNacion INTO vCountryCanariasCode @@ -45,7 +50,7 @@ BEGIN Email1, iban) SELECT - company_getCode(vCompanyFk), + vCompanyCode, 'C', c.id, c.socialName, @@ -53,7 +58,7 @@ BEGIN IFNULL(c.street, ''), c.accountingAccount, @fi := IF(cu.code = LEFT(TRIM(c.fi), 2) AND c.isVies, MID(TRIM(c.fi), 3, LENGTH(TRIM(c.fi))-1), TRIM(c.fi)), - IF(c.isVies, CONCAT(IFNULL(cu.viesCode,cu.code), @fi ), TRIM(c.fi)), + IF(c.isVies, CONCAT(IFNULL(cu.viesCode,cu.code), @fi ), TRIM(c.fi)), IFNULL(c.postcode, ''), IFNULL(c.city, ''), IFNULL(pr.CodigoProvincia, ''), @@ -75,15 +80,14 @@ BEGIN IFNULL(SUBSTR(c.email, 1, LOCATE(',', CONCAT(c.email, ','))-1), ''), IFNULL(c.iban, '') FROM vn.`client` c - JOIN clientLastTwoMonths clm ON clm.clientFk = c.id + JOIN tmp.clientSupplier cs ON cs.idClientSupplier = c.id LEFT JOIN vn.country cu ON cu.id = c.countryFk LEFT JOIN Naciones n ON n.countryFk = cu.id LEFT JOIN vn.province p ON p.id = c.provinceFk LEFT JOIN Provincias pr ON pr.provinceFk = p.id - WHERE c.isRelevant - AND clm.companyFk = vCompanyFk + WHERE cs.type = 'C' UNION ALL - SELECT company_getCode(vCompanyFk), + SELECT vCompanyCode, 'P', s.id, s.name, @@ -107,18 +111,18 @@ BEGIN IFNULL(s.transactionTypeSageFk, 0), IFNULL(s.withholdingSageFk, '0'), IFNULL(SUBSTR(sc.email, 1, (COALESCE(NULLIF(LOCATE(',', sc.email), 0), 99) - 1)), ''), - IFNULL(iban, '') + IFNULL(sa.iban, '') FROM vn.supplier s - JOIN supplierLastThreeMonths pl ON pl.supplierFk = s.id + JOIN tmp.clientSupplier cs ON cs.idClientSupplier = s.id LEFT JOIN vn.country co ON co.id = s.countryFk LEFT JOIN Naciones n ON n.countryFk = co.id LEFT JOIN vn.province p ON p.id = s.provinceFk LEFT JOIN Provincias pr ON pr.provinceFk = p.id LEFT JOIN vn.supplierContact sc ON sc.supplierFk = s.id LEFT JOIN vn.supplierAccount sa ON sa.supplierFk = s.id - WHERE pl.companyFk = vCompanyFk AND - s.isActive AND - s.nif <> '' - GROUP BY pl.supplierFk, pl.companyFk; + WHERE cs.type = 'P' + GROUP BY s.id; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientSupplier; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/client_afterUpdate.sql b/db/routines/vn/triggers/client_afterUpdate.sql index e316fb08a..a2a3e48e3 100644 --- a/db/routines/vn/triggers/client_afterUpdate.sql +++ b/db/routines/vn/triggers/client_afterUpdate.sql @@ -3,12 +3,35 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_afterUpdate` AFTER UPDATE ON `client` FOR EACH ROW BEGIN - IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN + IF NOT (NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN UPDATE `address` SET isDefaultAddress = FALSE WHERE clientFk = NEW.id; UPDATE `address` SET isDefaultAddress = TRUE WHERE id = NEW.defaultAddressFk; END IF; + + IF NEW.id <> OLD.id + OR NOT (NEW.provinceFk <=> OLD.provinceFk) + OR NOT (NEW.socialName <=> OLD.socialName) + OR NOT (NEW.street <=> OLD.street) + OR NOT (NEW.accountingAccount <=> OLD.accountingAccount) + OR NOT (NEW.isVies <=> OLD.isVies) + OR NOT (NEW.fi <=> OLD.fi) + OR NOT (NEW.postcode <=> OLD.postcode) + OR NOT (NEW.city <=> OLD.city) + OR NOT (NEW.countryFk <=> OLD.countryFk) + OR NOT (NEW.taxTypeSageFk <=> OLD.taxTypeSageFk) + OR NOT (NEW.transactionTypeSageFk <=> OLD.transactionTypeSageFk) + OR NOT (NEW.email <=> OLD.email) + OR NOT (NEW.iban <=> OLD.iban) + OR NOT (NEW.phone <=> OLD.phone) + OR NOT (NEW.mobile <=> OLD.mobile) THEN + + UPDATE sage.clientSupplier + SET isSync = FALSE + WHERE idClientSupplier IN (NEW.id, OLD.id) + AND `type` = 'C'; + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/client_beforeUpdate.sql b/db/routines/vn/triggers/client_beforeUpdate.sql index 2f384c535..914ae5b8a 100644 --- a/db/routines/vn/triggers/client_beforeUpdate.sql +++ b/db/routines/vn/triggers/client_beforeUpdate.sql @@ -65,11 +65,11 @@ BEGIN END IF; END IF; - IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN + IF NOT (NEW.salesPersonFk <=> OLD.salesPersonFk) THEN SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk); END IF; - IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN + IF NOT (NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN SET NEW.isTaxDataChecked = 0; END IF; END$$ diff --git a/db/routines/vn/triggers/supplier_afterUpdate.sql b/db/routines/vn/triggers/supplier_afterUpdate.sql new file mode 100644 index 000000000..e89df037f --- /dev/null +++ b/db/routines/vn/triggers/supplier_afterUpdate.sql @@ -0,0 +1,26 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`supplier_afterUpdate` + BEFORE UPDATE ON `supplier` + FOR EACH ROW +BEGIN + IF NEW.id <> OLD.id + OR NOT (NEW.name <=> OLD.name) + OR NOT (NEW.street <=> OLD.street) + OR NOT (NEW.account <=> OLD.account) + OR NOT (NEW.nif <=> OLD.nif) + OR NOT (NEW.isVies <=> OLD.isVies) + OR NOT (NEW.provinceFk <=> OLD.provinceFk) + OR NOT (NEW.countryFk <=> OLD.countryFk) + OR NOT (NEW.postCode <=> OLD.postCode) + OR NOT (NEW.city <=> OLD.city) + OR NOT (NEW.taxTypeSageFk <=> OLD.taxTypeSageFk) + OR NOT (NEW.transactionTypeSageFk <=> OLD.transactionTypeSageFk) + OR NOT (NEW.withholdingSageFk <=> OLD.withholdingSageFk) THEN + + UPDATE sage.clientSupplier + SET isSync = FALSE + WHERE idClientSupplier IN (NEW.id, OLD.id) + AND `type` = 'P'; + END IF; +END$$ +DELIMITER ; diff --git a/db/versions/11105-bronzeChrysanthemum/00-firstScript.sql b/db/versions/11105-bronzeChrysanthemum/00-firstScript.sql new file mode 100644 index 000000000..685cd8f75 --- /dev/null +++ b/db/versions/11105-bronzeChrysanthemum/00-firstScript.sql @@ -0,0 +1,9 @@ + +CREATE OR REPLACE TABLE sage.clientSupplier ( + `companyFk` smallint(6) NOT NULL, + `type` ENUM('C','P') NOT NULL, + `idClientSupplier` INT NOT NULL, + `isSync` TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY (`companyFk`,`idClientSupplier`,`type`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci + COMMENT='Clients and suppliers present in Sage and their synchronization status'; \ No newline at end of file -- 2.40.1 From 414bf9eb03a72329ffe7f5ef296b7a28d30214c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 20 Jun 2024 14:48:32 +0200 Subject: [PATCH 257/413] feat: sincro client supplier sage refs #7595 --- db/routines/sage/procedures/accountingMovements_add.sql | 2 ++ db/routines/sage/procedures/clientSupplier_add.sql | 2 -- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/sage/procedures/accountingMovements_add.sql b/db/routines/sage/procedures/accountingMovements_add.sql index 88c599b09..ada954334 100644 --- a/db/routines/sage/procedures/accountingMovements_add.sql +++ b/db/routines/sage/procedures/accountingMovements_add.sql @@ -425,6 +425,8 @@ BEGIN INSERT IGNORE INTO sage.clientSupplier (companyFk, `type`, idClientSupplier, isSync) SELECT vCompanyCode, `type`, idClientSupplier, FALSE FROM tmp.clientSupplier; + + DROP TEMPORARY TABLE tmp.clientSupplier; CALL pgc_add(vCompanyFk); -- Elimina cuentas contables que no se utilizarán en la importación diff --git a/db/routines/sage/procedures/clientSupplier_add.sql b/db/routines/sage/procedures/clientSupplier_add.sql index 2c4b4db9d..2d1a51882 100644 --- a/db/routines/sage/procedures/clientSupplier_add.sql +++ b/db/routines/sage/procedures/clientSupplier_add.sql @@ -122,7 +122,5 @@ BEGIN LEFT JOIN vn.supplierAccount sa ON sa.supplierFk = s.id WHERE cs.type = 'P' GROUP BY s.id; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientSupplier; END$$ DELIMITER ; -- 2.40.1 From 31a75956c040bf44665cf1ba3a9d0e153e479172 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 20 Jun 2024 11:49:25 +0000 Subject: [PATCH 258/413] feat: add CALL util.debugAdd --- back/methods/vn-user/renew-token.js | 66 +++++++++++++++++------------ 1 file changed, 40 insertions(+), 26 deletions(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 5581d19ac..ae554d398 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -16,36 +16,50 @@ module.exports = Self => { accessScopes: ['DEFAULT', 'read:multimedia']}); Self.renewToken = async function(ctx) { - const {accessToken: token} = ctx.req; + let accessToken; + let token; + try { + token = ctx.req.accessToken; + const {courtesyTime} = await models.AccessTokenConfig.findOne({ + fields: ['courtesyTime'] + }); + const isNotExceeded = await Self.validateToken(ctx); + if (isNotExceeded) + return token; - const {courtesyTime} = await models.AccessTokenConfig.findOne({ - fields: ['courtesyTime'] - }); - const isNotExceeded = await Self.validateToken(ctx); - if (isNotExceeded) - return token; - - // Schedule to remove current token - setTimeout(async() => { - try { - const exists = await models.AccessToken.findById(token.id); - exists && await Self.logout(token.id); - } catch (err) { + // Schedule to remove current token + setTimeout(async() => { + try { + const exists = await models.AccessToken.findById(token.id); + exists && await Self.logout(token.id); + } catch (error) { // eslint-disable-next-line no-console - console.error(err); - } - }, courtesyTime * 1000); + console.error(error); + const body = JSON.stringify({err: error, token}); + await handleError(body); + throw new Error(error); + } + }, courtesyTime * 1000); - // Get scopes + // Get scopes - let createTokenOptions = {}; - const {scopes} = token; - if (scopes) - createTokenOptions = {scopes: [scopes[0]]}; - // Create new accessToken - const user = await Self.findById(token.userId); - const accessToken = await user.accessTokens.create(createTokenOptions); + let createTokenOptions = {}; + const {scopes} = token; + if (scopes) + createTokenOptions = {scopes: [scopes[0]]}; + // Create new accessToken + const user = await Self.findById(token.userId); + accessToken = await user.accessTokens.create(createTokenOptions); - return {id: accessToken.id, ttl: accessToken.ttl}; + return {id: accessToken.id, ttl: accessToken.ttl}; + } catch (error) { + const body = JSON.stringify({error: error.message, token, accessToken}); + await handleError(body); + throw new Error(error); + } }; }; + +async function handleError(body, tag = 'renewToken') { + await models.Application.rawSql('CALL util.debugAdd(?,?);', [tag, body]); +} -- 2.40.1 From bfb6689835359d72cd9e6806f1c81d8dab044f92 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 20 Jun 2024 11:50:10 +0000 Subject: [PATCH 259/413] test: add CALL util.debugAdd --- back/methods/vn-user/specs/renew-token.spec.js | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js index 70e7473d1..8f1bb54c1 100644 --- a/back/methods/vn-user/specs/renew-token.spec.js +++ b/back/methods/vn-user/specs/renew-token.spec.js @@ -61,4 +61,21 @@ describe('Renew Token', () => { expect(error).toBeUndefined(); expect(response.id).toEqual(ctx.req.accessToken.id); }); + + it('throw error', async() => { + let error; + + try { + await models.VnUser.renewToken({req: {token: null}}); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + const query = 'SELECT * FROM util.debug'; + + const debugLog = await models.Application.rawSql(query, null); + + expect(debugLog.length).toEqual(1); + }); }); -- 2.40.1 From 833a7c87db39ef0bdd10b13f2b2d060098b2fcdb Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 20 Jun 2024 16:26:56 +0200 Subject: [PATCH 260/413] feat boxPicking refs #7357 --- loopback/locale/es.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 047774684..714475374 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -365,6 +365,5 @@ "You can only have one PDA": "Solo puedes tener un PDA", "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", - "Payment method is required": "El método de pago es obligatorio", - "CLIENT_NOT_ESPECIFIED": "CLIENT_NOT_ESPECIFIED" + "Payment method is required": "El método de pago es obligatorio" } \ No newline at end of file -- 2.40.1 From 68f48de6f0b6564b53fae47c08dcf6bd0c7041dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 20 Jun 2024 17:14:38 +0200 Subject: [PATCH 261/413] feat: sincro client supplier sage refs #7595 --- .../sage/procedures/accountingMovements_add.sql | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/db/routines/sage/procedures/accountingMovements_add.sql b/db/routines/sage/procedures/accountingMovements_add.sql index ada954334..8c129beb2 100644 --- a/db/routines/sage/procedures/accountingMovements_add.sql +++ b/db/routines/sage/procedures/accountingMovements_add.sql @@ -410,15 +410,26 @@ BEGIN FROM sage.movConta mc JOIN vn.supplier s ON s.account = mc.CodigoCuenta WHERE NOT enlazadoSage - )SELECT idClientSupplier, `type` + ),clientSupplierSync AS( + SELECT idClientSupplier, `type` + FROM sage.clientSupplier cs + WHERE isSync + ) + SELECT idClientSupplier, `type` FROM sage.clientSupplier cs WHERE NOT isSync UNION SELECT id, 'C' - FROM client + FROM client c + LEFT JOIN clientSupplierSync cs ON cs.idClientSupplier = c.id + AND cs.Type ='C' + WHERE cs.idClientSupplier IS NULL UNION SELECT id, 'P' - FROM supplier; + FROM supplier s + LEFT JOIN clientSupplierSync cs ON cs.idClientSupplier = s.id + AND cs.Type ='P' + WHERE cs.idClientSupplier IS NULL; CALL clientSupplier_add(vCompanyFk); -- 2.40.1 From ed49c98c1c51ee5f7848e4a7d7ca811b1d93640e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Thu, 20 Jun 2024 18:18:03 +0200 Subject: [PATCH 262/413] fnpmeat: previas con sitema de reservas refs #6861 --- db/routines/vn/procedures/itemShelvingSale_setQuantity.sql | 5 +---- db/routines/vn/triggers/itemShelvingSale_afterInsert.sql | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index 700821592..f3fed7c44 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -55,16 +55,13 @@ BEGIN SELECT id INTO vItemShelvingFk FROM itemShelving - WHERE id = vItemShelvingFk - AND FALSE + WHERE id = vItemShelvingFk FOR UPDATE; UPDATE itemShelving SET visible = GREATEST(0, visible - vQuantity) WHERE id = vItemShelvingFk; - - SELECT SUM(IF(isPicked, 0, quantity)), SUM(quantity) INTO vRemainingQuantity, vTotalQuantity FROM itemShelvingSale diff --git a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql index 0c609d328..ef0048b34 100644 --- a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql +++ b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql @@ -6,7 +6,7 @@ BEGIN UPDATE sale s JOIN operator o ON o.workerFk = account.myUser_getId() - SET s.isPicked = IF(o.isOnReservationMode, isPicked, TRUE) + SET s.isPicked = IF(o.isOnReservationMode, s.isPicked, TRUE) WHERE id = NEW.saleFk; END$$ DELIMITER ; \ No newline at end of file -- 2.40.1 From ba48d93c1e97cd94f8ef2e5a60f1e9dc8bd89c88 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Thu, 20 Jun 2024 23:28:11 +0200 Subject: [PATCH 263/413] perf(salix): refs #6264 #6264 remove save token as debug row --- back/methods/vn-user/renew-token.js | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index ae554d398..ae2d36e3e 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -16,44 +16,44 @@ module.exports = Self => { accessScopes: ['DEFAULT', 'read:multimedia']}); Self.renewToken = async function(ctx) { - let accessToken; - let token; + let createTokenOptions = {}; + let token; let isNotExceeded; try { token = ctx.req.accessToken; + const {courtesyTime} = await models.AccessTokenConfig.findOne({ fields: ['courtesyTime'] }); - const isNotExceeded = await Self.validateToken(ctx); + isNotExceeded = await Self.validateToken(ctx); if (isNotExceeded) return token; // Schedule to remove current token setTimeout(async() => { + let exists; try { - const exists = await models.AccessToken.findById(token.id); + exists = await models.AccessToken.findById(token.id); exists && await Self.logout(token.id); } catch (error) { // eslint-disable-next-line no-console console.error(error); - const body = JSON.stringify({err: error, token}); + const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, exists}; await handleError(body); throw new Error(error); } }, courtesyTime * 1000); // Get scopes - - let createTokenOptions = {}; const {scopes} = token; if (scopes) createTokenOptions = {scopes: [scopes[0]]}; // Create new accessToken const user = await Self.findById(token.userId); - accessToken = await user.accessTokens.create(createTokenOptions); + const accessToken = await user.accessTokens.create(createTokenOptions); return {id: accessToken.id, ttl: accessToken.ttl}; } catch (error) { - const body = JSON.stringify({error: error.message, token, accessToken}); + const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, createTokenOptions, isNotExceeded}; await handleError(body); throw new Error(error); } @@ -61,5 +61,6 @@ module.exports = Self => { }; async function handleError(body, tag = 'renewToken') { + body = JSON.stringify(body); await models.Application.rawSql('CALL util.debugAdd(?,?);', [tag, body]); } -- 2.40.1 From 13952f60e178ef6a147fe8f98cdd5e84aafce9c0 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 21 Jun 2024 07:18:10 +0200 Subject: [PATCH 264/413] feat boxPicking refs #7357 --- back/models/expedition_PrintOut.json | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/back/models/expedition_PrintOut.json b/back/models/expedition_PrintOut.json index 6f521cda3..23a2fdbc4 100644 --- a/back/models/expedition_PrintOut.json +++ b/back/models/expedition_PrintOut.json @@ -13,12 +13,7 @@ "description": "id expeditionFk" }, "itemFk": { - "type": "number", - "required": true - }, - "shelvingFk": { - "type": "string", - "required": true + "type": "number" } } } \ No newline at end of file -- 2.40.1 From fe154b9ee84f9db7c5e4edaa0ffd25b9156a7e4b Mon Sep 17 00:00:00 2001 From: Pako Date: Fri, 21 Jun 2024 08:32:22 +0200 Subject: [PATCH 265/413] sref --- .../supplierPackaging_ReportSource.sql | 37 +++++++++---------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index a8e506244..63285203b 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -22,7 +22,7 @@ BEGIN landed, `in`, `out`, - warehouse, + sref, buyingValue, IF ( NOT (@vItemFk <=> sub.itemFk), @@ -31,19 +31,20 @@ BEGIN ) balance, @vItemFk := sub.itemFk previousItemFk FROM ( - SELECT supplierFk, - itemFk, - longName, - supplier, - CONCAT('E',entryFk) entryFk, - landed, - `in`, - `out`, - warehouse, - buyingValue - FROM supplierPackaging - WHERE supplierFk = vSupplierFk - AND landed >= vFromDated + SELECT sp.supplierFk, + sp.itemFk, + sp.longName, + sp.supplier, + CONCAT('E',sp.entryFk) entryFk, + sp.landed, + sp.`in`, + sp.`out`, + e.invoiceNumber sref, + sp.buyingValue + FROM supplierPackaging sp + JOIN entry e ON e.id = sp.entryFk + WHERE sp.supplierFk = vSupplierFk + AND sp.landed >= vFromDated UNION ALL SELECT vSupplierFk, itemFk, @@ -68,7 +69,7 @@ BEGIN DATE(t.shipped), -LEAST(s.quantity,0) `in`, GREATEST(s.quantity,0) `out`, - w.name, + t.cmrFk, s.price * (100 - s.discount) / 100 FROM sale s JOIN item i ON i.id = s.itemFk @@ -76,7 +77,6 @@ BEGIN JOIN ticket t ON t.id = s.ticketFk JOIN client c ON c.id = t.clientFk JOIN supplier su ON su.nif = c.fi - JOIN warehouse w ON w.id = t.warehouseFk WHERE su.id = vSupplierFk AND t.shipped >= vFromDated AND p.isPackageReturnable @@ -111,7 +111,7 @@ BEGIN DATE(t.shipped), -LEAST(tp.quantity,0) `in`, GREATEST(tp.quantity,0) `out`, - w.name, + t.cmrFk, 0 FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk @@ -119,7 +119,6 @@ BEGIN JOIN ticket t ON t.id = tp.ticketFk JOIN client c ON c.id = t.clientFk JOIN supplier su ON su.nif = c.fi - JOIN warehouse w ON w.id = t.warehouseFk WHERE su.id = vSupplierFk AND t.shipped >= vFromDated AND p.isPackageReturnable @@ -157,7 +156,7 @@ BEGIN landed, CAST(`in` AS DECIMAL(10,0)) `in`, CAST(`out` AS DECIMAL(10,0)) `out`, - warehouse, + sref, buyingValue, balance FROM tSupplierPackaging -- 2.40.1 From 42b483e27e28878722206ee07cea699d4575cb43 Mon Sep 17 00:00:00 2001 From: alexm Date: Fri, 21 Jun 2024 08:35:35 +0200 Subject: [PATCH 266/413] feat: refs #7555 remove account.password__ --- db/versions/11111-tealAralia/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11111-tealAralia/00-firstScript.sql diff --git a/db/versions/11111-tealAralia/00-firstScript.sql b/db/versions/11111-tealAralia/00-firstScript.sql new file mode 100644 index 000000000..4ef10d5f2 --- /dev/null +++ b/db/versions/11111-tealAralia/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE account.`user` DROP COLUMN password__; -- 2.40.1 From c42a21bc6f8ed7fd42dd4eb28d7e4ebdb2fa09ec Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 21 Jun 2024 11:47:34 +0200 Subject: [PATCH 267/413] fix: refs #19537 changes required --- .../templates/reports/invoice-incoterms/sql/incoterms.sql | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/print/templates/reports/invoice-incoterms/sql/incoterms.sql b/print/templates/reports/invoice-incoterms/sql/incoterms.sql index f3566ae30..bbe4b2a0d 100644 --- a/print/templates/reports/invoice-incoterms/sql/incoterms.sql +++ b/print/templates/reports/invoice-incoterms/sql/incoterms.sql @@ -2,11 +2,6 @@ WITH tickets AS( SELECT id, packages, addressFk, weight FROM ticket WHERE refFk= ? -) , weight AS( -SELECT weight - FROM tickets - WHERE weight - LIMIT 1 ), volume AS( SELECT SUM(volume) volume FROM tickets t @@ -20,7 +15,7 @@ SELECT GROUP_CONCAT(DISTINCT ir.description ORDER BY ir.description SEPARATOR ' )SELECT SUM(t.packages), a.incotermsFk, ic.name incotermsName, - w.weight, + MAX(t.weight) weight, ca.fiscalName customsAgentName, ca.street customsAgentStreet, ca.nif customsAgentNif, @@ -34,4 +29,3 @@ SELECT GROUP_CONCAT(DISTINCT ir.description ORDER BY ir.description SEPARATOR ' LEFT JOIN vn.customsAgent ca ON ca.id = a.customsAgentFk JOIN volume v JOIN intrastat i - LEFT JOIN weight w ON TRUE -- 2.40.1 From 3fa7eb1d2aa03ca39289bb9836f5b997c0de0ca5 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 21 Jun 2024 13:01:19 +0200 Subject: [PATCH 268/413] feat itemShelving_filterBuyer refs #7023 --- db/routines/vn/procedures/itemShelving_filterBuyer.sql | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/db/routines/vn/procedures/itemShelving_filterBuyer.sql b/db/routines/vn/procedures/itemShelving_filterBuyer.sql index 894a14464..2fdf21ee1 100644 --- a/db/routines/vn/procedures/itemShelving_filterBuyer.sql +++ b/db/routines/vn/procedures/itemShelving_filterBuyer.sql @@ -15,13 +15,14 @@ proc:BEGIN SELECT * FROM (SELECT sub.itemFk, sub.longName, - CONCAT('Hoy quedan por sacar ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, + CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, CONCAT(IF(sub2.itemFk, IF(sub2.pendiente > (sub.upstairs + sub.downstairs),'(1) ','(2) '),'(3) ' ),sub.producer) producer, sub.upstairs, sub.downstairs, sub.visible, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho, - sub.name itemColour + sub.name itemColour, + CAST(sub2.pendiente AS DECIMAL(10,0)) pendingAmount FROM (SELECT iss.itemFk, CONCAT(i.longName, ' ', IFNULL(i.size, ''),' ', IFNULL(i.subName, '') ) longName, '' size, @@ -52,13 +53,14 @@ proc:BEGIN UNION ALL SELECT v.item_id, i.longName, - CONCAT('Hoy quedan por sacar ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, + CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, CONCAT(IF(sub5.pendiente,'(0) ','(3) ')) producer, 0, 0, v.visible, v.visible nicho, - ik.name itemColour + ik.name itemColour, + CAST(sub5.pendiente AS DECIMAL(10,0) pendingAmount FROM cache.visible v JOIN item i ON i.id = v.item_id LEFT JOIN ink ik ON ik.id = i.inkFk -- 2.40.1 From 41316537006c336064476cadd7add125ed74bbe9 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 21 Jun 2024 13:02:36 +0200 Subject: [PATCH 269/413] feat itemShelving_filterBuyer refs #7023 --- db/routines/vn/procedures/itemShelving_filterBuyer.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/itemShelving_filterBuyer.sql b/db/routines/vn/procedures/itemShelving_filterBuyer.sql index 2fdf21ee1..d4675ea0e 100644 --- a/db/routines/vn/procedures/itemShelving_filterBuyer.sql +++ b/db/routines/vn/procedures/itemShelving_filterBuyer.sql @@ -60,7 +60,7 @@ proc:BEGIN v.visible, v.visible nicho, ik.name itemColour, - CAST(sub5.pendiente AS DECIMAL(10,0) pendingAmount + CAST(sub5.pendiente AS DECIMAL(10,0)) pendingAmount FROM cache.visible v JOIN item i ON i.id = v.item_id LEFT JOIN ink ik ON ik.id = i.inkFk -- 2.40.1 From 24cf23dddc0ef4c42407ef7576689fff1767132f Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 21 Jun 2024 13:16:01 +0200 Subject: [PATCH 270/413] feat: refs #62add travelKgPercentage table and model --- .../11114-goldenDracena/00-firstScript.sql | 18 ++++++++++++++++ .../methods/travel/extraCommunityFilter.js | 14 ++++++++++++- modules/travel/back/model-config.json | 5 ++++- .../back/models/travel-kg-percentage.json | 21 +++++++++++++++++++ 4 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 db/versions/11114-goldenDracena/00-firstScript.sql create mode 100644 modules/travel/back/models/travel-kg-percentage.json diff --git a/db/versions/11114-goldenDracena/00-firstScript.sql b/db/versions/11114-goldenDracena/00-firstScript.sql new file mode 100644 index 000000000..0b6581faf --- /dev/null +++ b/db/versions/11114-goldenDracena/00-firstScript.sql @@ -0,0 +1,18 @@ +-- Place your SQL code here +CREATE TABLE IF NOT EXISTS travelKgPercentage ( + value INT(3) PRIMARY KEY, + className VARCHAR(50) +); + +INSERT IGNORE INTO travelKgPercentage (value, className) + VALUES + (80, 'primary'), + (100, 'alert'); + +INSERT IGNORE INTO salix.ACL + SET model = 'TravelKgPercentage', + property = '*', + accessType = 'READ', + permission = 'ALLOW', + principalType = 'ROLE', + principalId = 'employee'; \ No newline at end of file diff --git a/modules/travel/back/methods/travel/extraCommunityFilter.js b/modules/travel/back/methods/travel/extraCommunityFilter.js index 488297318..dcb704ff5 100644 --- a/modules/travel/back/methods/travel/extraCommunityFilter.js +++ b/modules/travel/back/methods/travel/extraCommunityFilter.js @@ -138,7 +138,19 @@ module.exports = Self => { b.stickers * IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000 ) as DECIMAL(10,0) - ) as volumeKg + ) as volumeKg, + GREATEST( + CAST(SUM(b.weight * b.stickers) AS INT), + CAST( + SUM(vc.aerealVolumetricDensity * + b.stickers * + IF(pkg.volume, + pkg.volume, + pkg.width * pkg.depth * pkg.height + ) / 1000000 + ) AS INT + ) + / t.kg * 100, 0) percentageKg FROM travel t LEFT JOIN supplier s ON s.id = t.cargoSupplierFk LEFT JOIN entry e ON e.travelFk = t.id diff --git a/modules/travel/back/model-config.json b/modules/travel/back/model-config.json index ed5c071b3..952ce0d20 100644 --- a/modules/travel/back/model-config.json +++ b/modules/travel/back/model-config.json @@ -11,6 +11,9 @@ "Thermograph": { "dataSource": "vn" }, + "TravelKgPercentage": { + "dataSource": "vn" + }, "TravelThermograph": { "dataSource": "vn" }, @@ -20,4 +23,4 @@ "Temperature": { "dataSource": "vn" } -} +} \ No newline at end of file diff --git a/modules/travel/back/models/travel-kg-percentage.json b/modules/travel/back/models/travel-kg-percentage.json new file mode 100644 index 000000000..e99a88999 --- /dev/null +++ b/modules/travel/back/models/travel-kg-percentage.json @@ -0,0 +1,21 @@ +{ + "name": "TravelKgPercentage", + "base": "VnModel", + "mixins": { + "Loggable": true + }, + "options": { + "mysql": { + "table": "travelKgPercentage" + } + }, + "properties": { + "value": { + "type": "number", + "id": true + }, + "className": { + "type": "string" + } + } +} \ No newline at end of file -- 2.40.1 From 5ef0dffa3e23d82a10a63ed26b126da05def2230 Mon Sep 17 00:00:00 2001 From: jorgep Date: Fri, 21 Jun 2024 13:38:00 +0200 Subject: [PATCH 271/413] fix: refs #6238 add scheme --- db/versions/11114-goldenDracena/00-firstScript.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/versions/11114-goldenDracena/00-firstScript.sql b/db/versions/11114-goldenDracena/00-firstScript.sql index 0b6581faf..cc283f418 100644 --- a/db/versions/11114-goldenDracena/00-firstScript.sql +++ b/db/versions/11114-goldenDracena/00-firstScript.sql @@ -1,10 +1,10 @@ -- Place your SQL code here -CREATE TABLE IF NOT EXISTS travelKgPercentage ( +CREATE TABLE IF NOT EXISTS vn.travelKgPercentage ( value INT(3) PRIMARY KEY, className VARCHAR(50) ); -INSERT IGNORE INTO travelKgPercentage (value, className) +INSERT IGNORE INTO vn.travelKgPercentage (value, className) VALUES (80, 'primary'), (100, 'alert'); -- 2.40.1 From 9022f6211639d163a4049962077d0d0d7acff180 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 24 Jun 2024 08:03:43 +0200 Subject: [PATCH 272/413] feat: refs #5855 changes required --- db/routines/vn/procedures/copyComponentsFromSaleList.sql | 2 +- db/routines/vn/procedures/itemShelving_inventory.sql | 2 +- db/routines/vn/procedures/ticket_add.sql | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/copyComponentsFromSaleList.sql b/db/routines/vn/procedures/copyComponentsFromSaleList.sql index ab75486d1..8db8409f1 100644 --- a/db/routines/vn/procedures/copyComponentsFromSaleList.sql +++ b/db/routines/vn/procedures/copyComponentsFromSaleList.sql @@ -30,6 +30,6 @@ BEGIN JOIN tmp.saleList s ON s.saleFk = sc.saleFk JOIN tNewSaleList ns ON ns.orden = s.orden; - DROP TEMPORARY TABLE IF EXISTS tNewSaleList; + DROP TEMPORARY TABLE tNewSaleList; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelving_inventory.sql b/db/routines/vn/procedures/itemShelving_inventory.sql index 6d780c342..f4b8ae165 100644 --- a/db/routines/vn/procedures/itemShelving_inventory.sql +++ b/db/routines/vn/procedures/itemShelving_inventory.sql @@ -60,6 +60,6 @@ BEGIN AND p.sectorFk = vSectorFk ORDER BY p.pickingOrder; - DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit; + DROP TEMPORARY TABLE tmp.stockMisfit; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_add.sql b/db/routines/vn/procedures/ticket_add.sql index c85000218..d9b68997c 100644 --- a/db/routines/vn/procedures/ticket_add.sql +++ b/db/routines/vn/procedures/ticket_add.sql @@ -66,7 +66,7 @@ BEGIN CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); END IF; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; + DROP TEMPORARY TABLE tmp.zoneGetShipped; END IF; INSERT INTO ticket ( -- 2.40.1 From ea0b0dc779f027491ce6c2eccea1ba4b3e32d493 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 24 Jun 2024 08:08:39 +0200 Subject: [PATCH 273/413] fix: business overlapping --- .../vn/triggers/business_beforeUpdate.sql | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/db/routines/vn/triggers/business_beforeUpdate.sql b/db/routines/vn/triggers/business_beforeUpdate.sql index 4b7a10041..7dc69bc75 100644 --- a/db/routines/vn/triggers/business_beforeUpdate.sql +++ b/db/routines/vn/triggers/business_beforeUpdate.sql @@ -12,23 +12,21 @@ BEGIN END IF; IF !(OLD.started <=> NEW.started AND OLD.ended <=> NEW.ended) THEN - - SELECT COUNT(*) > 0 INTO isOverlapping - FROM business b - WHERE (util.hasDateOverlapped( - NEW.started, - IFNULL(NEW.ended, b.started), - b.started, - IFNULL(b.ended, NEW.started)) - OR (NEW.ended <=> NULL AND b.ended <=> NULL)) - AND b.id <> OLD.id - AND workerFk = OLD.workerFk; + SELECT util.hasDateOverlapped( + started, + ended, + NEW.started, + IFNULL(NEW.ended, b.started) + ) isOverlapped INTO isOverlapping + FROM vn.business b + WHERE workerFk = NEW.workerFK + AND b.id <> NEW.id + ORDER BY isOverlapped DESC + LIMIT 1; IF isOverlapping THEN CALL util.throw ('IS_OVERLAPPING'); END IF; - END IF; - END$$ DELIMITER ; -- 2.40.1 From 8c5f468087cd7f50ac00d574961f1c556441c0a6 Mon Sep 17 00:00:00 2001 From: Pako Date: Mon, 24 Jun 2024 10:30:25 +0200 Subject: [PATCH 274/413] tested proc --- .../supplierPackaging_ReportSource.sql | 47 ++++++++++--------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index a3401843a..2426417c5 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -1,14 +1,14 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplierPackaging_ReportSource`( +CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplierPackaging_ReportSource`( vFromDated DATE, vSupplierFk INT ) BEGIN /** -* Selecciona los embalajes de un proveedor a partir de una fecha +* Create a report with packaging balance * -* @param vFromDated Fecha de la que partir -* @param vSupplierFk Id del proveedor +* @param vFromDated Starting date +* @param vSupplierFk Supplier ID */ SET @vBalance = 0; SET @vItemFk = NULL; @@ -22,7 +22,7 @@ BEGIN landed, `in`, `out`, - warehouse, + sref, buyingValue, IF ( NOT (@vItemFk <=> sub.itemFk), @@ -31,19 +31,20 @@ BEGIN ) balance, @vItemFk := sub.itemFk previousItemFk FROM ( - SELECT supplierFk, - itemFk, - longName, - supplier, - CONCAT('E',entryFk) entryFk, - landed, - `in`, - `out`, - warehouse, - buyingValue - FROM supplierPackaging - WHERE supplierFk = vSupplierFk - AND landed >= vFromDated + SELECT sp.supplierFk, + sp.itemFk, + sp.longName, + sp.supplier, + CONCAT('E',sp.entryFk) entryFk, + sp.landed, + sp.`in`, + sp.`out`, + e.invoiceNumber sref, + sp.buyingValue + FROM supplierPackaging sp + JOIN entry e ON e.id = sp.entryFk + WHERE sp.supplierFk = vSupplierFk + AND sp.landed >= vFromDated UNION ALL SELECT vSupplierFk, itemFk, @@ -68,7 +69,7 @@ BEGIN DATE(t.shipped), -LEAST(s.quantity,0) `in`, GREATEST(s.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, s.price * (100 - s.discount) / 100 FROM sale s JOIN item i ON i.id = s.itemFk @@ -99,6 +100,7 @@ BEGIN WHERE su.id = vSupplierFk AND t.shipped < vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY s.itemFk UNION ALL SELECT vSupplierFk, @@ -109,7 +111,7 @@ BEGIN DATE(t.shipped), -LEAST(tp.quantity,0) `in`, GREATEST(tp.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, 0 FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk @@ -138,8 +140,9 @@ BEGIN JOIN client c ON c.id = t.clientFk JOIN supplier su ON su.nif = c.fi WHERE su.id = vSupplierFk - AND t.shipped >= vFromDated + AND t.shipped < vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY p.itemFk ORDER BY itemFk, landed, entryFk ) sub @@ -153,7 +156,7 @@ BEGIN landed, CAST(`in` AS DECIMAL(10,0)) `in`, CAST(`out` AS DECIMAL(10,0)) `out`, - warehouse, + sref, buyingValue, balance FROM tSupplierPackaging -- 2.40.1 From f999010c6c670fa20c35814e3741d8eb59f008f9 Mon Sep 17 00:00:00 2001 From: Pako Date: Mon, 24 Jun 2024 10:32:12 +0200 Subject: [PATCH 275/413] tested proc --- .../supplierPackaging_ReportSource.sql | 45 ++++++++++--------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index a3401843a..63285203b 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -5,10 +5,10 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplierPackaging_R ) BEGIN /** -* Selecciona los embalajes de un proveedor a partir de una fecha +* Create a report with packaging balance * -* @param vFromDated Fecha de la que partir -* @param vSupplierFk Id del proveedor +* @param vFromDated Starting date +* @param vSupplierFk Supplier ID */ SET @vBalance = 0; SET @vItemFk = NULL; @@ -22,7 +22,7 @@ BEGIN landed, `in`, `out`, - warehouse, + sref, buyingValue, IF ( NOT (@vItemFk <=> sub.itemFk), @@ -31,19 +31,20 @@ BEGIN ) balance, @vItemFk := sub.itemFk previousItemFk FROM ( - SELECT supplierFk, - itemFk, - longName, - supplier, - CONCAT('E',entryFk) entryFk, - landed, - `in`, - `out`, - warehouse, - buyingValue - FROM supplierPackaging - WHERE supplierFk = vSupplierFk - AND landed >= vFromDated + SELECT sp.supplierFk, + sp.itemFk, + sp.longName, + sp.supplier, + CONCAT('E',sp.entryFk) entryFk, + sp.landed, + sp.`in`, + sp.`out`, + e.invoiceNumber sref, + sp.buyingValue + FROM supplierPackaging sp + JOIN entry e ON e.id = sp.entryFk + WHERE sp.supplierFk = vSupplierFk + AND sp.landed >= vFromDated UNION ALL SELECT vSupplierFk, itemFk, @@ -68,7 +69,7 @@ BEGIN DATE(t.shipped), -LEAST(s.quantity,0) `in`, GREATEST(s.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, s.price * (100 - s.discount) / 100 FROM sale s JOIN item i ON i.id = s.itemFk @@ -99,6 +100,7 @@ BEGIN WHERE su.id = vSupplierFk AND t.shipped < vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY s.itemFk UNION ALL SELECT vSupplierFk, @@ -109,7 +111,7 @@ BEGIN DATE(t.shipped), -LEAST(tp.quantity,0) `in`, GREATEST(tp.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, 0 FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk @@ -138,8 +140,9 @@ BEGIN JOIN client c ON c.id = t.clientFk JOIN supplier su ON su.nif = c.fi WHERE su.id = vSupplierFk - AND t.shipped >= vFromDated + AND t.shipped < vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY p.itemFk ORDER BY itemFk, landed, entryFk ) sub @@ -153,7 +156,7 @@ BEGIN landed, CAST(`in` AS DECIMAL(10,0)) `in`, CAST(`out` AS DECIMAL(10,0)) `out`, - warehouse, + sref, buyingValue, balance FROM tSupplierPackaging -- 2.40.1 From 5f329fde38055a153436297a05f9145c8c82959c Mon Sep 17 00:00:00 2001 From: Pako Date: Mon, 24 Jun 2024 10:32:51 +0200 Subject: [PATCH 276/413] or replace --- db/routines/vn/procedures/supplierPackaging_ReportSource.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index 2426417c5..63285203b 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplierPackaging_ReportSource`( +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`supplierPackaging_ReportSource`( vFromDated DATE, vSupplierFk INT ) -- 2.40.1 From cf79711f6aa2e0c675fedd11bc61cf67e3b87b4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Mon, 24 Jun 2024 13:30:03 +0200 Subject: [PATCH 277/413] feat: previas con sitema de reservas refs #6861 --- db/routines/vn/procedures/itemShelvingSale_doReserve.sql | 6 +++--- db/routines/vn/procedures/itemShelvingSale_reallocate.sql | 2 +- db/routines/vn/procedures/itemShelvingSale_setQuantity.sql | 2 +- db/versions/10852-pinkOak/00-firstScript.sql | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/db/routines/vn/procedures/itemShelvingSale_doReserve.sql b/db/routines/vn/procedures/itemShelvingSale_doReserve.sql index d7bf4b181..629e303b3 100644 --- a/db/routines/vn/procedures/itemShelvingSale_doReserve.sql +++ b/db/routines/vn/procedures/itemShelvingSale_doReserve.sql @@ -2,7 +2,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_doReserve`() proc: BEGIN /** - * Genera reservas de la tabla itemShelvingSaleReserv + * Genera reservas de la tabla vn.itemShelvingSaleReserve */ DECLARE vDone BOOL; DECLARE vSaleFk INT; @@ -26,7 +26,7 @@ proc: BEGIN CREATE OR REPLACE TEMPORARY TABLE tSale ENGINE = MEMORY - SELECT id, saleFk FROM itemShelvingSaleReserv; + SELECT id, saleFk FROM itemShelvingSaleReserve; OPEN vSales; @@ -43,7 +43,7 @@ proc: BEGIN CLOSE vSales; - DELETE iss FROM itemShelvingSaleReserv iss JOIN tSale s ON s.id = iss.id; + DELETE iss FROM itemShelvingSaleReserve iss JOIN tSale s ON s.id = iss.id; DROP TEMPORARY TABLE tSale; diff --git a/db/routines/vn/procedures/itemShelvingSale_reallocate.sql b/db/routines/vn/procedures/itemShelvingSale_reallocate.sql index ab898bdd4..85230a386 100644 --- a/db/routines/vn/procedures/itemShelvingSale_reallocate.sql +++ b/db/routines/vn/procedures/itemShelvingSale_reallocate.sql @@ -28,7 +28,7 @@ BEGIN WHERE id = vItemShelvingFk AND itemFk = vItemFk; - INSERT INTO itemShelvingSaleReserv (saleFk) + INSERT INTO itemShelvingSaleReserve (saleFk) SELECT DISTINCT iss.saleFk FROM itemShelvingSale iss JOIN itemShelving ish ON ish.id = iss.itemShelvingFk diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index 00427039a..42f915ead 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -86,7 +86,7 @@ BEGIN COMMIT; IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN - INSERT INTO itemShelvingSaleReserv (saleFk) + INSERT INTO itemShelvingSaleReserve (saleFk) SELECT vSaleFk; CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk); END IF; diff --git a/db/versions/10852-pinkOak/00-firstScript.sql b/db/versions/10852-pinkOak/00-firstScript.sql index 7739976e6..41b75c7e1 100644 --- a/db/versions/10852-pinkOak/00-firstScript.sql +++ b/db/versions/10852-pinkOak/00-firstScript.sql @@ -16,11 +16,11 @@ ALTER TABLE vn.itemShelving ADD available INT NULL; UPDATE vn.itemShelving SET available = visible; -CREATE TABLE vn.itemShelvingSaleReserv ( +CREATE TABLE vn.itemShelvingSaleReserve ( `id` int(11) NOT NULL AUTO_INCREMENT, `saleFk` int(11) NOT NULL, PRIMARY KEY (`id`), - KEY `itemShelvingSaleReserv_ibfk_1` (`saleFk`) + KEY `itemShelvingSaleReserve_ibfk_1` (`saleFk`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed itemShelvingSale to reserve'; -- 2.40.1 From 134c38b9fdb7df7dcb237b625c5f68b020fdccfb Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 25 Jun 2024 08:57:21 +0200 Subject: [PATCH 278/413] refs #6753 Hotfix --- modules/ticket/back/methods/ticket/saveSign.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/saveSign.js b/modules/ticket/back/methods/ticket/saveSign.js index b5c662089..ed54a5074 100644 --- a/modules/ticket/back/methods/ticket/saveSign.js +++ b/modules/ticket/back/methods/ticket/saveSign.js @@ -140,7 +140,7 @@ module.exports = Self => { await models.TicketDms.create({ticketFk: ticket.id, dmsFk: dms[0].id}, myOptions); await ticket.updateAttribute('isSigned', true, myOptions); - await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [params.ticketFk, params.code], myOptions); + await Self.rawSql(`CALL vn.ticket_setState(?, ?)`, [ticketId, 'DELIVERED'], myOptions); if (ticket?.address()?.province()?.country()?.code != 'ES' && ticket.cmrFk) { await models.Ticket.saveCmr(ctx, [ticketId], myOptions); -- 2.40.1 From cf0f80142fed798c3307565a69158d7dba9276c4 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 25 Jun 2024 09:24:34 +0200 Subject: [PATCH 279/413] hotFix: create view vn.expeditionTruck --- db/routines/vn/views/expeditionTruck.sql | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 db/routines/vn/views/expeditionTruck.sql diff --git a/db/routines/vn/views/expeditionTruck.sql b/db/routines/vn/views/expeditionTruck.sql new file mode 100644 index 000000000..065869de0 --- /dev/null +++ b/db/routines/vn/views/expeditionTruck.sql @@ -0,0 +1,11 @@ +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn`.`expeditionTruck` +AS SELECT `rs`.`id` AS `id`, + `rs`.`roadmapFk` AS `roadmapFk`, + `rs`.`eta` AS `eta`, + `rs`.`description` AS `description`, + `rs`.`bufferFk` AS `bufferFk`, + `rs`.`created` AS `created`, + `rs`.`userFk` AS `userFk` +FROM `vn`.`roadmapStop` `rs`; -- 2.40.1 From 6150f64e88853ce330ebef47ba42d96cc9b677d8 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 25 Jun 2024 09:29:42 +0200 Subject: [PATCH 280/413] build: db dump --- db/dump/.dump/data.sql | 97 ++-- db/dump/.dump/privileges.sql | 61 +- db/dump/.dump/structure.sql | 1057 ++++++++++++++++++---------------- db/dump/.dump/triggers.sql | 207 +++++-- 4 files changed, 809 insertions(+), 613 deletions(-) diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index 18e3fd4b5..c979ea1a2 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -3,7 +3,7 @@ USE `util`; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -INSERT INTO `version` VALUES ('vn-database','11090','7adf4a373d19ce126adbc7b1077f69a74559c09a','2024-06-11 08:32:36','11094'); +INSERT INTO `version` VALUES ('vn-database','11114','cf0f80142fed798c3307565a69158d7dba9276c4','2024-06-25 09:25:54','11115'); INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL); @@ -834,19 +834,34 @@ INSERT INTO `versionLog` VALUES ('vn-database','11058','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11059','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11060','00-createRoleReviewer.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11061','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11063','00-roadmapAddress.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11063','01-roadmapStop.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11063','02-roadmapStopGrants.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11064','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11065','00-modifyInvoiceInPrivileges.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11065','01-modifyInvoiceInAcls.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11068','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11069','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11070','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11071','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11074','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11075','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-28 12:54:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11078','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11079','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 08:22:10',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11080','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 12:01:58',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11082','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11083','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-03 10:46:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11084','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11087','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11089','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11090','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11092','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-07 08:21:23',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11093','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:16',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11096','00-addBuyerAcl.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 12:48:51',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11105','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-20 15:36:07',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11106','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11109','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-18 19:09:56',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11114','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; @@ -930,7 +945,7 @@ INSERT INTO `role` VALUES (109,'salesTeamBoss','Jefe de equipo de comerciales',1 INSERT INTO `role` VALUES (110,'palletizer','Paletizadores',1,'2022-12-02 13:56:22','2022-12-02 13:56:30',NULL); INSERT INTO `role` VALUES (111,'entryEditor','Entry editor',1,'2023-01-13 12:21:55','2023-01-13 12:21:55',NULL); INSERT INTO `role` VALUES (112,'maintenance','Personal de mantenimiento',1,'2023-01-19 07:23:35','2023-01-19 07:23:35',NULL); -INSERT INTO `role` VALUES (114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 07:31:16','2023-05-17 13:07:21',NULL); +INSERT INTO `role` VALUES (114,'maintenanceBoss','Jefe de mantenimiento',1,'2023-01-19 07:31:16','2024-06-14 08:56:41',19295); INSERT INTO `role` VALUES (115,'itManagement','TI management',1,'2023-03-29 09:27:55','2023-03-29 09:28:04',NULL); INSERT INTO `role` VALUES (119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 13:51:54','2023-06-07 13:51:54',NULL); INSERT INTO `role` VALUES (120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 09:07:21','2023-06-19 09:07:21',21709); @@ -1212,6 +1227,7 @@ INSERT INTO `roleInherit` VALUES (367,30,73,NULL); INSERT INTO `roleInherit` VALUES (368,130,49,10578); INSERT INTO `roleInherit` VALUES (369,50,130,10578); INSERT INTO `roleInherit` VALUES (370,72,130,10578); +INSERT INTO `roleInherit` VALUES (371,36,35,NULL); INSERT INTO `userPassword` VALUES (1,7,1,0,2,1); @@ -1535,7 +1551,7 @@ INSERT INTO `ACL` VALUES (383,'Sector','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (384,'Sector','*','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'); 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 (387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','$owner'); 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'); @@ -1791,10 +1807,6 @@ INSERT INTO `ACL` VALUES (686,'MailForward','*','*','ALLOW','ROLE','hr'); INSERT INTO `ACL` VALUES (687,'ClientSms','find','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'); -INSERT INTO `ACL` VALUES (691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'); -INSERT INTO `ACL` VALUES (692,'RoadmapStop','*','*','ALLOW','ROLE','production'); -INSERT INTO `ACL` VALUES (693,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'); @@ -1863,7 +1875,7 @@ INSERT INTO `ACL` VALUES (761,'Route','downloadZip','READ','ALLOW','ROLE','emplo INSERT INTO `ACL` VALUES (762,'Route','filter','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (763,'Route','getByWorker','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (764,'Route','getDeliveryPoint','READ','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (765,'Route','getExternalCmrs','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (765,'Route','cmrs','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (766,'Route','getSuggestedTickets','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (767,'Route','getTickets','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (768,'Route','guessPriority','WRITE','ALLOW','ROLE','employee'); @@ -1939,8 +1951,6 @@ INSERT INTO `ACL` VALUES (840,'Locker','*','*','ALLOW','ROLE','hr'); INSERT INTO `ACL` VALUES (841,'Locker','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (842,'Worker','__get__locker','READ','ALLOW','ROLE','hr'); INSERT INTO `ACL` VALUES (843,'Worker','__get__locker','READ','ALLOW','ROLE','productionBoss'); -INSERT INTO `ACL` VALUES (844,'RoadmapStop','*','*','ALLOW','ROLE','production'); -INSERT INTO `ACL` VALUES (845,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (846,'Ticket','refund','WRITE','ALLOW','ROLE','logistic'); INSERT INTO `ACL` VALUES (847,'RouteConfig','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (848,'InvoiceIn','updateInvoiceIn','WRITE','ALLOW','ROLE','administrative'); @@ -1960,6 +1970,19 @@ INSERT INTO `ACL` VALUES (861,'InvoiceIn','toBook','WRITE','ALLOW','ROLE','buyer INSERT INTO `ACL` VALUES (862,'InvoiceIn','deleteById','WRITE','ALLOW','ROLE','buyer'); INSERT INTO `ACL` VALUES (863,'InvoiceIn','create','WRITE','ALLOW','ROLE','administrative'); INSERT INTO `ACL` VALUES (864,'InvoiceIn','create','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (865,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (866,'InvoiceOut','download','READ','ALLOW','ROLE','$owner'); +INSERT INTO `ACL` VALUES (867,'InvoiceIn','*','READ','ALLOW','ROLE','maintenanceBoss'); +INSERT INTO `ACL` VALUES (868,'InvoiceIn','*','READ','ALLOW','ROLE','maintenanceBos'); +INSERT INTO `ACL` VALUES (869,'Ticket','editZone','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (870,'Entry','find','READ','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (871,'RoadmapAddress','*','WRITE','ALLOW','ROLE','palletizerBoss'); +INSERT INTO `ACL` VALUES (872,'RoadmapAddress','*','READ','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (873,'Roadmap','*','WRITE','ALLOW','ROLE','palletizerBoss'); +INSERT INTO `ACL` VALUES (874,'Roadmap','*','READ','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (875,'RoadmapStop','*','WRITE','ALLOW','ROLE','palletizerBoss'); +INSERT INTO `ACL` VALUES (876,'RoadmapStop','*','READ','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (877,'TravelKgPercentage','*','READ','ALLOW','ROLE','employee'); INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee'); INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee'); @@ -2280,7 +2303,7 @@ INSERT INTO `continent` VALUES (3,'África','AF'); INSERT INTO `continent` VALUES (4,'Europa','EU'); INSERT INTO `continent` VALUES (5,'Oceanía','OC'); -INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,110,763,0,0,0,0,25,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,110,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (22,'shopping','COMPRAS',2,3,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (23,'CMA','CAMARA',13,14,NULL,72,1,1,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (31,'it','INFORMATICA',4,5,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); @@ -2291,49 +2314,49 @@ INSERT INTO `department` VALUES (37,'PROD','PRODUCCION',12,35,NULL,72,1,1,1,11,1 INSERT INTO `department` VALUES (38,'picking','SACADO',15,16,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (39,'packing','ENCAJADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',36,37,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (43,'VT','VENTAS',38,71,NULL,0,0,0,1,16,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (44,'management','GERENCIA',72,73,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (46,'delivery','REPARTO',76,77,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',78,79,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (43,'VT','VENTAS',38,69,NULL,0,0,0,1,15,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (44,'management','GERENCIA',70,71,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',72,73,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (46,'delivery','REPARTO',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',76,77,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',39,40,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',84,85,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (55,NULL,'TALLER NATURAL',19,20,14548,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1118,NULL,NULL,NULL); INSERT INTO `department` VALUES (56,NULL,'TALLER ARTIFICIAL',21,22,8470,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1927,NULL,NULL,NULL); -INSERT INTO `department` VALUES (58,'CMP','CAMPOS',86,89,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',90,91,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (58,'CMP','CAMPOS',84,87,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',88,89,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (61,NULL,'VNH',92,95,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',96,97,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (61,NULL,'VNH',90,93,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',94,95,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (68,NULL,'COMPLEMENTOS',23,24,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',98,99,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',96,97,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (80,'spainTeam5','EQUIPO ESPAÑA 5',43,44,4250,0,0,0,2,0,43,'/1/43/','es5_equipo',1,'es5@verdnatura.es',0,0,0,0,NULL,NULL,'5300',NULL); -INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',100,101,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (89,NULL,'COORDINACION',102,103,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (90,NULL,'TRAILER',93,94,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',98,99,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (89,NULL,'COORDINACION',100,101,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (90,NULL,'TRAILER',91,92,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (91,'artificial','ARTIFICIAL',25,26,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (92,NULL,'EQUIPO SILVERIO',45,46,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (94,'spainTeam2','EQUIPO ESPAÑA 2',47,48,3797,0,0,0,2,0,43,'/1/43/','es2_equipo',0,'es2@verdnatura.es',0,0,0,0,NULL,NULL,'5100',NULL); -INSERT INTO `department` VALUES (95,'spainTeam1','EQUIPO ESPAÑA 1',49,50,24065,0,0,0,2,0,43,'/1/43/','es1_equipo',0,'es1@verdnatura.es',0,0,0,0,NULL,NULL,'5000',NULL); +INSERT INTO `department` VALUES (94,'spainTeam2','EQUIPO ESPAÑA 2',47,48,3797,0,0,0,2,0,43,'/1/43/','es2_equipo',1,'es2@verdnatura.es',0,0,0,0,NULL,NULL,'5100',NULL); +INSERT INTO `department` VALUES (95,'spainTeam1','EQUIPO ESPAÑA 1',49,50,24065,0,0,0,2,0,43,'/1/43/','es1_equipo',1,'es1@verdnatura.es',0,0,0,0,NULL,NULL,'5000',NULL); INSERT INTO `department` VALUES (96,NULL,'EQUIPO C LOPEZ',51,52,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (115,NULL,'EQUIPO CLAUDI',53,54,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (123,NULL,'EQUIPO ELENA BASCUÑANA',55,56,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',57,58,NULL,72,0,0,2,0,43,'/1/43/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (125,'spainTeam3','EQUIPO ESPAÑA 3',59,60,1118,0,0,0,2,0,43,'/1/43/','es3_equipo',0,'es3@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL); +INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',102,103,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (125,'spainTeam3','EQUIPO ESPAÑA 3',57,58,1118,0,0,0,2,0,43,'/1/43/','es3_equipo',1,'es3@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL); INSERT INTO `department` VALUES (126,NULL,'PRESERVADO',27,28,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (128,NULL,'PALETIZADO',29,30,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (130,NULL,'REVISION',31,32,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',87,88,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',61,62,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',63,64,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL); -INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',65,66,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL); +INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',85,86,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',59,60,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',61,62,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL); +INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',63,64,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL); INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',104,105,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',106,107,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (137,'sorter','SORTER',108,109,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (139,'spainTeam4','EQUIPO ESPAÑA 4',67,68,3803,0,0,0,2,0,43,'/1/43/','es4_equipo',1,'es4@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL); -INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',69,70,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (139,'spainTeam4','EQUIPO ESPAÑA 4',65,66,3803,0,0,0,2,0,43,'/1/43/','es4_equipo',1,'es4@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL); +INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',67,68,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (141,NULL,'PREVIA',33,34,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); INSERT INTO `docuware` VALUES (1,'deliveryNote','Albaranes cliente','find','find','N__ALBAR_N',NULL); diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql index 00ef1018b..b99a60395 100644 --- a/db/dump/.dump/privileges.sql +++ b/db/dump/.dump/privileges.sql @@ -647,7 +647,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','pgcMaster',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemBarcode','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','host','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticket','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','Update'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceIn','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','inventoryFailure','alexm@%','0000-00-00 00:00:00','Select',''); @@ -982,7 +982,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceCorre INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ink','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','zone','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','XDiario','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','XDiario','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','XDiario','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','workerTimeControlMail','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerTimeControl','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','bi','financial','Greuge_Evolution','alexm@%','0000-00-00 00:00:00','Select',''); @@ -1048,7 +1048,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','userSession','j INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','receipt','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','buy','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','calendarHolidays','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','parking','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','parking','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','role','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','errorLogApp','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','continent','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -1300,7 +1300,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemShelving','g INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','negativeOrigin','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','Vehiculos_consumo','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','entryOrder','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','project','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBoss','machineDms','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','ink','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); @@ -1350,7 +1350,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','warehouse INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','component','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','config','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','componentType','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','machineDms','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','priceFixed','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','itemShelvingSale','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','tagAbbreviation','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','ticketTracking','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert',''); @@ -1361,7 +1361,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','sale_freight INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','accounting','jgallego@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','accounting','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','machineDetail','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketRequest','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','vehicleState','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','expeditionState','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','specialPrice','jgallego@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -1384,6 +1384,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','professionalCategor INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','ticketObservation','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNoteState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNote','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','comparative','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceOutExpense','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','delivery','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','entry','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update',''); @@ -1398,23 +1399,29 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','visit','root@lo INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyDetail','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyReview','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyReview','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','roadmapStop','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','roadmapStop','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','agencyWorkCenter','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','roadmapStop','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','antenna','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','bufferPool','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','enteringLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','expeditionLoading','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','failureLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','movingLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','sorterLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','entryEditor','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientInforma','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','solunionCAP','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientUnpaid','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','pay_dem','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','invoiceOut','guillermo@10.5.1.3','0000-00-00 00:00:00','Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financialBoss','invoiceOut','guillermo@10.5.1.3','0000-00-00 00:00:00','Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financialBoss','accountDetail','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','accountDetail','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBoss','project','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBoss','machineDetail','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','antenna','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','bufferPool','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','enteringLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','expeditionLoading','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','failureLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','movingLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','sorterLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); /*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */; @@ -1474,28 +1481,6 @@ INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','user_id','0 INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','extension','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','name','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','active','0000-00-00 00:00:00','Select'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','editorFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','expenseFkDeductible','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','withholdingSageFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','isVatDeductible','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','bookEntried','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','siiTrascendencyInvoiceInFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','cplusTaxBreakFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','cplusSubjectOpFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','cplusRectificationTypeFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','siiTypeInvoiceInFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','operated','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','booked','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','docFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','companyFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','created','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','currencyFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','supplierRef','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','issued','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','supplierFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','serial','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','serialNumber','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','id','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','routeFk','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','name','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','beachFk','0000-00-00 00:00:00','Update'); @@ -1904,7 +1889,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','invoiceoutboo INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ticket_gettax','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','productionAssi','midnight','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','dipole','employee','expedition_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticketstateupdate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','coolerBoss','itempacking','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesPerson','ticket_clone','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','cache','employee','available_refresh','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); @@ -2151,6 +2135,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','artificialBoss','confection_co INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','remittance_calc','PROCEDURE','alexm@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','developer','connection_kill','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','client_getRisk','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','account','developer','user_hasRole','FUNCTION','root@localhost','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financialBoss','balance_create','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hrBoss','balance_create','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buy_recalcPricesByEntry','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2215,7 +2200,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','logisticAssist','{\"access\":0,\"v INSERT IGNORE INTO `global_priv` VALUES ('','logisticBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','maintenance','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBos','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','manager','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','marketing','{\"access\": 0, \"is_role\": true,\"version_id\":101106}'); INSERT IGNORE INTO `global_priv` VALUES ('','marketingBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index dd068cdc7..cd5b6aa3b 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -3240,11 +3240,12 @@ BEGIN JOIN vn.ticketLastState ts ON ts.ticketFk = t.id JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk JOIN vn.state st ON st.id = tt.stateFk + JOIN vn.alertLevel al ON al.code = 'DELIVERED' WHERE sc.componentFk = 17 AND sc.isGreuge = 0 AND t.shipped >= '2016-10-01' AND t.shipped < util.VN_CURDATE() - AND st.alertLevel >= 3; + AND st.alertLevel >= al.id; DELETE g.* FROM vn.greuge g @@ -8280,7 +8281,7 @@ BEGIN JOIN vn.address a ON a.id = t.addressFk JOIN vn.province p ON p.id = a.provinceFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk LEFT JOIN vn.beach b ON b.code = rm.beachFk LEFT JOIN vn.`zone`z ON z.id = t.zoneFk JOIN vn.agencyMode am ON t.agencyModeFk = am.id @@ -13105,7 +13106,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`( vType INT, vPrefix VARCHAR(255)) BEGIN - + /** * Gets visible items of the specified type at specified date. * @@ -13114,7 +13115,7 @@ BEGIN * @param vType The type id * @param vPrefix The article prefix to filter or %NULL for all * @return tmp.itemVisible Visible items - */ + */ DECLARE vPrefixLen SMALLINT; DECLARE vFilter VARCHAR(255) DEFAULT NULL; DECLARE vDateInv DATE DEFAULT vn.getInventoryDate(); @@ -13123,13 +13124,13 @@ BEGIN GET DIAGNOSTICS CONDITION 1 @message = MESSAGE_TEXT; CALL vn.mail_insert( - 'cau@verdnatura.es', - NULL, + 'cau@verdnatura.es', + NULL, CONCAT('hedera.item_getVisible error: ', @message), CONCAT( - 'warehouse: ', IFNULL(vWarehouse, ''), - ', Fecha:', IFNULL(vDate, ''), - ', tipo: ', IFNULL(vType,''), + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), ', prefijo: ', IFNULL(vPrefix,''))); RESIGNAL; END; @@ -13174,9 +13175,10 @@ BEGIN FROM vn.sale m JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id + JOIN vn.alertLevel al ON al.code = 'DELIVERED' WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() AND t.warehouseFk = vWarehouse - AND s.alertLevel = 3 + AND s.alertLevel = al.id ) t GROUP BY itemFk HAVING quantity > 0; @@ -13208,7 +13210,7 @@ BEGIN IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, CEIL(s.quantity / t.packing) etiquetas FROM vn.item i - JOIN `filter` f ON f.itemFk = i.id + JOIN `filter` f ON f.itemFk = i.id JOIN currentStock s ON s.itemFk = i.id LEFT JOIN tmp t ON t.itemFk = i.id LEFT JOIN vn.packaging p ON p.id = t.packagingFk @@ -14618,7 +14620,7 @@ BEGIN END; -- Carga los datos del pedido - SELECT o.date_send, o.address_id, o.note, a.clientFk, + SELECT o.date_send, o.address_id, o.note, a.clientFk, o.company_id, o.agency_id, c.isTaxDataChecked INTO vDelivery, vAddress, vNotes, vClientId, vCompanyId, vAgencyModeId, vIsTaxDataChecked @@ -14677,6 +14679,7 @@ BEGIN ) SELECT t.id INTO vTicket FROM vn.ticket t + JOIN vn.alertLevel al ON al.code = 'FREE' LEFT JOIN tPrevia tp ON tp.ticketFk = t.id LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id JOIN hedera.`order` o @@ -14687,7 +14690,7 @@ BEGIN WHERE o.id = vSelf AND t.refFk IS NULL AND tp.ticketFk IS NULL - AND IFNULL(tls.alertLevel,0) = 0 + AND (tls.alertLevel IS NULL OR tls.alertLevel = al.id) LIMIT 1; -- Crea el ticket en el caso de no existir uno adecuado @@ -17013,6 +17016,22 @@ SET character_set_client = utf8; 1 AS `companyFk` */; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `clientSupplier` +-- + +DROP TABLE IF EXISTS `clientSupplier`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientSupplier` ( + `companyFk` smallint(6) NOT NULL, + `type` enum('C','P') NOT NULL, + `idClientSupplier` int(11) NOT NULL, + `isSync` tinyint(1) NOT NULL DEFAULT 0, + PRIMARY KEY (`companyFk`,`idClientSupplier`,`type`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Clients and suppliers present in Sage and their synchronization status'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `clientesProveedores` -- @@ -17596,7 +17615,8 @@ BEGIN DECLARE vTransactionExportTaxFreeFk INT; DECLARE vSerialDua VARCHAR(1) DEFAULT 'D'; DECLARE vInvoiceTypeInformativeCode VARCHAR(1); - DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2) ; + DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2); + DECLARE vCompanyCode INT; SELECT SiglaNacion INTO vCountryCanariasCode FROM Naciones @@ -17606,9 +17626,6 @@ BEGIN FROM Naciones WHERE Nacion ='CEUTA Y MELILLA'; - SELECT pendingServiceTransactionTypeFk INTO vDuaTransactionFk - FROM config; - SELECT id INTO vTaxImportFk FROM taxType WHERE code = 'import21'; @@ -17621,10 +17638,14 @@ BEGIN FROM taxType WHERE code = 'import4'; - SELECT definitiveExportTransactionTypeFk INTO vTransactionExportFk - FROM config; - - SELECT shipmentTransactionTypeFk INTO vTransactionExportTaxFreeFk + SELECT shipmentTransactionTypeFk, + definitiveExportTransactionTypeFk, + pendingServiceTransactionTypeFk, + company_getCode(vCompanyFk) + INTO vTransactionExportTaxFreeFk, + vTransactionExportFk, + vDuaTransactionFk, + vCompanyCode FROM config; SELECT codeSage INTO vInvoiceTypeInformativeCode @@ -17639,8 +17660,6 @@ BEGIN WHERE enlazadoSage = FALSE AND Asiento <> 1 ; - CALL clientSupplier_add(vCompanyFk); - CALL pgc_add(vCompanyFk); CALL invoiceOut_manager(vYear, vCompanyFk); CALL invoiceIn_manager(vYear, vCompanyFk); @@ -17733,7 +17752,7 @@ BEGIN ) SELECT 'EN' TipoEntrada, YEAR(x.FECHA) Ejercicio, - company_getCode(vCompanyFk) AS CodigoEmpresa, + vCompanyCode CodigoEmpresa, x.ASIEN Asiento, IF(EURODEBE <> 0 OR (EURODEBE = 0 AND EUROHABER IS NULL), 'D', 'H') CargoAbono, @@ -17866,20 +17885,6 @@ BEGIN WHERE m.CargoAbono = 'D' AND m.enlazadoSage = FALSE; --- Elimina cuentas de cliente/proveedor que no se utilizarán en la importación - DELETE cp - FROM clientesProveedores cp - LEFT JOIN movConta mc ON mc.codigoCuenta = cp.codigoCuenta - AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL; - --- Elimina cuentas contables que no se utilizarán en la importación - DELETE pc - FROM planCuentasPGC pc - LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta - AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL; - -- DUAS UPDATE movConta mci JOIN vn.XDiario x ON x.ASIEN = mci.Asiento @@ -17986,6 +17991,56 @@ BEGIN AND importeDivisa > 0 AND ImporteAsiento < 0; + CREATE OR REPLACE TEMPORARY TABLE tmp.clientSupplier + (INDEX(idClientSupplier, `type`)) + ENGINE = MEMORY + WITH client AS( + SELECT DISTINCT c.id + FROM sage.movConta mc + JOIN vn.client c ON c.accountingAccount = mc.CodigoCuenta + WHERE NOT enlazadoSage + ),supplier AS( + SELECT DISTINCT s.id + FROM sage.movConta mc + JOIN vn.supplier s ON s.account = mc.CodigoCuenta + WHERE NOT enlazadoSage + ),clientSupplierSync AS( + SELECT idClientSupplier, `type` + FROM sage.clientSupplier cs + WHERE isSync + ) + SELECT idClientSupplier, `type` + FROM sage.clientSupplier cs + WHERE NOT isSync + UNION + SELECT id, 'C' + FROM client c + LEFT JOIN clientSupplierSync cs ON cs.idClientSupplier = c.id + AND cs.Type ='C' + WHERE cs.idClientSupplier IS NULL + UNION + SELECT id, 'P' + FROM supplier s + LEFT JOIN clientSupplierSync cs ON cs.idClientSupplier = s.id + AND cs.Type ='P' + WHERE cs.idClientSupplier IS NULL; + + CALL clientSupplier_add(vCompanyFk); + + INSERT IGNORE INTO sage.clientSupplier (companyFk, `type`, idClientSupplier, isSync) + SELECT vCompanyCode, `type`, idClientSupplier, FALSE + FROM tmp.clientSupplier; + + DROP TEMPORARY TABLE tmp.clientSupplier; + + CALL pgc_add(vCompanyFk); +-- Elimina cuentas contables que no se utilizarán en la importación + DELETE pc + FROM planCuentasPGC pc + LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta + AND mc.enlazadoSage = FALSE + WHERE mc.codigoCuenta IS NULL; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18027,13 +18082,18 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `clientSupplier_add`(vCompanyFk INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `clientSupplier_add`( + vCompanyFk INT +) BEGIN /** - * Prepara los datos de clientes y proveedores para exportarlos a Sage - * @vCompanyFk Empresa dela que se quiere trasladar datos + * Inserta en la tabla sage.clientesProveedores los datos de clientes y proveedores + * que se actualizaran o se daran de alta en Sage + * @vCompanyFk Id de empresa + * @table tmp.clientSupplier(idClientSupplier, `type`) */ DECLARE vCountryCeutaMelillaFk INT; + DECLARE vCompanyCode INT DEFAULT company_getCode(vCompanyFk); DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2); SELECT SiglaNacion INTO vCountryCanariasCode @@ -18073,7 +18133,7 @@ BEGIN Email1, iban) SELECT - company_getCode(vCompanyFk), + vCompanyCode, 'C', c.id, c.socialName, @@ -18081,7 +18141,7 @@ BEGIN IFNULL(c.street, ''), c.accountingAccount, @fi := IF(cu.code = LEFT(TRIM(c.fi), 2) AND c.isVies, MID(TRIM(c.fi), 3, LENGTH(TRIM(c.fi))-1), TRIM(c.fi)), - IF(c.isVies, CONCAT(IFNULL(cu.viesCode,cu.code), @fi ), TRIM(c.fi)), + IF(c.isVies, CONCAT(IFNULL(cu.viesCode,cu.code), @fi ), TRIM(c.fi)), IFNULL(c.postcode, ''), IFNULL(c.city, ''), IFNULL(pr.CodigoProvincia, ''), @@ -18103,15 +18163,14 @@ BEGIN IFNULL(SUBSTR(c.email, 1, LOCATE(',', CONCAT(c.email, ','))-1), ''), IFNULL(c.iban, '') FROM vn.`client` c - JOIN clientLastTwoMonths clm ON clm.clientFk = c.id + JOIN tmp.clientSupplier cs ON cs.idClientSupplier = c.id LEFT JOIN vn.country cu ON cu.id = c.countryFk LEFT JOIN Naciones n ON n.countryFk = cu.id LEFT JOIN vn.province p ON p.id = c.provinceFk LEFT JOIN Provincias pr ON pr.provinceFk = p.id - WHERE c.isRelevant - AND clm.companyFk = vCompanyFk + WHERE cs.type = 'C' UNION ALL - SELECT company_getCode(vCompanyFk), + SELECT vCompanyCode, 'P', s.id, s.name, @@ -18135,19 +18194,17 @@ BEGIN IFNULL(s.transactionTypeSageFk, 0), IFNULL(s.withholdingSageFk, '0'), IFNULL(SUBSTR(sc.email, 1, (COALESCE(NULLIF(LOCATE(',', sc.email), 0), 99) - 1)), ''), - IFNULL(iban, '') + IFNULL(sa.iban, '') FROM vn.supplier s - JOIN supplierLastThreeMonths pl ON pl.supplierFk = s.id + JOIN tmp.clientSupplier cs ON cs.idClientSupplier = s.id LEFT JOIN vn.country co ON co.id = s.countryFk LEFT JOIN Naciones n ON n.countryFk = co.id LEFT JOIN vn.province p ON p.id = s.provinceFk LEFT JOIN Provincias pr ON pr.provinceFk = p.id LEFT JOIN vn.supplierContact sc ON sc.supplierFk = s.id LEFT JOIN vn.supplierAccount sa ON sa.supplierFk = s.id - WHERE pl.companyFk = vCompanyFk AND - s.isActive AND - s.nif <> '' - GROUP BY pl.supplierFk, pl.companyFk; + WHERE cs.type = 'P' + GROUP BY s.id; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -20439,7 +20496,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON t.routeFk = rm.routeFk - LEFT JOIN vn.roadmapStop rs ON rm.expeditionTruckFk = rs.id + LEFT JOIN vn.roadmapStop rs ON rm.roadmapStopFk = rs.id WHERE e.id = vExpeditionFk; RETURN vDayMinute; @@ -23592,12 +23649,13 @@ BEGIN m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked + m.isPicked OR s.alertLevel > al.id isPicked FROM vn.sale m JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.item i ON i.id = m.itemFk JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.alertLevel al ON al.code = 'ON_PREPARATION' WHERE ( vTableId IS NULL OR (vTableName = 'ticket' AND t.id = vTableId) @@ -25637,7 +25695,10 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `debugAdd`(vVariable VARCHAR(255), vValue VARCHAR(255)) +CREATE DEFINER=`root`@`localhost` PROCEDURE `debugAdd`( + vVariable VARCHAR(255), + vValue TEXT +) MODIFIES SQL DATA BEGIN /** @@ -28592,7 +28653,7 @@ CREATE TABLE `clientLog` ( `action` set('insert','update','delete') NOT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, - `changedModel` enum('Client','Address','ClientContact','ClientDms','ClientObservation','ClientSample','Greuge','Recovery','TpvTransaction','WorkerDms','Sms') NOT NULL DEFAULT 'Client', + `changedModel` enum('Client','Address','ClientContact','ClientDms','ClientObservation','ClientSample','ClientUnpaid','Greuge','Recovery','TpvTransaction','WorkerDms','Sms') NOT NULL DEFAULT 'Client', `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)), `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)), `changedModelId` int(11) NOT NULL, @@ -28706,6 +28767,24 @@ CREATE TABLE `clientProtected` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de clientes y comerciales que no se van a ver afectados por las desagsignaciones mensuales automaticas'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `clientRate` +-- + +DROP TABLE IF EXISTS `clientRate`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientRate` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL, + `dated` date NOT NULL DEFAULT current_timestamp(), + `value` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `clientRate_unique` (`clientFk`,`dated`), + CONSTRAINT `clientRate_client_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `clientRisk` -- @@ -29567,7 +29646,6 @@ CREATE TABLE `country` ( `continentFk` tinyint(4) DEFAULT NULL, `a3Code` int(11) DEFAULT NULL COMMENT 'Código país para a3', `isSocialNameUnique` tinyint(1) NOT NULL DEFAULT 1, - `country` varchar(25) GENERATED ALWAYS AS (`name`) VIRTUAL, PRIMARY KEY (`id`), UNIQUE KEY `country_unique` (`code`), KEY `Id_Paisreal` (`politicalCountryFk__`), @@ -31063,7 +31141,7 @@ SET character_set_client = utf8; 1 AS `routeFk`, 1 AS `scanFk`, 1 AS `expeditionFk`, - 1 AS `expeditionTruckFk`, + 1 AS `roadmapStopFk`, 1 AS `warehouseFk`, 1 AS `lastPacked`, 1 AS `ticketFk` */; @@ -31233,6 +31311,7 @@ CREATE TABLE `expeditionState` ( `expeditionFk` int(11) NOT NULL, `typeFk` int(11) NOT NULL, `userFk` int(11) DEFAULT NULL, + `isScanned` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`id`), KEY `expeditionState_FK` (`expeditionFk`), KEY `expeditionState_FK_1` (`typeFk`), @@ -31324,7 +31403,6 @@ SET character_set_client = utf8; /*!50001 CREATE VIEW `expeditionTruck` AS SELECT 1 AS `id`, 1 AS `roadmapFk`, - 1 AS `warehouseFk`, 1 AS `eta`, 1 AS `description`, 1 AS `bufferFk`, @@ -31332,68 +31410,6 @@ SET character_set_client = utf8; 1 AS `userFk` */; SET character_set_client = @saved_cs_client; --- --- Temporary table structure for view `expeditionTruck_Control` --- - -DROP TABLE IF EXISTS `expeditionTruck_Control`; -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expeditionTruck_Control` AS SELECT - 1 AS `id`, - 1 AS `ETD`, - 1 AS `description`, - 1 AS `ticketsSinBultos`, - 1 AS `pallets`, - 1 AS `routes`, - 1 AS `scans`, - 1 AS `expeditions`, - 1 AS `fallos`, - 1 AS `lastPacked` */; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `expeditionTruck_Control_Detail` --- - -DROP TABLE IF EXISTS `expeditionTruck_Control_Detail`; -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expeditionTruck_Control_Detail` AS SELECT - 1 AS `id`, - 1 AS `eta`, - 1 AS `destino`, - 1 AS `pallet`, - 1 AS `routes`, - 1 AS `scans`, - 1 AS `destinos`, - 1 AS `fallos`, - 1 AS `lastPacked` */; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `expeditionTruck_Control_Detail_Pallet` --- - -DROP TABLE IF EXISTS `expeditionTruck_Control_Detail_Pallet`; -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail_Pallet`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expeditionTruck_Control_Detail_Pallet` AS SELECT - 1 AS `id`, - 1 AS `eta`, - 1 AS `destino`, - 1 AS `pallet`, - 1 AS `route`, - 1 AS `scans`, - 1 AS `destinos`, - 1 AS `fallos`, - 1 AS `expeditionTruckFk`, - 1 AS `lastPacked` */; -SET character_set_client = @saved_cs_client; - -- -- Table structure for table `expense` -- @@ -31628,13 +31644,13 @@ CREATE TABLE `floramondoConfig` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `forecastedBalance` +-- Table structure for table `forecastedBalance__` -- -DROP TABLE IF EXISTS `forecastedBalance`; +DROP TABLE IF EXISTS `forecastedBalance__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `forecastedBalance` ( +CREATE TABLE `forecastedBalance__` ( `id` int(11) NOT NULL AUTO_INCREMENT, `description` varchar(45) DEFAULT NULL, `amount` double NOT NULL DEFAULT 0, @@ -31647,7 +31663,7 @@ CREATE TABLE `forecastedBalance` ( KEY `empresa_prevision_idx` (`companyFk`), CONSTRAINT `Saldos_PrevisionCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, CONSTRAINT `banco_prevision` FOREIGN KEY (`accountingFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Aqui ponemos los gastos e ingresos pendientes de introducir '; +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-05-21'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -33197,11 +33213,11 @@ CREATE TABLE `itemShelving` ( `buyFk` int(11) DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), - UNIQUE KEY `itemShelving_UN` (`buyFk`,`shelvingFk`), KEY `itemShelving_fk1_idx` (`itemFk`), KEY `itemShelving_fk2_idx` (`shelvingFk`), KEY `itemShelving_fk3_idx` (`packagingFk`), KEY `itemShelving_fk3_idx1` (`userFk`), + KEY `itemShelvingBuy_FK` (`buyFk`), CONSTRAINT `itemShelvingBuy_FK` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`), CONSTRAINT `itemShelving_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, @@ -35804,13 +35820,20 @@ CREATE TABLE `productionConfig` ( `defaultSectorFk` int(10) unsigned NOT NULL DEFAULT 37 COMMENT 'Default sector', `scannableCodeType` enum('qr','barcode') NOT NULL DEFAULT 'barcode', `scannablePreviusCodeType` enum('qr','barcode') NOT NULL DEFAULT 'barcode', + `itemOlderReviewHours` int(11) NOT NULL DEFAULT 0 COMMENT 'Horas que se tienen en cuenta para comprobar si un ítem es más viejo.', + `sectorFromCode` varchar(15) DEFAULT NULL COMMENT 'Sector origen que se revisa ítems más nuevos al parkinear', + `sectorToCode` varchar(15) DEFAULT NULL COMMENT 'Sector destino que se revisa ítems más nuevos al parkinear', PRIMARY KEY (`id`), KEY `productionConfig_FK` (`shortageAddressFk`), KEY `productionConfig_FK_1` (`clientSelfConsumptionFk`), KEY `productionConfig_FK_2` (`addressSelfConsumptionFk`), + KEY `productionConfig_sector_FK` (`sectorFromCode`), + KEY `productionConfig_sector_FK_1` (`sectorToCode`), CONSTRAINT `productionConfig_FK` FOREIGN KEY (`shortageAddressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE, CONSTRAINT `productionConfig_FK_1` FOREIGN KEY (`clientSelfConsumptionFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `productionConfig_FK_2` FOREIGN KEY (`addressSelfConsumptionFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE, + CONSTRAINT `productionConfig_sector_FK` FOREIGN KEY (`sectorFromCode`) REFERENCES `sector` (`code`) ON UPDATE CASCADE, + CONSTRAINT `productionConfig_sector_FK_1` FOREIGN KEY (`sectorToCode`) REFERENCES `sector` (`code`) ON UPDATE CASCADE, CONSTRAINT `productionConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los parámetros que condicionan la producción'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36473,6 +36496,21 @@ CREATE TABLE `roadmap` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Troncales diarios que se contratan'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `roadmapAddress` +-- + +DROP TABLE IF EXISTS `roadmapAddress`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `roadmapAddress` ( + `addressFk` int(11) NOT NULL, + `isActive` tinyint(4) DEFAULT 1, + PRIMARY KEY (`addressFk`), + CONSTRAINT `roadmapAddress_address_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Direcciones de los troncales'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `roadmapStop` -- @@ -36483,7 +36521,7 @@ DROP TABLE IF EXISTS `roadmapStop`; CREATE TABLE `roadmapStop` ( `id` int(11) NOT NULL AUTO_INCREMENT, `roadmapFk` int(10) unsigned DEFAULT NULL, - `warehouseFk` smallint(6) unsigned DEFAULT NULL, + `addressFk` int(11) DEFAULT NULL, `eta` datetime DEFAULT NULL COMMENT 'Estimated time of arrival', `description` varchar(45) NOT NULL, `bufferFk` int(11) DEFAULT NULL COMMENT 'buffer destino de las cajas', @@ -36492,13 +36530,13 @@ CREATE TABLE `roadmapStop` ( PRIMARY KEY (`id`), KEY `expeditionTruck_idx1` (`eta`), KEY `expeditionTruck_FK` (`bufferFk`), - KEY `expeditionTruck_FK_1` (`warehouseFk`), KEY `expeditionTruck_FK_2` (`roadmapFk`), KEY `expeditionTruck_FK_3` (`userFk`), + KEY `roadmapStop_roadmapAddress_FK` (`addressFk`), CONSTRAINT `expeditionTruck_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `expeditionTruck_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, CONSTRAINT `expeditionTruck_FK_2` FOREIGN KEY (`roadmapFk`) REFERENCES `roadmap` (`id`) ON UPDATE CASCADE, - CONSTRAINT `expeditionTruck_FK_3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE + CONSTRAINT `expeditionTruck_FK_3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE, + CONSTRAINT `roadmapStop_roadmapAddress_FK` FOREIGN KEY (`addressFk`) REFERENCES `roadmapAddress` (`addressFk`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Distintas paradas que hacen los trocales'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36872,21 +36910,22 @@ CREATE TABLE `routesMonitor` ( `m3` decimal(10,1) DEFAULT NULL, `priority` int(11) NOT NULL DEFAULT 0, `etd` time DEFAULT NULL, - `expeditionTruckFk` int(11) DEFAULT NULL, + `roadmapStopFk` int(11) DEFAULT NULL, `m3boxes` decimal(10,1) DEFAULT NULL, `bufferFk` int(11) DEFAULT NULL COMMENT 'Buffer del sorter por el que se quiere sacar esa ruta', `isPickingAllowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Los tickets de esta ruta se pueden preparar', `editorFk` int(10) unsigned DEFAULT NULL, + `expeditionTruckFk` int(11) GENERATED ALWAYS AS (`roadmapStopFk`) VIRTUAL, PRIMARY KEY (`routeFk`), KEY `routesMonitor_FK` (`bufferFk`), KEY `routesMonitor_FK_2` (`beachFk`), KEY `routesMonitor_FK_1` (`dockFk`), - KEY `routesMonitor_FK_3` (`expeditionTruckFk`), + KEY `routesMonitor_FK_3` (`roadmapStopFk`), KEY `routesMonitor_fk_editor` (`editorFk`), CONSTRAINT `routesMonitor_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `routesMonitor_FK_1` FOREIGN KEY (`dockFk`) REFERENCES `dock` (`code`) ON UPDATE CASCADE, CONSTRAINT `routesMonitor_FK_2` FOREIGN KEY (`beachFk`) REFERENCES `beach` (`code`) ON UPDATE CASCADE, - CONSTRAINT `routesMonitor_FK_3` FOREIGN KEY (`expeditionTruckFk`) REFERENCES `roadmapStop` (`id`) ON UPDATE CASCADE, + CONSTRAINT `routesMonitor_FK_3` FOREIGN KEY (`roadmapStopFk`) REFERENCES `roadmapStop` (`id`) ON UPDATE CASCADE, CONSTRAINT `routesMonitor_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39160,7 +39199,7 @@ CREATE TABLE `ticketPackagingStartingStock` ( KEY `ticketPackagingStartingStock_fk2_idx` (`packagingFk`), KEY `ticketPackagingStartingStock_fk3_idx` (`itemFk`), CONSTRAINT `ticketPackagingStartingStock_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `ticketPackagingStartingStock_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketPackagingStartingStock_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, CONSTRAINT `ticketPackagingStartingStock_fk3` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39879,6 +39918,20 @@ CREATE TABLE `travelConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `travelKgPercentage` +-- + +DROP TABLE IF EXISTS `travelKgPercentage`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `travelKgPercentage` ( + `value` int(3) NOT NULL, + `className` varchar(50) DEFAULT NULL, + PRIMARY KEY (`value`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `travelLog` -- @@ -48182,7 +48235,9 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_afterUpsert`(vSelf INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_afterUpsert`( + vSelf INT +) BEGIN /** * Triggered actions when a buy is updated or inserted. @@ -48199,7 +48254,7 @@ BEGIN DECLARE vIsFeedStock BOOL; DECLARE vWeight DECIMAL(10,2); DECLARE vPacking INT; - + SELECT b.entryFk, b.itemFk, i.packingOut, @@ -48230,8 +48285,11 @@ BEGIN WHERE e.id = vEntryFk; IF vIsMerchandise THEN + IF vWarehouse IS NULL THEN + CALL util.throw('The entry does not have travel'); + END IF; - REPLACE itemCost SET + REPLACE itemCost SET itemFk = vItemFk, warehouseFk = vWarehouse, cm3 = buy_getUnitVolume(vSelf), @@ -48257,7 +48315,7 @@ BEGIN WHERE b.id = vSelf; END IF; - CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck + CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck SELECT vSelf id; CALL buy_checkItem(); END ;; @@ -51672,6 +51730,8 @@ BEGIN DECLARE vLockName VARCHAR(215); DECLARE vLockTime INT DEFAULT 30; DECLARE vFreeWagonFk INT; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; DECLARE c1 CURSOR FOR SELECT ticketFk, `lines`, m3 @@ -51691,12 +51751,18 @@ BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; + IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); - CALL util.debugAdd(JSON_OBJECT( - 'type', 'releaseLock', - 'userFk', vUserFk - ), vLockName); -- Tmp + CALL util.debugAdd('collection_new', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk + )); -- Tmp END IF; RESIGNAL; @@ -52613,7 +52679,7 @@ BEGIN LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.agency a ON a.id = am.agencyFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded @@ -55323,13 +55389,13 @@ BEGIN LIMIT 1; IF vPalletFk IS NULL THEN - SELECT expeditionTruckFk + SELECT roadmapStopFk INTO vTruckFk FROM ( - SELECT rm.expeditionTruckFk, count(*) n + SELECT rm.roadmapStopFk, count(*) n FROM vn.routesMonitor rm JOIN tExpedition e ON e.routeFk = rm.routeFk - GROUP BY expeditionTruckFk + GROUP BY roadmapStopFk ORDER BY n DESC LIMIT 1) sub; @@ -55795,53 +55861,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `expeditionTruck_Add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_Add`(vHour VARCHAR(5), vDescription VARCHAR(45)) -BEGIN - - INSERT INTO vn.roadmapStop(eta,description) - VALUES(CONCAT(util.VN_CURDATE(), ' ', vHour), vDescription); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `expeditionTruck_List` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_List`() -BEGIN - - SELECT id truckFk, - eta, - description Destino - FROM roadmapStop - WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) - ORDER BY eta; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `expedition_getFromRoute` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -55866,7 +55885,8 @@ BEGIN t.addressFk, a.nickname, sub2.itemPackingTypeConcat, - est.code + est.code, + es.isScanned FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = e.ticketFk @@ -55884,6 +55904,10 @@ BEGIN GROUP BY sub.ticketFk ) sub2 ON sub2.ticketFk = t.id LEFT JOIN expeditionStateType est ON est.id = e.stateTypeFk + LEFT JOIN expeditionState es ON es.id = ( + SELECT MAX(id) + FROM expeditionState es + WHERE expeditionFk = e.id) WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE ORDER BY r.created, t.priority DESC; END ;; @@ -55953,7 +55977,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE e.id = vExpeditionFk; END ;; @@ -56040,7 +56064,7 @@ BEGIN LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE e.id = vExpeditionFk; END ;; @@ -58276,8 +58300,8 @@ BEGIN OR t.isDeleted OR c.hasToInvoice = FALSE OR itc.id IS NULL - OR a.id IS NULL - OR (vTaxArea = 'WORLD' + OR a.id IS NULL + OR (vTaxArea = 'WORLD' AND (a.customsAgentFk IS NULL OR a.incotermsFk IS NULL)); SELECT SUM(s.quantity * s.price * (100 - s.discount)/100) <> 0 @@ -58349,7 +58373,9 @@ BEGIN FROM tmp.ticketToInvoice ti LEFT JOIN ticketState ts ON ti.id = ts.ticketFk JOIN state s - WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id); + JOIN alertLevel al ON al.code = 'DELIVERED' + WHERE (ts.alertLevel IS NULL OR ts.alertLevel < al.id) + AND s.`code` = getAlert3State(ti.id); INSERT INTO ticketTracking(stateFk, ticketFk, userFk) SELECT * FROM tmp.updateInter; @@ -59438,7 +59464,7 @@ BEGIN ish.isChecked, sub.isAllChecked FROM itemShelvingStock iss - JOIN itemShelving ish ON ish.shelvingFk = iss.shelvingFk + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk LEFT JOIN ( SELECT itemFk, IF( @@ -60138,9 +60164,16 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`( + vShelvingFk VARCHAR(8), + vBarcode VARCHAR(22), + vQuantity INT, + vPackagingFk VARCHAR(10), + vGrouping INT, + vPacking INT, + vWarehouseFk INT +) BEGIN - /** * Añade registro o lo actualiza si ya existe. * @@ -60162,12 +60195,7 @@ BEGIN SELECT barcodeToItem(vBarcode) INTO vItemFk; IF vBuyFk IS NULL THEN - CALL cache.last_buy_refresh(FALSE); - - SELECT buy_id INTO vBuyFk - FROM cache.last_buy - WHERE item_id = vItemFk - AND warehouse_id = vWarehouseFk; + CALL util.throw('The buy is required'); END IF; IF vPacking IS NULL @@ -62827,6 +62855,7 @@ BEGIN FROM sale s JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + AND t.warehouseFk AND s.quantity != 0 AND (vItemFk IS NULL OR s.itemFk = vItemFk) AND (vWarehouseFk IS NULL OR t.warehouseFk = vWarehouseFk) @@ -62837,7 +62866,7 @@ BEGIN t.warehouseInFk FROM buy b JOIN entry e ON e.id = b.entryFk - LEFT JOIN travel t ON t.id = e.travelFk + JOIN travel t ON t.id = e.travelFk WHERE t.landed BETWEEN vDatedFrom AND vDatedTo AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND !e.isExcludedFromAvailable @@ -62850,7 +62879,7 @@ BEGIN t.warehouseOutFk FROM buy b JOIN entry e ON e.id = b.entryFk - LEFT JOIN travel t ON t.id = e.travelFk + JOIN travel t ON t.id = e.travelFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND (vWarehouseFk IS NULL OR t.warehouseOutFk = vWarehouseFk) AND !e.isExcludedFromAvailable @@ -63601,6 +63630,239 @@ BEGIN */ UPDATE item SET itemPackingTypeFk = vItemPackingTypeFk WHERE id = vItem; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_valuateInventory` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `item_valuateInventory`( +vDated DATE +) +BEGIN +DECLARE vInventoried DATE; +DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE; +DECLARE vInventoryClone DATE; +DECLARE vDateDayEnd DATETIME; +DECLARE vInventorySupplierFk INT; + +SELECT inventorySupplierFk INTO vInventorySupplierFk +FROM entryConfig; + +SET vDateDayEnd = util.dayEnd(vDated); + +SELECT tr.landed INTO vInventoried +FROM travel tr +JOIN `entry` e ON e.travelFk = tr.id +WHERE tr.landed <= vDateDayEnd +AND e.supplierFk = vInventorySupplierFk +ORDER BY tr.landed DESC +LIMIT 1; + +SET vHasNotInventory = (vInventoried IS NULL); + +IF vHasNotInventory THEN +SELECT landed INTO vInventoryClone +FROM travel tr +JOIN `entry` e ON e.travelFk = tr.id +WHERE tr.landed >= vDated +AND e.supplierFk = vInventorySupplierFk +ORDER BY landed ASC +LIMIT 1; + +SET vInventoried = vDated + INTERVAL 1 DAY; +SET vDateDayEnd = vInventoryClone; +END IF; + +CREATE OR REPLACE TEMPORARY TABLE tInventory( +warehouseFk SMALLINT, +itemFk BIGINT, +quantity INT, +volume DECIMAL(10,2), +cost DOUBLE DEFAULT 0, +total DOUBLE DEFAULT 0, +warehouseInventory VARCHAR(20), +PRIMARY KEY (warehouseInventory, itemFk) USING HASH +) +ENGINE = MEMORY; + + +IF vHasNotInventory THEN +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseInFk, +b.itemFk, +SUM(b.quantity), +w.name +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse w ON w.id = tr.warehouseInFk +WHERE tr.landed = vDateDayEnd +AND e.supplierFk = vInventorySupplierFk +AND w.valuatedInventory +AND t.isInventory +GROUP BY tr.warehouseInFk, b.itemFk; +ELSE +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseInFk, +b.itemFk, +SUM(b.quantity), +w.name +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse w ON w.id = tr.warehouseInFk +WHERE tr.landed = vInventoried +AND e.supplierFk = vInventorySupplierFk +AND w.valuatedInventory +AND t.isInventory +GROUP BY tr.warehouseInFk, b.itemFk; +END IF; + + +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseInFk, +b.itemFk, +b.quantity * IF(vHasNotInventory, -1, 1), +w.name +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse w ON w.id = tr.warehouseInFk +WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd +AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE) +AND NOT e.isRaid +AND w.valuatedInventory +AND t.isInventory +AND e.supplierFk <> vInventorySupplierFk +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory, -1, 1)); + + +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseOutFk, +b.itemFk, +b.quantity * IF(vHasNotInventory, 1, -1), +w.name +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse w ON w.id = tr.warehouseOutFk +WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd +AND NOT e.isRaid +AND w.valuatedInventory +AND t.isInventory +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory,1,-1)); + + +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT w.id, +s.itemFk, +s.quantity * IF(vHasNotInventory, 1, -1), +w.name +FROM sale s +JOIN ticket t ON t.id = s.ticketFk +JOIN `client` c ON c.id = t.clientFk +JOIN item i ON i.id = s.itemFk +JOIN itemType it ON it.id = i.typeFk +JOIN warehouse w ON w.id = t.warehouseFk +WHERE t.shipped BETWEEN vInventoried AND vDateDayEnd +AND w.valuatedInventory +AND it.isInventory +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1); + + +IF vDated = util.VN_CURDATE() THEN +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT w.id, +s.itemFk, +s.quantity * IF(vHasNotInventory, 0, 1), +w.name +FROM sale s +JOIN ticket t ON t.id = s.ticketFk +JOIN `client` c ON c.id = t.clientFk +JOIN item i ON i.id = s.itemFk +JOIN itemType it ON it.id = i.typeFk +JOIN warehouse w ON w.id = t.warehouseFk +WHERE t.shipped BETWEEN vDated AND vDateDayEnd +AND NOT (s.isPicked OR t.isLabeled) +AND w.valuatedInventory +AND it.isInventory +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 0, 1); +END IF; + + +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseInFk, +b.itemFk, +b.quantity, +CONCAT(wOut.`name`, ' - ', wIn.`name`) +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse wIn ON wIn.id = tr.warehouseInFk +JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk +WHERE vDated >= tr.shipped AND vDated < tr.landed +AND NOT isRaid +AND wIn.valuatedInventory +AND t.isInventory +AND e.isConfirmed +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity); + +CALL buyUltimate(NULL, vDateDayEnd); + +DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity; + +UPDATE tInventory i +JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.itemFk = bu.itemFk +JOIN buy b ON b.id = bu.buyFk +LEFT JOIN itemCost ic ON ic.itemFk = i.itemFk +AND ic.warehouseFk = i.warehouseFk +SET i.total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)), +i.cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0), +i.volume = i.quantity * ic.cm3delivery / 1000000; + +SELECT ti.warehouseFk, +i.id, +i.longName, +i.size, +ti.quantity, +ti.volume, +tp.name itemTypeName, +ic.name itemCategoryName, +ti.cost, +ti.total, +ti.warehouseInventory +FROM tInventory ti +JOIN warehouse w ON w.id = warehouseFk +JOIN item i ON i.id = ti.itemFk +JOIN itemType tp ON tp.id = i.typeFk +JOIN itemCategory ic ON ic.id = tp.categoryFk +WHERE w.valuatedInventory +AND ti.total > 0; + +DROP TEMPORARY TABLE +tmp.buyUltimate, +tInventory; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65248,14 +65510,16 @@ BEGIN (PRIMARY KEY (ticketFk)) ENGINE = MEMORY SELECT t.id ticketFk, t.clientFk - FROM vn.ticket t - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - JOIN vn.client c ON c.id = t.clientFk + FROM ticket t + JOIN alertLevel al ON al.code = 'DELIVERED' + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + JOIN client c ON c.id = t.clientFk + WHERE c.typeFk IN ('normal','handMaking','internalUse') AND ( t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate OR ( - ts.alertLevel < 3 + ts.alertLevel < al.id AND t.shipped >= vStartingDate AND t.shipped < util.VN_CURDATE() ) @@ -65383,7 +65647,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `productionControl`( - vWarehouseFk INT, + vWarehouseFk INT, vScopeDays INT ) proc: BEGIN @@ -65450,7 +65714,7 @@ proc: BEGIN wk.code salesPersonCode, p.id provinceFk, tls.productionOrder, - IFNULL(tls.alertLevel, 0) alertLevel, + IFNULL(tls.alertLevel, al.id) alertLevel, t.isBoxed palletized, IF(rm.isPickingAllowed, rm.bufferFk, NULL) ubicacion, tlu.lastUpdated, @@ -65464,6 +65728,7 @@ proc: BEGIN rm.bufferFk FROM tmp.productionTicket tt JOIN ticket t ON tt.ticketFk = t.id + JOIN alertLevel al ON al.code = 'FREE' LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id LEFT JOIN `state` st ON st.id = tst.state LEFT JOIN client c ON c.id = t.clientFk @@ -65484,7 +65749,7 @@ proc: BEGIN LEFT JOIN parking pk ON pk.id = tp.parkingFk WHERE t.warehouseFk = vWarehouseFk AND dm.code IN ('AGENCY', 'DELIVERY', 'PICKUP'); - + UPDATE tmp.productionBuffer pb JOIN ( SELECT pb.ticketFk, GROUP_CONCAT(p.code) previaParking @@ -65492,12 +65757,12 @@ proc: BEGIN JOIN sale s ON s.ticketFk = pb.ticketFk JOIN saleGroupDetail sgd ON sgd.saleFk = s.id JOIN saleGroup sg ON sg.id = sgd.saleGroupFk - JOIN parking p ON p.id = sg.parkingFk + JOIN parking p ON p.id = sg.parkingFk GROUP BY pb.ticketFk ) t ON t.ticketFk = pb.ticketFk SET pb.previaParking = t.previaParking; - -- Problemas por ticket + -- Problemas por ticket ALTER TABLE tmp.productionBuffer CHANGE COLUMN `problem` `problem` VARCHAR(255), ADD COLUMN `collectionH` INT, @@ -66406,7 +66671,7 @@ BEGIN LEFT JOIN ticketTrolley tt ON tt.ticket = t.id LEFT JOIN zone zo ON t.zoneFk = zo.id LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam) GROUP BY t.id ORDER BY cc.code; @@ -66708,7 +66973,7 @@ BEGIN SET rm.m3boxes = sub.m3boxes; UPDATE routesMonitor rm - JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk SET rm.etd = rs.eta; DROP TEMPORARY TABLE tmp.routesMonitor; @@ -70065,10 +70330,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `supplierPackaging_ReportSource`( ) BEGIN /** -* Selecciona los embalajes de un proveedor a partir de una fecha +* Create a report with packaging balance * -* @param vFromDated Fecha de la que partir -* @param vSupplierFk Id del proveedor +* @param vFromDated Starting date +* @param vSupplierFk Supplier ID */ SET @vBalance = 0; SET @vItemFk = NULL; @@ -70082,7 +70347,7 @@ BEGIN landed, `in`, `out`, - warehouse, + sref, buyingValue, IF ( NOT (@vItemFk <=> sub.itemFk), @@ -70091,19 +70356,20 @@ BEGIN ) balance, @vItemFk := sub.itemFk previousItemFk FROM ( - SELECT supplierFk, - itemFk, - longName, - supplier, - CONCAT('E',entryFk) entryFk, - landed, - `in`, - `out`, - warehouse, - buyingValue - FROM supplierPackaging - WHERE supplierFk = vSupplierFk - AND landed >= vFromDated + SELECT sp.supplierFk, + sp.itemFk, + sp.longName, + sp.supplier, + CONCAT('E',sp.entryFk) entryFk, + sp.landed, + sp.`in`, + sp.`out`, + e.invoiceNumber sref, + sp.buyingValue + FROM supplierPackaging sp + JOIN entry e ON e.id = sp.entryFk + WHERE sp.supplierFk = vSupplierFk + AND sp.landed >= vFromDated UNION ALL SELECT vSupplierFk, itemFk, @@ -70128,7 +70394,7 @@ BEGIN DATE(t.shipped), -LEAST(s.quantity,0) `in`, GREATEST(s.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, s.price * (100 - s.discount) / 100 FROM sale s JOIN item i ON i.id = s.itemFk @@ -70159,6 +70425,7 @@ BEGIN WHERE su.id = vSupplierFk AND t.shipped < vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY s.itemFk UNION ALL SELECT vSupplierFk, @@ -70169,7 +70436,7 @@ BEGIN DATE(t.shipped), -LEAST(tp.quantity,0) `in`, GREATEST(tp.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, 0 FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk @@ -70198,8 +70465,9 @@ BEGIN JOIN client c ON c.id = t.clientFk JOIN supplier su ON su.nif = c.fi WHERE su.id = vSupplierFk - AND t.shipped >= vFromDated + AND t.shipped < vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY p.itemFk ORDER BY itemFk, landed, entryFk ) sub @@ -70213,7 +70481,7 @@ BEGIN landed, CAST(`in` AS DECIMAL(10,0)) `in`, CAST(`out` AS DECIMAL(10,0)) `out`, - warehouse, + sref, buyingValue, balance FROM tSupplierPackaging @@ -71253,13 +71521,16 @@ BEGIN DECLARE vShipped DATE; DECLARE vWarehouse TINYINT; DECLARE vAlertLevel INT; + DECLARE vAlertLevelFree INT; - SELECT t.warehouseFk, t.shipped, ts.alertLevel INTO vWarehouse, vShipped, vAlertLevel + SELECT t.warehouseFk, t.shipped, ts.alertLevel, al.id + INTO vWarehouse, vShipped, vAlertLevel, vAlertLevelFree FROM ticket t + JOIN alertLevel al ON al.code = 'FREE' LEFT JOIN ticketState ts ON ts.ticketFk = vTicket WHERE t.id = vTicket; - IF vAlertLevel IS NULL OR vAlertLevel = 0 THEN + IF vAlertLevel IS NULL OR vAlertLevel = vAlertLevelFree THEN IF vShipped >= util.VN_CURDATE() THEN CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped); END IF; @@ -71283,68 +71554,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketMissed_List` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketMissed_List`(vTicketFk INT) -BEGIN - - DECLARE vParkingFk INT; - DECLARE vParked DATETIME; - DECLARE vLevel INT; - DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) - INTO vLevel, vCollectionFk - FROM vn.ticketCollection - WHERE ticketFk = vTicketFk - LIMIT 1; - - SELECT created, parkingFk - INTO vParked, vParkingFk - FROM vn.ticketParking - WHERE ticketFk = vTicketFk; - - SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia - FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND ( - ( - ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) - OR - ( tc.collectionFk = vCollectionFk AND LEFT(tc.level,1) < LEFT(vLevel,1) ) - ) - )) -- Etiquetas que no se han escaneado y ya estamos con una posterior - OR - (s.alertLevel > 1 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND tp.created < vParked - AND t.packages <=> 0); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticketNotInvoicedByClient` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -71585,64 +71794,66 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1)) BEGIN - + /** * Averigua los tickets que se han saltado por un error en el proceso encajado * @param vTicketFk Ticket * @param vItemPackingTypeFk Modo de encajado * @return un select con los tickets afectados - */ + */ DECLARE vParkingFk INT; DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vWagon INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) INTO vLevel, vWagon, vCollectionFk FROM vn.ticketCollection tc JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk WHERE ticketFk = vTicketFk ORDER BY c.id DESC LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk WHERE ticketFk = vTicketFk AND s.itemPackingTypeFk = vItemPackingTypeFk AND s.isPackagingArea ; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk + JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.zone z ON z.id = t.zoneFk + JOIN vn.agencyMode am ON am.id = z.agencyModeFk + JOIN vn.state s ON s.id = tst.state + JOIN vn.alertLevel alPacked ON alPacked.code = 'PACKED' + JOIN vn.alertLevel alOnPreparation ON alOnPreparation.code = 'ON_PREPARATION' + WHERE (s.alertLevel < alPacked.id AND tp.parkingFk = vParkingFk AND sc.isPackagingArea AND ( ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) OR - ( tc.collectionFk = vCollectionFk + ( tc.collectionFk = vCollectionFk AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) - OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) + OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) ) ) ) -- Etiquetas que no se han escaneado y ya estamos con una posterior OR - (s.alertLevel > 1 + (s.alertLevel > alOnPreparation.id AND tp.parkingFk = vParkingFk AND sc.isPackagingArea - AND tp.created < vParked + AND tp.created < vParked AND t.packages <=> 0); END ;; DELIMITER ; @@ -71662,64 +71873,28 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* Modifica el estado de un ticket de hoy - * + * * @param vTicketFk el id del ticket * @param vStateCode estado a modificar del ticket - * + * */ - + DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM state s - JOIN ticketStateToday tst ON tst.state = s.id + DECLARE vAlertLevelPacked INT; + + SELECT s.alertLevel, al.id + INTO vAlertLevel, vAlertLevelPacked + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id + JOIN alertLevel al ON al.code = 'PACKED' WHERE tst.ticketFk = vTicketFk LIMIT 1; - - IF vAlertLevel < 2 THEN - + + IF vAlertLevel < vAlertLevelPacked THEN + CALL vn.ticket_setState(vTicketFk, vStateCode); - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketStateUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) -BEGIN - - /* - * @deprecated:utilizar ticket_setState - */ - - DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM vn.state s - JOIN vn.ticketState ts ON ts.stateFk = s.id - WHERE ts.ticketFk = vTicketFk; - - IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN - - INSERT INTO ticketTracking(stateFk, ticketFk, userFk) - SELECT id, vTicketFk, account.myUser_getId() - FROM vn.state - WHERE `code` = vStateCode collate utf8_unicode_ci; END IF; @@ -73157,10 +73332,11 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticket SELECT ticketFk FROM tmp.productionBuffer + JOIN alertLevel al ON al.code = 'FREE' WHERE shipped = util.VN_CURDATE() AND problem LIKE '%I:%' AND (HH <= vHour OR HH = vHour AND mm < vMinute) - AND alertLevel = 0; + AND alertLevel = al.id; OPEN cur1; @@ -73279,7 +73455,7 @@ BEGIN com.id companyFk, a.id addressFk, c2.defaultAddressFk, - su.id supplierFk, + IFNULL(sat.supplierFk, su.id) supplierFk, t.landed FROM ticket t JOIN ticketState ts ON ts.ticketFk = t.id @@ -73289,15 +73465,18 @@ BEGIN JOIN `address` a ON a.id = t.addressFk JOIN province p ON p.id = a.provinceFk JOIN country co ON co.id = p.countryFk - JOIN agencyMode am ON am.id = t.agencyModeFk JOIN warehouse w ON w.id = t.warehouseFk JOIN company com ON com.id = t.companyFk JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk JOIN supplier su ON su.id = sa.supplierFk LEFT JOIN route r ON r.id = t.routeFk LEFT JOIN worker wo ON wo.id = r.workerFk LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency ag ON ag.id = am.agencyFk + LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id + AND wo.isFreelance WHERE al.code IN ('PACKED', 'DELIVERED') AND co.code <> 'ES' AND am.name <> 'ABONO' @@ -82100,23 +82279,6 @@ SET character_set_client = utf8; 1 AS `description` */; SET character_set_client = @saved_cs_client; --- --- Temporary table structure for view `Saldos_Prevision` --- - -DROP TABLE IF EXISTS `Saldos_Prevision`; -/*!50001 DROP VIEW IF EXISTS `Saldos_Prevision`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Saldos_Prevision` AS SELECT - 1 AS `Saldos_Prevision_id`, - 1 AS `Descripcion`, - 1 AS `Importe`, - 1 AS `Fecha`, - 1 AS `Id_Banco`, - 1 AS `empresa_id` */; -SET character_set_client = @saved_cs_client; - -- -- Temporary table structure for view `Split_lines` -- @@ -82177,7 +82339,6 @@ SET character_set_client = utf8; 1 AS `Id_Trabajador`, 1 AS `Observaciones`, 1 AS `Firmado`, - 1 AS `Etiquetasemitidas`, 1 AS `PedidoImpreso`, 1 AS `Hora`, 1 AS `blocked`, @@ -85135,7 +85296,7 @@ USE `srt`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `bufferDayMinute` AS select `b`.`id` AS `bufferFk`,`e`.`id` AS `expeditionFk`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,`e`.`position` AS `position`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) minute) AS `ETD`,`e2`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`es`.`description` AS `expeditionState` from ((((((((`srt`.`buffer` `b` left join `srt`.`expedition` `e` on(`b`.`id` = `e`.`bufferFk`)) left join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) left join `vn`.`expedition` `e2` on(`e2`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`e2`.`ticketFk` = `t`.`id`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`expeditionTruckFk` = `rs`.`id`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) where `b`.`isActive` <> 0 */; +/*!50001 VIEW `bufferDayMinute` AS select `b`.`id` AS `bufferFk`,`e`.`id` AS `expeditionFk`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,`e`.`position` AS `position`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) minute) AS `ETD`,`e2`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`es`.`description` AS `expeditionState` from ((((((((`srt`.`buffer` `b` left join `srt`.`expedition` `e` on(`b`.`id` = `e`.`bufferFk`)) left join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) left join `vn`.`expedition` `e2` on(`e2`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`e2`.`ticketFk` = `t`.`id`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`roadmapStopFk` = `rs`.`id`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) where `b`.`isActive` <> 0 */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85171,7 +85332,7 @@ USE `srt`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `bufferStock` AS select `e`.`id` AS `expeditionFk`,`e`.`bufferFk` AS `bufferFk`,`e`.`position` AS `position`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `eta`,`ve`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`es`.`description` AS `expeditionState`,`b`.`hasWorkerWaiting` AS `hasWorkerWaiting`,`b`.`isActive` AS `isActive`,if(`rs`.`id` is null,`c`.`bufferDefault`,`rs`.`bufferFk`) AS `bufferTruck`,`bt`.`typeName` AS `typeName`,`rm`.`bufferFk` AS `routeBuffer` from (((((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`buffer` `b` on(`b`.`id` = `e`.`bufferFk`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`expeditionTruckFk` = `rs`.`id`)) join `srt`.`config` `c`) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) where `bt`.`typeName` <> 'DISABLED' */; +/*!50001 VIEW `bufferStock` AS select `e`.`id` AS `expeditionFk`,`e`.`bufferFk` AS `bufferFk`,`e`.`position` AS `position`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `eta`,`ve`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`es`.`description` AS `expeditionState`,`b`.`hasWorkerWaiting` AS `hasWorkerWaiting`,`b`.`isActive` AS `isActive`,if(`rs`.`id` is null,`c`.`bufferDefault`,`rs`.`bufferFk`) AS `bufferTruck`,`bt`.`typeName` AS `typeName`,`rm`.`bufferFk` AS `routeBuffer` from (((((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`buffer` `b` on(`b`.`id` = `e`.`bufferFk`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`roadmapStopFk` = `rs`.`id`)) join `srt`.`config` `c`) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) where `bt`.`typeName` <> 'DISABLED' */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85261,7 +85422,7 @@ USE `srt`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `upperStickers` AS select `e`.`id` AS `expeditionFk`,`e`.`id` MOD 10000 AS `expedition`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `ETD`,`ve`.`ticketFk` AS `ticketFk`,right(ifnull(`t`.`routeFk`,`t`.`agencyModeFk`),3) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`epo`.`workerCode` AS `worker`,`p`.`name` AS `labeler`,`ve`.`counter` AS `expeditionCounter`,`vn`.`ticketTotalVolume`(`t`.`id`) AS `m3`,`t`.`clientFk` AS `clientFk` from (((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`expeditionTruckFk` = `rs`.`id`)) join `dipole`.`expedition_PrintOut` `epo` on(`epo`.`expeditionFk` = `e`.`id`)) join `vn`.`printer` `p` on(`p`.`id` = `epo`.`printerFk`)) */; +/*!50001 VIEW `upperStickers` AS select `e`.`id` AS `expeditionFk`,`e`.`id` MOD 10000 AS `expedition`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `ETD`,`ve`.`ticketFk` AS `ticketFk`,right(ifnull(`t`.`routeFk`,`t`.`agencyModeFk`),3) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`epo`.`workerCode` AS `worker`,`p`.`name` AS `labeler`,`ve`.`counter` AS `expeditionCounter`,`vn`.`ticketTotalVolume`(`t`.`id`) AS `m3`,`t`.`clientFk` AS `clientFk` from (((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`roadmapStopFk` = `rs`.`id`)) join `dipole`.`expedition_PrintOut` `epo` on(`epo`.`expeditionFk` = `e`.`id`)) join `vn`.`printer` `p` on(`p`.`id` = `epo`.`printerFk`)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85681,7 +85842,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionCommon` AS select `rs`.`id` AS `truckFk`,`rs`.`eta` AS `eta`,ifnull(ucase(`rs`.`description`),'SIN ESCANEAR') AS `description`,`es`.`palletFk` AS `palletFk`,`t`.`routeFk` AS `routeFk`,`es`.`id` AS `scanFk`,`e`.`id` AS `expeditionFk`,`r`.`expeditionTruckFk` AS `expeditionTruckFk`,`t`.`warehouseFk` AS `warehouseFk`,`e`.`created` AS `lastPacked`,`t`.`id` AS `ticketFk` from (((((`roadmapStop` `rs` left join `routesMonitor` `r` on(`rs`.`id` = `r`.`expeditionTruckFk`)) left join `ticket` `t` on(`r`.`routeFk` = `t`.`routeFk`)) left join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`e`.`id` = `es`.`expeditionFk`)) left join `expeditionPallet` `ep` on(`es`.`palletFk` = `ep`.`id`)) where `rs`.`eta` >= `util`.`VN_CURDATE`() */; +/*!50001 VIEW `expeditionCommon` AS select `rs`.`id` AS `truckFk`,`rs`.`eta` AS `eta`,ifnull(ucase(`rs`.`description`),'SIN ESCANEAR') AS `description`,`es`.`palletFk` AS `palletFk`,`t`.`routeFk` AS `routeFk`,`es`.`id` AS `scanFk`,`e`.`id` AS `expeditionFk`,`r`.`roadmapStopFk` AS `roadmapStopFk`,`t`.`warehouseFk` AS `warehouseFk`,`e`.`created` AS `lastPacked`,`t`.`id` AS `ticketFk` from (((((`roadmapStop` `rs` left join `routesMonitor` `r` on(`rs`.`id` = `r`.`roadmapStopFk`)) left join `ticket` `t` on(`r`.`routeFk` = `t`.`routeFk`)) left join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`e`.`id` = `es`.`expeditionFk`)) left join `expeditionPallet` `ep` on(`es`.`palletFk` = `ep`.`id`)) where `rs`.`eta` >= `util`.`VN_CURDATE`() */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85699,7 +85860,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionPallet_Print` AS select `rs2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,`rs`.`id` <=> `rm`.`expeditionTruckFk` AS `isMatch`,`t`.`warehouseFk` AS `warehouseFk`,if(`r`.`created` > `util`.`VN_CURDATE`() + interval 1 day,ucase(dayname(`r`.`created`)),NULL) AS `nombreDia` from (((((((`roadmapStop` `rs` join `expeditionPallet` `ep` on(`ep`.`truckFk` = `rs`.`id`)) join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) join `expedition` `e` on(`e`.`id` = `es`.`expeditionFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `r`.`id`)) left join `roadmapStop` `rs2` on(`rs2`.`id` = `rm`.`expeditionTruckFk`)) group by `ep`.`id`,`t`.`routeFk` */; +/*!50001 VIEW `expeditionPallet_Print` AS select `rs2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,`rs`.`id` <=> `rm`.`roadmapStopFk` AS `isMatch`,`t`.`warehouseFk` AS `warehouseFk`,if(`r`.`created` > `util`.`VN_CURDATE`() + interval 1 day,ucase(dayname(`r`.`created`)),NULL) AS `nombreDia` from (((((((`roadmapStop` `rs` join `expeditionPallet` `ep` on(`ep`.`truckFk` = `rs`.`id`)) join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) join `expedition` `e` on(`e`.`id` = `es`.`expeditionFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `r`.`id`)) left join `roadmapStop` `rs2` on(`rs2`.`id` = `rm`.`roadmapStopFk`)) group by `ep`.`id`,`t`.`routeFk` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85717,7 +85878,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct if(`e`.`id` is null,`t`.`id`,NULL)) AS `tickets`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked`,`r`.`created` AS `created` from (((((`route` `r` left join `routesMonitor` `rm` on(`r`.`id` = `rm`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`expeditionTruckFk`)) join `ticket` `t` on(`t`.`routeFk` = `r`.`id`)) left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) where `r`.`created` >= `util`.`yesterday`() group by `r`.`id` */; +/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct if(`e`.`id` is null,`t`.`id`,NULL)) AS `tickets`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked`,`r`.`created` AS `created` from (((((`route` `r` left join `routesMonitor` `rm` on(`r`.`id` = `rm`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`roadmapStopFk`)) join `ticket` `t` on(`t`.`routeFk` = `r`.`id`)) left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) where `r`.`created` >= `util`.`yesterday`() group by `r`.`id` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85771,7 +85932,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionSticker` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',right(`t`.`routeFk`,3),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,ifnull(`rs`.`description`,replace(`am`.`name`,'ZONA ','Z')),`z`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`c`.`mobile`,ifnull(`a`.`mobile`,ifnull(`c`.`phone`,`a`.`phone`))) AS `phone`,`w`.`code` AS `workerCode` from (((((((((((`expedition` `e` join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`expeditionTruckFk`)) left join `beach` `b` on(`b`.`code` = `rm`.`beachFk`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `agencyMode` `am` on(`am`.`id` = `r`.`agencyModeFk`)) join `client` `c` on(`c`.`id` = `a`.`clientFk`)) join `worker` `w` on(`w`.`id` = `e`.`workerFk`)) */; +/*!50001 VIEW `expeditionSticker` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',right(`t`.`routeFk`,3),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,ifnull(`rs`.`description`,replace(`am`.`name`,'ZONA ','Z')),`z`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`c`.`mobile`,ifnull(`a`.`mobile`,ifnull(`c`.`phone`,`a`.`phone`))) AS `phone`,`w`.`code` AS `workerCode` from (((((((((((`expedition` `e` join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`roadmapStopFk`)) left join `beach` `b` on(`b`.`code` = `rm`.`beachFk`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `agencyMode` `am` on(`am`.`id` = `r`.`agencyModeFk`)) join `client` `c` on(`c`.`id` = `a`.`clientFk`)) join `worker` `w` on(`w`.`id` = `e`.`workerFk`)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85789,7 +85950,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTicket_NoBoxes` AS select `t`.`id` AS `ticketFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`routeFk` AS `routeFk`,`rs`.`description` AS `description` from (((`ticket` `t` left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`expeditionTruckFk`)) where `e`.`id` is null and `rs`.`eta` > `util`.`VN_CURDATE`() */; +/*!50001 VIEW `expeditionTicket_NoBoxes` AS select `t`.`id` AS `ticketFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`routeFk` AS `routeFk`,`rs`.`description` AS `description` from (((`ticket` `t` left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`roadmapStopFk`)) where `e`.`id` is null and `rs`.`eta` > `util`.`VN_CURDATE`() */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85825,61 +85986,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck` AS select `rs`.`id` AS `id`,`rs`.`roadmapFk` AS `roadmapFk`,`rs`.`warehouseFk` AS `warehouseFk`,`rs`.`eta` AS `eta`,`rs`.`description` AS `description`,`rs`.`bufferFk` AS `bufferFk`,`rs`.`created` AS `created`,`rs`.`userFk` AS `userFk` from `roadmapStop` `rs` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `expeditionTruck_Control` --- - -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `ETD`,`e`.`description` AS `description`,count(distinct if(`e`.`expeditionFk` is null,`e`.`ticketFk`,NULL)) AS `ticketsSinBultos`,count(distinct `e`.`palletFk`) AS `pallets`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionFk`) AS `expeditions`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,max(`e`.`lastPacked`) AS `lastPacked` from `expeditionCommon` `e` group by `e`.`truckFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`eta` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `expeditionTruck_Control_Detail` --- - -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control_Detail` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `eta`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionTruckFk`) AS `destinos`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,max(`e`.`lastPacked`) AS `lastPacked` from `expeditionCommon` `e` group by `e`.`truckFk`,`e`.`palletFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`eta`,`e`.`truckFk` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `expeditionTruck_Control_Detail_Pallet` --- - -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail_Pallet`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control_Detail_Pallet` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `eta`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,`e`.`routeFk` AS `route`,count(distinct `e`.`scanFk`) AS `scans`,`rs`.`description` AS `destinos`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,`e`.`expeditionTruckFk` AS `expeditionTruckFk`,max(`e`.`lastPacked`) AS `lastPacked` from (`expeditionCommon` `e` left join `roadmapStop` `rs` on(`rs`.`id` = `e`.`expeditionTruckFk`)) group by `e`.`truckFk`,`e`.`palletFk`,`e`.`routeFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`palletFk` */; +/*!50001 VIEW `expeditionTruck` AS select `rs`.`id` AS `id`,`rs`.`roadmapFk` AS `roadmapFk`,`rs`.`eta` AS `eta`,`rs`.`description` AS `description`,`rs`.`bufferFk` AS `bufferFk`,`rs`.`created` AS `created`,`rs`.`userFk` AS `userFk` from `roadmapStop` `rs` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -87852,24 +87959,6 @@ USE `vn2008`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Final view structure for view `Saldos_Prevision` --- - -/*!50001 DROP VIEW IF EXISTS `Saldos_Prevision`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Saldos_Prevision` AS select `fb`.`id` AS `Saldos_Prevision_id`,`fb`.`description` AS `Descripcion`,`fb`.`amount` AS `Importe`,`fb`.`dated` AS `Fecha`,`fb`.`accountingFk` AS `Id_Banco`,`fb`.`companyFk` AS `empresa_id` from `vn`.`forecastedBalance` `fb` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Final view structure for view `Split_lines` -- @@ -87919,7 +88008,7 @@ USE `vn2008`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Tickets` AS select `t`.`id` AS `Id_Ticket`,`t`.`clientFk` AS `Id_Cliente`,`t`.`warehouseFk` AS `warehouse_id`,`t`.`shipped` AS `Fecha`,`t`.`landed` AS `landing`,`t`.`nickname` AS `Alias`,`t`.`refFk` AS `Factura`,`t`.`addressFk` AS `Id_Consigna`,`t`.`location` AS `Localizacion`,`t`.`solution` AS `Solucion`,`t`.`routeFk` AS `Id_Ruta`,`t`.`companyFk` AS `empresa_id`,`t`.`agencyModeFk` AS `Id_Agencia`,`t`.`priority` AS `Prioridad`,`t`.`packages` AS `Bultos`,`t`.`isDeleted` AS `isDeleted`,`t`.`created` AS `odbc_date`,`t`.`workerFk` AS `Id_Trabajador`,`t`.`observations` AS `Observaciones`,`t`.`isSigned` AS `Firmado`,`t`.`isLabeled` AS `Etiquetasemitidas`,`t`.`isPrinted` AS `PedidoImpreso`,`t`.`hour` AS `Hora`,`t`.`isBlocked` AS `blocked`,`t`.`hasPriority` AS `priority`,`t`.`isBoxed` AS `boxed`,`t`.`zoneFk` AS `zoneFk`,`t`.`totalWithVat` AS `totalWithVat`,`t`.`totalWithoutVat` AS `totalWithoutVat` from `vn`.`ticket` `t` */; +/*!50001 VIEW `Tickets` AS select `t`.`id` AS `Id_Ticket`,`t`.`clientFk` AS `Id_Cliente`,`t`.`warehouseFk` AS `warehouse_id`,`t`.`shipped` AS `Fecha`,`t`.`landed` AS `landing`,`t`.`nickname` AS `Alias`,`t`.`refFk` AS `Factura`,`t`.`addressFk` AS `Id_Consigna`,`t`.`location` AS `Localizacion`,`t`.`solution` AS `Solucion`,`t`.`routeFk` AS `Id_Ruta`,`t`.`companyFk` AS `empresa_id`,`t`.`agencyModeFk` AS `Id_Agencia`,`t`.`priority` AS `Prioridad`,`t`.`packages` AS `Bultos`,`t`.`isDeleted` AS `isDeleted`,`t`.`created` AS `odbc_date`,`t`.`workerFk` AS `Id_Trabajador`,`t`.`observations` AS `Observaciones`,`t`.`isSigned` AS `Firmado`,`t`.`isPrinted` AS `PedidoImpreso`,`t`.`hour` AS `Hora`,`t`.`isBlocked` AS `blocked`,`t`.`hasPriority` AS `priority`,`t`.`isBoxed` AS `boxed`,`t`.`zoneFk` AS `zoneFk`,`t`.`totalWithVat` AS `totalWithVat`,`t`.`totalWithoutVat` AS `totalWithoutVat` from `vn`.`ticket` `t` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -89715,4 +89804,4 @@ USE `vn2008`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-06-11 6:35:36 +-- Dump completed on 2024-06-25 7:26:45 diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql index b2f550bbe..90ff6b30d 100644 --- a/db/dump/.dump/triggers.sql +++ b/db/dump/.dump/triggers.sql @@ -2140,24 +2140,22 @@ BEGIN END IF; IF !(OLD.started <=> NEW.started AND OLD.ended <=> NEW.ended) THEN - - SELECT COUNT(*) > 0 INTO isOverlapping - FROM business b - WHERE (util.hasDateOverlapped( - NEW.started, - IFNULL(NEW.ended, b.started), - b.started, - IFNULL(b.ended, NEW.started)) - OR (NEW.ended <=> NULL AND b.ended <=> NULL)) - AND b.id <> OLD.id - AND workerFk = OLD.workerFk; + SELECT util.hasDateOverlapped( + started, + ended, + NEW.started, + IFNULL(NEW.ended, b.started) + ) isOverlapped INTO isOverlapping + FROM vn.business b + WHERE workerFk = NEW.workerFK + AND b.id <> NEW.id + ORDER BY isOverlapped DESC + LIMIT 1; IF isOverlapping THEN CALL util.throw ('IS_OVERLAPPING'); END IF; - END IF; - END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2366,7 +2364,15 @@ trig:BEGIN LEAVE trig; END IF; - CALL entry_isEditable(OLD.entryFk); + IF NOT (NEW.entryFk <=> OLD.entryFk) OR + NOT (NEW.quantity <=> OLD.quantity) OR + NOT (NEW.buyingValue <=> OLD.buyingValue) OR + NOT (NEW.packing <=> OLD.packing) + THEN + + CALL entry_isEditable(OLD.entryFk); + END IF; + SET NEW.editorFk = account.myUser_getId(); SELECT defaultEntry INTO vDefaultEntry @@ -3010,6 +3016,52 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimRatio_afterInsert` + AFTER INSERT ON `claimRatio` + FOR EACH ROW +BEGIN + INSERT INTO clientRate(clientFk, `value`) + VALUES(NEW.clientFk, NEW.priceIncreasing) + ON DUPLICATE KEY UPDATE + `value` = VALUES(`value`); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimRatio_afterUpdate` + AFTER UPDATE ON `claimRatio` + FOR EACH ROW +BEGIN + INSERT INTO clientRate(clientFk, `value`) + VALUES(NEW.clientFk, NEW.priceIncreasing) + ON DUPLICATE KEY UPDATE + `value` = VALUES(`value`); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`claimState_beforeInsert` BEFORE INSERT ON `claimState` FOR EACH ROW @@ -3198,11 +3250,11 @@ BEGIN END IF; END IF; - IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN + IF NOT (NEW.salesPersonFk <=> OLD.salesPersonFk) THEN SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk); END IF; - IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN + IF NOT (NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN SET NEW.isTaxDataChecked = 0; END IF; END */;; @@ -3224,13 +3276,36 @@ DELIMITER ;; AFTER UPDATE ON `client` FOR EACH ROW BEGIN - IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN + IF NOT (NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN UPDATE `address` SET isDefaultAddress = FALSE WHERE clientFk = NEW.id; UPDATE `address` SET isDefaultAddress = TRUE WHERE id = NEW.defaultAddressFk; END IF; + + IF NEW.id <> OLD.id + OR NOT (NEW.provinceFk <=> OLD.provinceFk) + OR NOT (NEW.socialName <=> OLD.socialName) + OR NOT (NEW.street <=> OLD.street) + OR NOT (NEW.accountingAccount <=> OLD.accountingAccount) + OR NOT (NEW.isVies <=> OLD.isVies) + OR NOT (NEW.fi <=> OLD.fi) + OR NOT (NEW.postcode <=> OLD.postcode) + OR NOT (NEW.city <=> OLD.city) + OR NOT (NEW.countryFk <=> OLD.countryFk) + OR NOT (NEW.taxTypeSageFk <=> OLD.taxTypeSageFk) + OR NOT (NEW.transactionTypeSageFk <=> OLD.transactionTypeSageFk) + OR NOT (NEW.email <=> OLD.email) + OR NOT (NEW.iban <=> OLD.iban) + OR NOT (NEW.phone <=> OLD.phone) + OR NOT (NEW.mobile <=> OLD.mobile) THEN + + UPDATE sage.clientSupplier + SET isSync = FALSE + WHERE idClientSupplier IN (NEW.id, OLD.id) + AND `type` = 'C'; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4203,31 +4278,6 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionConfig_afterUpdate` - AFTER UPDATE ON `deviceProductionConfig` - FOR EACH ROW -BEGIN - IF NEW.isAllUsersAllowed = 1 OR NEW.isAllUsersAllowed = -1 THEN - SET @username := (SELECT account.myUser_getName()); - INSERT INTO vn.mail (receiver, subject, body) - VALUES ('cau@verdnatura.es', 'Se ha activado la autenticación sin restricciones en la app', - CONCAT('El usuario ', @username,' ha habilitado la opción para que todos los usuarios puedan acceder a la app sin restricciones')); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`deviceProductionModels_beforeInsert` BEFORE INSERT ON `deviceProductionModels` FOR EACH ROW @@ -4617,10 +4667,21 @@ BEGIN DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; DECLARE vTotalBuy INT; - - IF NEW.isBooked = OLD.isBooked THEN + + IF NEW.isBooked = OLD.isBooked AND ( + NOT (NEW.supplierFk <=> OLD.supplierFk) OR + NOT (NEW.dated <=> OLD.dated) OR + NOT (NEW.invoiceNumber <=> OLD.invoiceNumber) OR + NOT (NEW.travelFk <=> OLD.travelFk) OR + NOT (NEW.companyFk <=> OLD.companyFk) OR + NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) OR + NOT (NEW.invoiceAmount <=> OLD.invoiceAmount) OR + NOT (NEW.typeFk <=> OLD.typeFk) + ) THEN + CALL entry_isEditable(OLD.id); ELSE + IF NEW.isBooked THEN SELECT COUNT(*) INTO vTotalBuy FROM buy @@ -4894,25 +4955,25 @@ DELIMITER ;; BEFORE INSERT ON `expedition` FOR EACH ROW BEGIN - DECLARE intcounter INT; - DECLARE vShipFk INT; + DECLARE vMaxCounter INT; SET NEW.editorFk = account.myUser_getId(); - IF NEW.freightItemFk IS NOT NULL THEN + IF NEW.freightItemFk IS NOT NULL THEN UPDATE ticket SET packages = IFNULL(packages, 0) + 1 WHERE id = NEW.ticketFk; - SELECT IFNULL(MAX(counter),0) +1 INTO intcounter - FROM expedition e - INNER JOIN ticket t1 ON e.ticketFk = t1.id + SELECT IFNULL(MAX(counter),0) + 1 INTO vMaxCounter + FROM expedition e + JOIN alertLevel al ON al.code = 'DELIVERED' + JOIN ticket t1 ON e.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticketFk = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) AND t1.warehouseFk = t2.warehouseFk - WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < al.id AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; - SET NEW.`counter` = intcounter; + SET NEW.`counter` = vMaxCounter; END IF; END */;; DELIMITER ; @@ -8525,6 +8586,44 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplier_afterUpdate` + BEFORE UPDATE ON `supplier` + FOR EACH ROW +BEGIN + IF NEW.id <> OLD.id + OR NOT (NEW.name <=> OLD.name) + OR NOT (NEW.street <=> OLD.street) + OR NOT (NEW.account <=> OLD.account) + OR NOT (NEW.nif <=> OLD.nif) + OR NOT (NEW.isVies <=> OLD.isVies) + OR NOT (NEW.provinceFk <=> OLD.provinceFk) + OR NOT (NEW.countryFk <=> OLD.countryFk) + OR NOT (NEW.postCode <=> OLD.postCode) + OR NOT (NEW.city <=> OLD.city) + OR NOT (NEW.taxTypeSageFk <=> OLD.taxTypeSageFk) + OR NOT (NEW.transactionTypeSageFk <=> OLD.transactionTypeSageFk) + OR NOT (NEW.withholdingSageFk <=> OLD.withholdingSageFk) THEN + + UPDATE sage.clientSupplier + SET isSync = FALSE + WHERE idClientSupplier IN (NEW.id, OLD.id) + AND `type` = 'P'; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`supplier_afterDelete` AFTER DELETE ON `supplier` FOR EACH ROW @@ -10825,4 +10924,4 @@ USE `vn2008`; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-06-11 6:35:55 +-- Dump completed on 2024-06-25 7:27:06 -- 2.40.1 From 2797a731c548b83185af42abebf9044c39ce0b07 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 25 Jun 2024 12:00:49 +0200 Subject: [PATCH 281/413] refs #6952 subName --- .../reports/delivery-note/delivery-note.html | 3 ++- .../reports/delivery-note/locale/en.yml | 5 +++-- .../reports/delivery-note/locale/es.yml | 5 +++-- .../reports/delivery-note/locale/fr.yml | 7 ++++--- .../reports/delivery-note/locale/pt.yml | 5 +++-- .../reports/delivery-note/sql/sales.sql | 19 ++++++++++--------- 6 files changed, 25 insertions(+), 19 deletions(-) diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html index 92dd1b126..540a80a3a 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -81,6 +81,7 @@ {{sale.tag5}} {{sale.value5}} {{sale.tag6}} {{sale.value6}} {{sale.tag7}} {{sale.value7}} + {{$t('producer')}} {{ sale.subName }} @@ -249,4 +250,4 @@ v-bind:center-text="client.socialName" v-bind="$props"> - \ No newline at end of file + diff --git a/print/templates/reports/delivery-note/locale/en.yml b/print/templates/reports/delivery-note/locale/en.yml index 5902da8b3..84b31e494 100644 --- a/print/templates/reports/delivery-note/locale/en.yml +++ b/print/templates/reports/delivery-note/locale/en.yml @@ -20,6 +20,7 @@ vatType: VAT Type digitalSignature: Digital signature plantPassport: Plant passport packages: Packages +producer: Producer services: title: Services theader: @@ -44,7 +45,7 @@ taxes: taxBase: Tax base tax: Tax fee: Fee - tfoot: + tfoot: subtotal: Subtotal total: Total -observations: Observations \ No newline at end of file +observations: Observations diff --git a/print/templates/reports/delivery-note/locale/es.yml b/print/templates/reports/delivery-note/locale/es.yml index d87198f45..891e59d77 100644 --- a/print/templates/reports/delivery-note/locale/es.yml +++ b/print/templates/reports/delivery-note/locale/es.yml @@ -15,6 +15,7 @@ discount: Dto. vat: IVA amount: Importe total: Total +producer: Productor subtotal: Subtotal vatType: Tipo de IVA digitalSignature: Firma digital @@ -45,7 +46,7 @@ taxes: taxBase: Base imp. tax: Tasa fee: Cuota - tfoot: + tfoot: subtotal: Subtotal total: Total -observations: Observaciones \ No newline at end of file +observations: Observaciones diff --git a/print/templates/reports/delivery-note/locale/fr.yml b/print/templates/reports/delivery-note/locale/fr.yml index 603623a47..87cd2bcde 100644 --- a/print/templates/reports/delivery-note/locale/fr.yml +++ b/print/templates/reports/delivery-note/locale/fr.yml @@ -14,7 +14,8 @@ price: PRIX/u discount: Remise vat: TVA amount: Montant -total: Total +producer: producteur +total: Total subtotal: Total partiel vatType: Type de TVA digitalSignature: Signature numérique @@ -45,7 +46,7 @@ taxes: taxBase: Base imposable tax: Taxe fee: Quote - tfoot: + tfoot: subtotal: Total partiel total: Total -observations: Observations \ No newline at end of file +observations: Observations diff --git a/print/templates/reports/delivery-note/locale/pt.yml b/print/templates/reports/delivery-note/locale/pt.yml index fb49d230b..be39eb3f0 100644 --- a/print/templates/reports/delivery-note/locale/pt.yml +++ b/print/templates/reports/delivery-note/locale/pt.yml @@ -14,6 +14,7 @@ price: PVP/u discount: Dto. vat: IVA amount: Importe +producer: Produtor total: Total subtotal: Sub-total vatType: Tipo de IVA @@ -45,7 +46,7 @@ taxes: taxBase: Tributável tax: Taxa fee: Compartilhado - tfoot: + tfoot: subtotal: Subtotal total: Total -observations: Observações \ No newline at end of file +observations: Observações diff --git a/print/templates/reports/delivery-note/sql/sales.sql b/print/templates/reports/delivery-note/sql/sales.sql index c449030cf..4cbffa12f 100644 --- a/print/templates/reports/delivery-note/sql/sales.sql +++ b/print/templates/reports/delivery-note/sql/sales.sql @@ -1,4 +1,4 @@ -SELECT +SELECT s.id, s.itemFk, s.concept, @@ -15,12 +15,13 @@ SELECT s.ticketFk, tcl.code vatType, ib.ediBotanic botanical, - i.tag5, + i.tag5, i.value5, - i.tag6, - i.value6, - i.tag7, - i.value7 + i.tag6, + i.value6, + i.tag7, + i.value7, + i.subName FROM vn.sale s LEFT JOIN saleComponent sc ON sc.saleFk = s.id LEFT JOIN component cr ON cr.id = sc.componentFk @@ -32,12 +33,12 @@ FROM vn.sale s LEFT JOIN supplier sp ON sp.id = t.companyFk LEFT JOIN itemType it ON it.id = i.typeFk LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id - AND itc.countryFk = sp.countryFk + LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id + AND itc.countryFk = sp.countryFk LEFT JOIN taxClass tcl ON tcl.id = itc.taxClassFk LEFT JOIN itemBotanicalWithGenus ib ON ib.itemFk = i.id AND ic.code = 'plant' AND ib.ediBotanic IS NOT NULL WHERE s.ticketFk = ? GROUP BY s.id -ORDER BY (it.isPackaging), s.concept, s.itemFk \ No newline at end of file +ORDER BY (it.isPackaging), s.concept, s.itemFk -- 2.40.1 From 655bbe4967e34ca9fa02adc70f77b40503979785 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 25 Jun 2024 12:29:17 +0200 Subject: [PATCH 282/413] refs #7406 fix pr --- db/dump/fixtures.before.sql | 10 ++++------ db/versions/11073-crimsonBirch/00-firstScript.sql | 8 ++++---- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 941a046b0..0be918fbb 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3828,7 +3828,6 @@ INSERT INTO vn.workerTeam(id, team, workerFk) INSERT INTO vn.workCenter (id, name, payrollCenterFk, counter, warehouseFk, street, geoFk, deliveryManAdjustment) VALUES(100, 'workCenterOne', 1, NULL, 1, 'gotham', NULL, NULL); -UPDATE vn.locker SET workerFk = 1110 WHERE id = 147; INSERT INTO `vn`.`locker` (code, gender, workerFk) VALUES ('1M', 'M', 1), ('2M', 'M', 9), @@ -3848,11 +3847,10 @@ INSERT INTO `vn`.`ledgerConfig` SET INSERT INTO vn.trainingCourse (workerFk,trainingCourseTypeFk,centerFk,started,ended,hasDiscount,hasDiploma) - VALUES (9,2,1,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',0,1); -INSERT INTO vn.trainingCourse (workerFk,trainingCourseTypeFk,centerFk,started,ended,hasDiscount,hasDiploma) - VALUES (9,1,2,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',1,0); -INSERT INTO vn.trainingCourse (workerFk,trainingCourseTypeFk,centerFk,started,ended,hasDiscount,hasDiploma) - VALUES (9,2,2,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',1,1); + VALUES + (9,2,1,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',0,1), + (9,1,2,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',1,0), + (9,2,2,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',1,1); INSERT INTO vn.sectorCollection SET id = 2, diff --git a/db/versions/11073-crimsonBirch/00-firstScript.sql b/db/versions/11073-crimsonBirch/00-firstScript.sql index 7d76a75cd..e82d342c9 100644 --- a/db/versions/11073-crimsonBirch/00-firstScript.sql +++ b/db/versions/11073-crimsonBirch/00-firstScript.sql @@ -1,9 +1,9 @@ -- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('TrainingCourse','*','*','ALLOW','ROLE','employee'); + VALUES ('TrainingCourse','*','*','ALLOW','ROLE','hr'); INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('TrainingCourseType','*','*','ALLOW','ROLE','employee'); + VALUES ('TrainingCourseType','*','*','ALLOW','ROLE','hr'); INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('TrainingCenter','*','*','ALLOW','ROLE','employee'); + VALUES ('TrainingCenter','*','*','ALLOW','ROLE','hr'); INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Worker','__get__trainingCourse','*','ALLOW','ROLE','employee'); + VALUES ('Worker','__get__trainingCourse','*','ALLOW','ROLE','hr'); -- 2.40.1 From 248358fbd7ed63ab213d9a99d942fd7e0cc57462 Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 25 Jun 2024 12:35:25 +0200 Subject: [PATCH 283/413] refs #7409 fix pr --- db/dump/fixtures.before.sql | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 1f19ba510..bc73916ba 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3884,20 +3884,16 @@ INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHoli INSERT INTO vn.payrollComponent (id, name, isSalaryAgreed, isVariable, isException) -VALUES(1, 'Salario1', 1, 0, 0); -INSERT INTO vn.payrollComponent -(id, name, isSalaryAgreed, isVariable, isException) -VALUES(2, 'Salario2', 1, 1, 0); -INSERT INTO vn.payrollComponent -(id, name, isSalaryAgreed, isVariable, isException) -VALUES(3, 'Salario3', 1, 0, 1); + VALUES + (1, 'Salario1', 1, 0, 0), + (2, 'Salario2', 1, 1, 0), + (3, 'Salario3', 1, 0, 1); INSERT INTO vn.workerIncome (debit, credit, incomeTypeFk, paymentDate, workerFk, concept) -VALUES(1000.00, 900.00, 2, '2000-01-01', 1106, NULL); -INSERT INTO vn.workerIncome -(debit, credit, incomeTypeFk, paymentDate, workerFk, concept) -VALUES(1001.00, 800.00, 2, '2000-01-01', 1106, NULL); + VALUES + (1000.00, 900.00, 2, '2000-01-01', 1106, NULL), + (1001.00, 800.00, 2, '2000-01-01', 1106, NULL); -- 2.40.1 From f5bc0482d2d88822bb5e0f34517bb150a9f295ef Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 25 Jun 2024 12:36:28 +0200 Subject: [PATCH 284/413] refs #7409 resolve conflicts --- 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 77b63f45c..ae9ab621c 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3897,10 +3897,10 @@ INSERT INTO vn.workerIncome (1001.00, 800.00, 2, '2000-01-01', 1106, NULL); - INSERT INTO dipole.printer (id, description) - VALUES(1, ''); +INSERT INTO dipole.printer (id, description) +VALUES(1, ''); - INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, street, postalCode, city, shopName, isPrinted, created, printerFk, routeFk, parkingCode, - truckName, clientFk, phone, province, agency, m3, workerCode, itemFk, quantity, longName, shelvingFk, comments) - VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, NULL, 'NCC', NULL); +INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, street, postalCode, city, shopName, isPrinted, created, printerFk, routeFk, parkingCode, +truckName, clientFk, phone, province, agency, m3, workerCode, itemFk, quantity, longName, shelvingFk, comments) +VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, NULL, 'NCC', NULL); -- 2.40.1 From 4bf00bd428fb1455411f4bbc6596f02460f2c838 Mon Sep 17 00:00:00 2001 From: Pako Date: Tue, 25 Jun 2024 12:51:14 +0200 Subject: [PATCH 285/413] version 240625 --- .../floranet/procedures/catalogue_get.sql | 27 +++++++++++-------- .../floranet/procedures/deliveryDate_get.sql | 4 +-- .../floranet/procedures/order_confirm.sql | 4 +-- 3 files changed, 19 insertions(+), 16 deletions(-) diff --git a/db/routines/floranet/procedures/catalogue_get.sql b/db/routines/floranet/procedures/catalogue_get.sql index 7ce32cfac..1e224c810 100644 --- a/db/routines/floranet/procedures/catalogue_get.sql +++ b/db/routines/floranet/procedures/catalogue_get.sql @@ -1,16 +1,15 @@ -DROP PROCEDURE IF EXISTS floranet.catalogue_get; - DELIMITER $$ $$ -CREATE DEFINER=`root`@`localhost` PROCEDURE floranet.catalogue_get(vLanded DATE, vPostalCode VARCHAR(15)) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE floranet.catalogue_get(vLanded DATE, vPostalCode VARCHAR(15)) READS SQL DATA proc:BEGIN /** - * Returns list, price and all the stuff regarding the floranet items. + * Returns list, price and all the stuff regarding the floranet items, for the designed shop * * @param vLanded Delivery date * @param vPostalCode Delivery address postal code */ + DECLARE vAddressFk INT; DECLARE vLastCatalogueFk INT; DECLARE vLockName VARCHAR(20); DECLARE vLockTime INT; @@ -21,7 +20,7 @@ proc:BEGIN RESIGNAL; END; - + SET vLockName = 'catalogue_get'; SET vLockTime = 15; @@ -32,6 +31,15 @@ proc:BEGIN SELECT MAX(id) INTO vLastCatalogueFk FROM catalogue; + SELECT addressFk + INTO vAddressFk + FROM addressPostCode apc + WHERE apc.dayOfWeek = dayOfWeek(vLanded) + AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR + AND apc.postCode = vPostalCode + -- Aquí hay que incluir los criterios de selección de tienda + LIMIT 1; + INSERT INTO catalogue( name, price, @@ -51,17 +59,14 @@ proc:BEGIN it.name, CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image), i.description, - apc.addressFk + vAddressFk FROM vn.item i JOIN (SELECT itemFk, SUM(quantity * cost) price FROM recipe GROUP BY itemFk) r ON r.itemFk = i.id JOIN vn.itemType it ON it.id = i.typeFk - JOIN addressPostCode apc - ON apc.dayOfWeek = dayOfWeek(vLanded) - AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR - AND apc.postCode = vPostalCode - JOIN vn.address a ON a.id = apc.addressFk; + JOIN addressPostCode apc ON addressFk = vAddressFk + JOIN vn.address a ON a.id = vAddressFk; SELECT * FROM catalogue diff --git a/db/routines/floranet/procedures/deliveryDate_get.sql b/db/routines/floranet/procedures/deliveryDate_get.sql index a235e8c31..70cb48818 100644 --- a/db/routines/floranet/procedures/deliveryDate_get.sql +++ b/db/routines/floranet/procedures/deliveryDate_get.sql @@ -1,8 +1,6 @@ -DROP PROCEDURE IF EXISTS floranet.deliveryDate_get; - DELIMITER $$ $$ -CREATE DEFINER=`root`@`localhost` PROCEDURE `floranet`.`deliveryDate_get`(vPostalCode VARCHAR(15)) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `floranet`.`deliveryDate_get`(vPostalCode VARCHAR(15)) READS SQL DATA BEGIN /** diff --git a/db/routines/floranet/procedures/order_confirm.sql b/db/routines/floranet/procedures/order_confirm.sql index 3b9413da9..98e15bbab 100644 --- a/db/routines/floranet/procedures/order_confirm.sql +++ b/db/routines/floranet/procedures/order_confirm.sql @@ -101,7 +101,7 @@ proc:BEGIN vNewTicketFk, c.itemFk, CONCAT('Entrega: ',c.name), - - c.price, + - apc.deliveryCost, 1 FROM catalogue c JOIN addressPostCode apc @@ -119,7 +119,7 @@ proc:BEGIN vNewTicketFk, r.elementFk, i.longName, - r.cost, + 0, r.quantity FROM catalogue c JOIN recipe r ON r.itemFk = c.itemFk -- 2.40.1 From 85854e0713d07a3e525a6a0e5fd7a64c350dc406 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 25 Jun 2024 13:14:44 +0200 Subject: [PATCH 286/413] warmFix: use vn --- db/routines/vn/procedures/duaInvoiceInBooking.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index 1f026e96b..6d0c9f517 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -36,7 +36,7 @@ BEGIN SELECT ASIEN INTO vBookEntry FROM dua WHERE id = vDuaFk; - IF vBookEntry IS NULL THEN + IF vBookEntry IS NULL THEN SELECT YEAR(IFNULL(ii.bookEntried, d.bookEntried)) INTO vFiscalYear FROM invoiceIn ii JOIN `entry` e ON e.invoiceInFk = ii.id @@ -45,7 +45,7 @@ BEGIN WHERE d.id = vDuaFk LIMIT 1; CALL ledger_nextTx(vFiscalYear, vBookEntry); - END IF; + END IF; OPEN vInvoicesIn; @@ -75,14 +75,14 @@ BEGIN JOIN ( WITH entries AS ( SELECT e.id, de.duaFk - FROM `entry` e - JOIN duaEntry de ON de.entryFk = e.id + FROM vn.`entry` e + JOIN vn.duaEntry de ON de.entryFk = e.id WHERE de.duaFk = vDuaFk AND (NOT e.isBooked OR NOT e.isConfirmed) ), notBookedEntries AS ( SELECT e.id - FROM duaEntry + FROM vn.duaEntry WHERE duaFk = vDuaFk AND NOT customsValue ) -- 2.40.1 From c551e229fba16626939303deda5c4c3582eff2bd Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 25 Jun 2024 13:30:46 +0200 Subject: [PATCH 287/413] feat itemShelvingLog refs #7168 --- .../11116-tealRuscus/00-firstScript.sql | 3 ++ modules/item/back/model-config.json | 5 +- .../item/back/models/item-shelving-log.json | 52 +++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 db/versions/11116-tealRuscus/00-firstScript.sql create mode 100644 modules/item/back/models/item-shelving-log.json diff --git a/db/versions/11116-tealRuscus/00-firstScript.sql b/db/versions/11116-tealRuscus/00-firstScript.sql new file mode 100644 index 000000000..a74021dd5 --- /dev/null +++ b/db/versions/11116-tealRuscus/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +USE vn; +INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) VALUES('ItemShelvingLog', '*', 'READ', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file diff --git a/modules/item/back/model-config.json b/modules/item/back/model-config.json index 40d73f1a6..2d06e1ada 100644 --- a/modules/item/back/model-config.json +++ b/modules/item/back/model-config.json @@ -50,6 +50,9 @@ "ItemShelving": { "dataSource": "vn" }, + "ItemShelvingLog": { + "dataSource": "vn" + }, "ItemShelvingSale": { "dataSource": "vn" }, @@ -74,4 +77,4 @@ "FixedPrice": { "dataSource": "vn" } -} +} \ No newline at end of file diff --git a/modules/item/back/models/item-shelving-log.json b/modules/item/back/models/item-shelving-log.json new file mode 100644 index 000000000..f976008f1 --- /dev/null +++ b/modules/item/back/models/item-shelving-log.json @@ -0,0 +1,52 @@ +{ + "name": "ItemShelvingLog", + "base": "VnModel", + "mixins": { + "Loggable": true + }, + "options": { + "mysql": { + "table": "itemShelvingLog" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "created": { + "type": "date" + }, + "shelvingFk": { + "type": "string" + }, + "itemFk": { + "type": "number" + }, + "visible": { + "type": "number" + }, + "accion": { + "type": "string" + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "shelving": { + "type": "belongsTo", + "model": "Shelving", + "foreignKey": "shelvingFk", + "primaryKey": "code" + } + } +} \ No newline at end of file -- 2.40.1 From acf308fd16672094e326ac1b4fbfe28e64098f52 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 25 Jun 2024 13:35:21 +0200 Subject: [PATCH 288/413] feat itemShelvingLog refs #7168 --- db/versions/11116-tealRuscus/00-firstScript.sql | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/db/versions/11116-tealRuscus/00-firstScript.sql b/db/versions/11116-tealRuscus/00-firstScript.sql index a74021dd5..dc577a36b 100644 --- a/db/versions/11116-tealRuscus/00-firstScript.sql +++ b/db/versions/11116-tealRuscus/00-firstScript.sql @@ -1,3 +1,8 @@ -- Place your SQL code here USE vn; -INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) VALUES('ItemShelvingLog', '*', 'READ', 'ALLOW', 'ROLE', 'production'); \ No newline at end of file +INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) VALUES('ItemShelvingLog', '*', 'READ', 'ALLOW', 'ROLE', 'production'); + +-- redmine regularitzar parking per a que no tinguen espais +ALTER TABLE parking DROP CONSTRAINT chkParkingCodeFormat; +ALTER TABLE parking +ADD CONSTRAINT chkParkingCodeFormat CHECK (CHAR_LENGTH(code) > 4 AND code REGEXP ('^[^ ]+-[^ ]+$')); \ No newline at end of file -- 2.40.1 From e55af8d36f48f7e3fb99ca32c006df3527879fb4 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 25 Jun 2024 13:41:10 +0200 Subject: [PATCH 289/413] feat itemShelvingLog refs #7168 --- .../vn/procedures/itemShelvingLog_get.sql | 54 +++++++++---------- 1 file changed, 26 insertions(+), 28 deletions(-) diff --git a/db/routines/vn/procedures/itemShelvingLog_get.sql b/db/routines/vn/procedures/itemShelvingLog_get.sql index f72a31a9b..ad67ea5cd 100644 --- a/db/routines/vn/procedures/itemShelvingLog_get.sql +++ b/db/routines/vn/procedures/itemShelvingLog_get.sql @@ -1,37 +1,35 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`( - vShelvingFk VARCHAR(10), - vRecords INT -) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`(vShelvingFk VARCHAR(10) ) BEGIN + /** * Devuelve el log de los item en cada carro * - * @param vShelvingFk Matrícula del carro - * @param vRecords Límite de registros retornados + * @param vShelvingFk Matrícula del carro * */ - DECLARE vQuery TEXT; - SET vQuery = ' - SELECT isl.itemFk, - i.longName, - isl.shelvingFk, - w.code, - isl.accion, - isl.quantity, - isl.created - FROM item i - JOIN itemShelvingLog isl ON i.id = isl.itemFk - JOIN worker w ON isl.workerFk = w.id - WHERE shelvingFk = ? - OR isl.itemFk = ? - ORDER BY isl.created DESC'; - - IF vRecords IS NOT NULL THEN - SET vQuery = CONCAT(vQuery, '\nLIMIT ', vRecords); - END IF; - - EXECUTE IMMEDIATE vQuery - USING vShelvingFk, vShelvingFk; + + SELECT isl.itemShelvingFk, + isl.created, + isl.accion, + isl.itemFk, + isl.shelvingFk, + isl.quantity, + isl.visible, + isl.available, + isl.grouping, + isl.packing, + isl.stars, + item.longName, + item.size, + item.subName, + worker.code, + isl.accion + FROM item + JOIN itemShelvingLog isl ON item.id = isl.itemFk + JOIN worker ON isl.workerFk = worker.id + WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk + ORDER BY isl.created DESC; + END$$ DELIMITER ; -- 2.40.1 From 2e1ab3af206ad21a14d9fb5f3046fc2dfb2587b3 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 25 Jun 2024 14:00:46 +0200 Subject: [PATCH 290/413] refs #7486 Fix same assign collection --- .../vn/procedures/collection_assign.sql | 50 +++++++++++++++++-- db/routines/vn/procedures/collection_new.sql | 3 +- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/db/routines/vn/procedures/collection_assign.sql b/db/routines/vn/procedures/collection_assign.sql index fc9f9a711..84067e7d8 100644 --- a/db/routines/vn/procedures/collection_assign.sql +++ b/db/routines/vn/procedures/collection_assign.sql @@ -13,12 +13,39 @@ BEGIN * @param vCollectionFk Id de colección */ DECLARE vHasTooMuchCollections BOOL; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; + + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + CALL util.debugAdd('collection_assign', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk + )); -- Tmp + END IF; + + RESIGNAL; + END; -- Si hay colecciones sin terminar, sale del proceso CALL collection_get(vUserFk); - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName FROM productionConfig pc LEFT JOIN tCollection ON TRUE; @@ -28,6 +55,21 @@ BEGIN CALL util.throw('Hay colecciones pendientes'); END IF; + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + END IF; + -- Se eliminan las colecciones sin asignar que estan obsoletas INSERT INTO ticketTracking(stateFk, ticketFk) SELECT s.id, tc.ticketFk @@ -35,7 +77,7 @@ BEGIN JOIN ticketCollection tc ON tc.collectionFk = c.id JOIN `state` s ON s.code = 'PRINTED_AUTO' JOIN productionConfig pc - WHERE c.workerFk IS NULL + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* @@ -75,5 +117,7 @@ BEGIN UPDATE `collection` SET workerFk = vUserFk WHERE id = vCollectionFk; + + DO RELEASE_LOCK(vLockName); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index b022d8dcc..029427306 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -59,7 +59,8 @@ BEGIN 'errorNumber', vErrorNumber, 'errorMsg', vErrorMsg, 'lockName', vLockName, - 'userFk', vUserFk + 'userFk', vUserFk, + 'ticketFk', vTicketFk )); -- Tmp END IF; -- 2.40.1 From d1ed4b44590c0fb1765fbcbe36bb9703f740fc3f Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 25 Jun 2024 16:03:59 +0200 Subject: [PATCH 291/413] refs #7409 fix back --- modules/worker/back/models/worker.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 323c2cd28..2c749144b 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -118,7 +118,8 @@ }, "incomes": { "type": "hasMany", - "model": "WorkerIncome" + "model": "WorkerIncome", + "foreignKey": "workerFk" }, "trainingCourse": { "type": "hasMany", -- 2.40.1 From 1f6fd8d6d1455f9d76b08890f78da1e991b776b9 Mon Sep 17 00:00:00 2001 From: jorgep Date: Tue, 25 Jun 2024 17:27:00 +0200 Subject: [PATCH 292/413] feat: refs #6286 check if is teamBoss --- .../back/methods/worker-time-control/resendWeeklyHourEmail.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js b/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js index 68d03f7e4..ed6b4e6ab 100644 --- a/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js +++ b/modules/worker/back/methods/worker-time-control/resendWeeklyHourEmail.js @@ -35,8 +35,10 @@ module.exports = Self => { const yearNumber = dated.getFullYear(); const weekNumber = moment(dated).isoWeek(); + const isSubordinate = await models.Worker.isSubordinate(ctx, workerId, myOptions); + const isTeamBoss = await models.ACL.checkAccessAcl(ctx, 'Worker', 'isTeamBoss', 'WRITE'); - if (!await models.Worker.isSubordinate(ctx, workerId) || workerId === ctx.req.accessToken.userId) + if (!isSubordinate || (workerId === ctx.req.accessToken.userId && !isTeamBoss)) throw new UserError(`You don't have enough privileges`); const workerTimeControlMail = await models.WorkerTimeControlMail.findOne({ -- 2.40.1 From 82118ae93315b82e3c4e7498e623d8ca8baec17e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 25 Jun 2024 19:30:59 +0200 Subject: [PATCH 293/413] Hotfix ticketStateUpdate to ticket_setState --- db/routines/vn/procedures/ticket_DelayTruckSplit.sql | 10 +++++----- db/routines/vn/procedures/ticket_cloneWeekly.sql | 2 +- db/routines/vn/procedures/ticket_split.sql | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql index c7de6a984..14720ffc2 100644 --- a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql +++ b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql @@ -1,5 +1,5 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruckSplit`(vTicketFk INT) +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruckSplit`(vTicketFk INT) BEGIN /** * Splita las lineas de ticket que no estan ubicadas @@ -50,8 +50,8 @@ BEGIN SET s.ticketFk = vNewTicketFk; END IF; - CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); + CALL ticket_setState(vNewTicketFk, 'FIXING'); DROP TEMPORARY TABLE tmp.SalesToSplit; -END$$ -DELIMITER ; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_cloneWeekly.sql b/db/routines/vn/procedures/ticket_cloneWeekly.sql index 6bceb2fdf..18a33ac14 100644 --- a/db/routines/vn/procedures/ticket_cloneWeekly.sql +++ b/db/routines/vn/procedures/ticket_cloneWeekly.sql @@ -189,7 +189,7 @@ BEGIN IF NOT vIsDuplicateMail THEN CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage); END IF; - CALL ticketStateUpdate (vNewTicket, 'FIXING'); + CALL ticket_setState(vNewTicket, 'FIXING'); ELSE CALL ticketCalculateClon(vNewTicket, vTicketFk); END IF; diff --git a/db/routines/vn/procedures/ticket_split.sql b/db/routines/vn/procedures/ticket_split.sql index 172f6829a..01eb4d8b9 100644 --- a/db/routines/vn/procedures/ticket_split.sql +++ b/db/routines/vn/procedures/ticket_split.sql @@ -69,7 +69,7 @@ proc:BEGIN s.concept = CONCAT('(s) ', s.concept) WHERE sts.ticketFk = vTicketFk; - CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING'); + CALL ticket_setState(vTicketFutureFk, 'FIXING'); SELECT "new" message,vTicketFutureFk ticketFuture; END$$ -- 2.40.1 From 5bcdc579784e99824625a00e7c2466afbbd1e1e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 25 Jun 2024 19:33:54 +0200 Subject: [PATCH 294/413] Hotfix ticketStateUpdate to ticket_setState --- db/routines/vn/procedures/ticket_split.sql | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/db/routines/vn/procedures/ticket_split.sql b/db/routines/vn/procedures/ticket_split.sql index 01eb4d8b9..07e0329ea 100644 --- a/db/routines/vn/procedures/ticket_split.sql +++ b/db/routines/vn/procedures/ticket_split.sql @@ -18,7 +18,7 @@ proc:BEGIN WHERE ticketFk = vTicketFk; SELECT count(*) INTO vTotalLines - FROM vn.sale s + FROM sale s WHERE s.ticketFk = vTicketFk; SET vHasFullProblem = (vTotalLines = vProblemLines); @@ -26,7 +26,7 @@ proc:BEGIN -- Ticket completo IF vHasFullProblem THEN - UPDATE vn.ticket + UPDATE ticket SET landed = vDated + INTERVAL 1 DAY, shipped = vDated, nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) @@ -40,7 +40,7 @@ proc:BEGIN -- Ticket a futuro existe IF vTicketFutureFk THEN - UPDATE vn.sale s + UPDATE sale s JOIN tmp.salesToSplit ss ON s.id = ss.saleFk SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) @@ -52,10 +52,10 @@ proc:BEGIN END IF; -- Ticket nuevo - CALL vn.ticket_Clone(vTicketFk, vTicketFutureFk); + CALL ticket_Clone(vTicketFk, vTicketFutureFk); - UPDATE vn.ticket t - JOIN vn.productionConfig pc + UPDATE ticket t + JOIN productionConfig pc SET t.routeFk = IF(t.shipped = vDated , t.routeFk, NULL), t.landed = vDated + INTERVAL 1 DAY, t.shipped = vDated, @@ -63,7 +63,7 @@ proc:BEGIN t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - UPDATE vn.sale s + UPDATE sale s JOIN tmp.salesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) -- 2.40.1 From 75486ae743af847d801e1dde4cf11b3b19c69911 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Tue, 25 Jun 2024 19:47:22 +0200 Subject: [PATCH 295/413] Hotfix ticketStateUpdate to ticket_setState --- .../vn/procedures/ticket_DelayTruckSplit.sql | 4 +- .../vn/procedures/ticket_cloneWeekly.sql | 68 ++++++++++++------- db/routines/vn/procedures/ticket_split.sql | 32 ++++----- 3 files changed, 61 insertions(+), 43 deletions(-) diff --git a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql index 14720ffc2..3e5195d9c 100644 --- a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql +++ b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql @@ -1,5 +1,7 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruckSplit`(vTicketFk INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruckSplit`( + vTicketFk INT +) BEGIN /** * Splita las lineas de ticket que no estan ubicadas diff --git a/db/routines/vn/procedures/ticket_cloneWeekly.sql b/db/routines/vn/procedures/ticket_cloneWeekly.sql index 18a33ac14..764e72254 100644 --- a/db/routines/vn/procedures/ticket_cloneWeekly.sql +++ b/db/routines/vn/procedures/ticket_cloneWeekly.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_cloneWeekly`(vDateFrom DATE, vDateTo DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_cloneWeekly`( + vDateFrom DATE, + vDateTo DATE +) BEGIN DECLARE vIsDone BOOL; DECLARE vLanding DATE; @@ -39,9 +42,16 @@ BEGIN DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); DECLARE vMessage TEXT; - + SET vIsDone = FALSE; - FETCH rsTicket INTO vTicketFk,vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk,vShipment; + FETCH rsTicket INTO + vTicketFk, + vClientFk, + vWarehouseFk, + vCompanyFk, + vAddressFk, + vAgencyModeFk, + vShipment; IF vIsDone THEN LEAVE myLoop; @@ -67,7 +77,7 @@ BEGIN AND isDefaultAddress; END IF; - CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk,FALSE); + CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk, FALSE); SET vLanding = NULL; SELECT landed INTO vLanding FROM tmp.zoneGetLanded LIMIT 1; @@ -88,16 +98,22 @@ BEGIN SET clonedFrom = vTicketFk WHERE id = vNewTicket; - INSERT INTO sale (ticketFk, itemFk, concept, quantity, price, - discount, priceFixed, isPriceFixed) + INSERT INTO sale (ticketFk, + itemFk, + concept, + quantity, + price, + discount, + priceFixed, + isPriceFixed) SELECT vNewTicket, - saleOrig.itemFk, - saleOrig.concept, - saleOrig.quantity, - saleOrig.price, - saleOrig.discount, - saleOrig.priceFixed, - saleOrig.isPriceFixed + saleOrig.itemFk, + saleOrig.concept, + saleOrig.quantity, + saleOrig.price, + saleOrig.discount, + saleOrig.priceFixed, + saleOrig.isPriceFixed FROM sale saleOrig WHERE saleOrig.ticketFk = vTicketFk; @@ -123,20 +139,20 @@ BEGIN ,attenderFk, ticketFk) SELECT description, - ordered, - shipped, - quantity, - price, - itemFk, - clientFk, - response, - total, - buyed, - requesterFk, - attenderFk, - vNewTicket + ordered, + shipped, + quantity, + price, + itemFk, + clientFk, + response, + total, + buyed, + requesterFk, + attenderFk, + vNewTicket FROM ticketRequest - WHERE ticketFk =vTicketFk; + WHERE ticketFk =vTicketFk; SELECT id INTO vSalesPersonFK FROM observationType diff --git a/db/routines/vn/procedures/ticket_split.sql b/db/routines/vn/procedures/ticket_split.sql index 07e0329ea..9a359b83f 100644 --- a/db/routines/vn/procedures/ticket_split.sql +++ b/db/routines/vn/procedures/ticket_split.sql @@ -1,5 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_split`(vTicketFk INT, vTicketFutureFk INT, vDated DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_split`( + vTicketFk INT, + vTicketFutureFk INT, + vDated DATE +) proc:BEGIN /** * Mueve las lineas con problemas a otro ticket existente o a uno nuevo. @@ -17,7 +21,7 @@ proc:BEGIN FROM tmp.salesToSplit WHERE ticketFk = vTicketFk; - SELECT count(*) INTO vTotalLines + SELECT COUNT(*) INTO vTotalLines FROM sale s WHERE s.ticketFk = vTicketFk; @@ -25,52 +29,48 @@ proc:BEGIN -- Ticket completo IF vHasFullProblem THEN - UPDATE ticket - SET landed = vDated + INTERVAL 1 DAY, + SET landed = vDated + INTERVAL 1 DAY, shipped = vDated, - nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) + nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname) WHERE id = vTicketFk; - SELECT "moved" message, NULL ticketFuture; + SELECT 'moved' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket a futuro existe IF vTicketFutureFk THEN - UPDATE sale s - JOIN tmp.salesToSplit ss ON s.id = ss.saleFk + JOIN tmp.salesToSplit ss ON s.id = ss.saleFk SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE ss.ticketFk = vTicketFk; - SELECT "future" message, NULL ticketFuture; + SELECT 'future' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket nuevo CALL ticket_Clone(vTicketFk, vTicketFutureFk); UPDATE ticket t - JOIN productionConfig pc + JOIN productionConfig pc SET t.routeFk = IF(t.shipped = vDated , t.routeFk, NULL), - t.landed = vDated + INTERVAL 1 DAY, + t.landed = vDated + INTERVAL 1 DAY, t.shipped = vDated, t.agencyModeFk = pc.defautlAgencyMode, t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - + UPDATE sale s - JOIN tmp.salesToSplit sts ON sts.saleFk = s.id + JOIN tmp.salesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE sts.ticketFk = vTicketFk; CALL ticket_setState(vTicketFutureFk, 'FIXING'); - SELECT "new" message,vTicketFutureFk ticketFuture; + SELECT 'new' message, vTicketFutureFk ticketFuture; END$$ DELIMITER ; -- 2.40.1 From 0534526ac217774581922736b4b74abdf8ac815a Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 26 Jun 2024 09:03:06 +0200 Subject: [PATCH 296/413] fix: refs #7039 filterFix --- front/salix/components/bank-entity/index.html | 2 +- modules/client/back/methods/client/getCard.js | 2 +- modules/client/back/methods/client/summary.js | 2 +- modules/client/front/address/index/index.js | 2 +- modules/client/front/extended-list/index.js | 2 +- modules/item/back/methods/item/getSummary.js | 2 +- modules/supplier/back/methods/supplier/getSummary.js | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/front/salix/components/bank-entity/index.html b/front/salix/components/bank-entity/index.html index 6ce073f1a..915294671 100644 --- a/front/salix/components/bank-entity/index.html +++ b/front/salix/components/bank-entity/index.html @@ -27,7 +27,7 @@ vn-id="country" ng-model="$ctrl.data.countryFk" url="Countries" - fields="['id', 'country', 'code']" + fields="['id', 'name', 'code']" show-field="name" value-field="id" label="Country"> diff --git a/modules/client/back/methods/client/getCard.js b/modules/client/back/methods/client/getCard.js index 10e6f7adf..c15c260bc 100644 --- a/modules/client/back/methods/client/getCard.js +++ b/modules/client/back/methods/client/getCard.js @@ -50,7 +50,7 @@ module.exports = function(Self) { { relation: 'country', scope: { - fields: ['id', 'country'] + fields: ['id', 'name'] } }, { diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js index 8de887b47..8162096f0 100644 --- a/modules/client/back/methods/client/summary.js +++ b/modules/client/back/methods/client/summary.js @@ -54,7 +54,7 @@ module.exports = Self => { { relation: 'country', scope: { - fields: ['country'] + fields: ['name'] } }, { diff --git a/modules/client/front/address/index/index.js b/modules/client/front/address/index/index.js index 4bad9d4c8..f47d079b2 100644 --- a/modules/client/front/address/index/index.js +++ b/modules/client/front/address/index/index.js @@ -37,7 +37,7 @@ class Controller extends Section { include: { relation: 'country', scope: { - fields: ['id', 'country'] + fields: ['id', 'name'] } } } diff --git a/modules/client/front/extended-list/index.js b/modules/client/front/extended-list/index.js index 8eed48d01..208d77539 100644 --- a/modules/client/front/extended-list/index.js +++ b/modules/client/front/extended-list/index.js @@ -28,7 +28,7 @@ class Controller extends Section { field: 'countryFk', autocomplete: { url: 'Countries', - showField: 'country', + showField: 'name', } }, { diff --git a/modules/item/back/methods/item/getSummary.js b/modules/item/back/methods/item/getSummary.js index 17a38cf07..55222f133 100644 --- a/modules/item/back/methods/item/getSummary.js +++ b/modules/item/back/methods/item/getSummary.js @@ -59,7 +59,7 @@ module.exports = Self => { include: [{ relation: 'country', scope: { - fields: ['id', 'country'] + fields: ['id', 'name'] } }, { relation: 'taxClass', diff --git a/modules/supplier/back/methods/supplier/getSummary.js b/modules/supplier/back/methods/supplier/getSummary.js index 699233386..67767e7b4 100644 --- a/modules/supplier/back/methods/supplier/getSummary.js +++ b/modules/supplier/back/methods/supplier/getSummary.js @@ -55,7 +55,7 @@ module.exports = Self => { { relation: 'country', scope: { - fields: ['id', 'country', 'code'] + fields: ['id', 'name', 'code'] } }, { -- 2.40.1 From b4afb883fc71e335ef41572d2dbc77c1126f0536 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 26 Jun 2024 09:35:18 +0200 Subject: [PATCH 297/413] feat(salix): refs #6436 #6436 remove unnecessary object.assign --- back/vn-jasmine.js | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/back/vn-jasmine.js b/back/vn-jasmine.js index c2d8a497c..2b981c6d9 100644 --- a/back/vn-jasmine.js +++ b/back/vn-jasmine.js @@ -27,13 +27,7 @@ const default_loopback_ctx = userId => { }; function vnBeforeAll() { - Object.assign(beforeAll, {getCtx: default_before_all}); - Object.assign(beforeAll, {mockLoopBackContext}); -} -function mockBeforeAll(value = default_before_all) { - const origin = beforeAll.ctx; - Object.assign(origin, value); - return origin; + Object.assign(beforeAll, {getCtx: default_before_all, mockLoopBackContext}); } const mockLoopBackContext = userId => { @@ -46,7 +40,7 @@ const mockLoopBackContext = userId => { return activeCtx; }; module.exports = { - mockBeforeAll, mockLoopBackContext + mockLoopBackContext }; (function init() { -- 2.40.1 From c4af92e9baebb23ea09f4a8b63b8f69f7199b94e Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 26 Jun 2024 09:54:51 +0200 Subject: [PATCH 298/413] horfix: ticket 197676 --- db/routines/vn/procedures/client_unassignSalesPerson.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/db/routines/vn/procedures/client_unassignSalesPerson.sql b/db/routines/vn/procedures/client_unassignSalesPerson.sql index f939ae68b..8773104ca 100644 --- a/db/routines/vn/procedures/client_unassignSalesPerson.sql +++ b/db/routines/vn/procedures/client_unassignSalesPerson.sql @@ -26,6 +26,7 @@ BEGIN JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk + JOIN bs.clientDiedPeriod cdp ON cdp.countryFk = co.id WHERE cd.warning = 'third' AND cp.clientFk IS NULL AND sp.salesPersonFk IS NULL -- 2.40.1 From cca62ae90242766767c64f18df758d2b9b45385f Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 26 Jun 2024 12:25:18 +0200 Subject: [PATCH 299/413] feat: return sql check error --- loopback/locale/es.json | 3 ++- loopback/server/middleware/error-handler.js | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 5b5928993..e2be5d013 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -366,5 +366,6 @@ "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", "Payment method is required": "El método de pago es obligatorio", - "Cannot send mail": "Não é possível enviar o email" + "Cannot send mail": "Não é possível enviar o email", + "CONSTRAINT `supplierAccountTooShort` failed for `vn`.`supplier`": "La cuenta debe tener exactamente 10 dígitos" } diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index cc7b81618..beeff95ae 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -22,7 +22,7 @@ module.exports = function() { } // MySQL user-defined exceptions - if (err.sqlState == '45000') + if (err.sqlState == '45000' || err?.errno == 4025) return next(new UserError(req.__(err.sqlMessage))); // Logs error to console -- 2.40.1 From cbc00b90b96797da9672aed997c2f77cd6fe9b53 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 26 Jun 2024 14:02:25 +0200 Subject: [PATCH 300/413] feat front-reservas refs #6861 --- modules/worker/back/models/operator.json | 44 +++++++++++++----------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/modules/worker/back/models/operator.json b/modules/worker/back/models/operator.json index a2f3ee01c..d4832bccf 100644 --- a/modules/worker/back/models/operator.json +++ b/modules/worker/back/models/operator.json @@ -26,29 +26,33 @@ }, "labelerFk": { "type": "number" + }, + "isOnReservationMode": { + "type": "boolean", + "required": true } - }, + }, "relations": { - "sector": { - "type": "belongsTo", - "model": "Sector", - "foreignKey": "sectorFk" - }, + "sector": { + "type": "belongsTo", + "model": "Sector", + "foreignKey": "sectorFk" + }, "train": { - "type": "belongsTo", - "model": "Train", - "foreignKey": "trainFk" - }, + "type": "belongsTo", + "model": "Train", + "foreignKey": "trainFk" + }, "printer": { - "type": "belongsTo", - "model": "Printer", - "foreignKey": "labelerFk" - }, + "type": "belongsTo", + "model": "Printer", + "foreignKey": "labelerFk" + }, "itemPackingType": { - "type": "belongsTo", - "model": "ItemPackingType", - "foreignKey": "itemPackingTypeFk", + "type": "belongsTo", + "model": "ItemPackingType", + "foreignKey": "itemPackingTypeFk", "primaryKey": "code" - } - } -} + } + } +} \ No newline at end of file -- 2.40.1 From 0da6d633fd4fdea65965547656eb9de22582a887 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 26 Jun 2024 17:21:22 +0200 Subject: [PATCH 301/413] fix: refs 197934 add alias --- print/templates/reports/invoice-incoterms/sql/incoterms.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/print/templates/reports/invoice-incoterms/sql/incoterms.sql b/print/templates/reports/invoice-incoterms/sql/incoterms.sql index bbe4b2a0d..016a8342e 100644 --- a/print/templates/reports/invoice-incoterms/sql/incoterms.sql +++ b/print/templates/reports/invoice-incoterms/sql/incoterms.sql @@ -12,7 +12,7 @@ SELECT GROUP_CONCAT(DISTINCT ir.description ORDER BY ir.description SEPARATOR ' JOIN vn.sale s ON t.id = s.ticketFk JOIN vn.item i ON i.id = s.itemFk JOIN vn.intrastat ir ON ir.id = i.intrastatFk -)SELECT SUM(t.packages), +)SELECT SUM(t.packages) packages, a.incotermsFk, ic.name incotermsName, MAX(t.weight) weight, -- 2.40.1 From 47a0cb6d4f7e4be3a02fc7f884ee0cbd09929c61 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 27 Jun 2024 09:27:37 +0200 Subject: [PATCH 302/413] fix: refs #6238 insert ignore --- .../11102-wheatCarnation/00-createTravelKgPercentage.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql b/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql index 6c8bb4784..3abcd0074 100644 --- a/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql +++ b/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql @@ -3,7 +3,7 @@ CREATE TABLE IF NOT EXISTS vn.travelKgPercentage ( className VARCHAR(50) ); -INSERT INTO vn.travelKgPercentage (value, className) +INSERT IGNORE INTO vn.travelKgPercentage (value, className) VALUES (80, 'primary'), (100, 'alert'); -- 2.40.1 From 1b7c7336afcb918f807b270be5729b698cf73886 Mon Sep 17 00:00:00 2001 From: jorgep Date: Thu, 27 Jun 2024 10:08:58 +0200 Subject: [PATCH 303/413] fix: refs #6238 delete unused SQL script --- .../11114-goldenDracena/00-firstScript.sql | 18 ------------------ 1 file changed, 18 deletions(-) delete mode 100644 db/versions/11114-goldenDracena/00-firstScript.sql diff --git a/db/versions/11114-goldenDracena/00-firstScript.sql b/db/versions/11114-goldenDracena/00-firstScript.sql deleted file mode 100644 index cc283f418..000000000 --- a/db/versions/11114-goldenDracena/00-firstScript.sql +++ /dev/null @@ -1,18 +0,0 @@ --- Place your SQL code here -CREATE TABLE IF NOT EXISTS vn.travelKgPercentage ( - value INT(3) PRIMARY KEY, - className VARCHAR(50) -); - -INSERT IGNORE INTO vn.travelKgPercentage (value, className) - VALUES - (80, 'primary'), - (100, 'alert'); - -INSERT IGNORE INTO salix.ACL - SET model = 'TravelKgPercentage', - property = '*', - accessType = 'READ', - permission = 'ALLOW', - principalType = 'ROLE', - principalId = 'employee'; \ No newline at end of file -- 2.40.1 From e8dc6eafdcb8cf99f5bb105bb0f2c0df007b1796 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 27 Jun 2024 10:18:43 +0200 Subject: [PATCH 304/413] refs #7640 multiple inventory --- .../vn/procedures/multipleInventory.sql | 42 +++++++++++-------- 1 file changed, 24 insertions(+), 18 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 2a28aa9a0..1bbf4c6c7 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -1,9 +1,9 @@ -DELIMITER $$ +DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`multipleInventory`( vDate DATE, vWarehouseFk TINYINT, vMaxDays TINYINT -) +) proc: BEGIN DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; DECLARE vDateFrom DATE DEFAULT vDate; @@ -36,9 +36,12 @@ proc: BEGIN ADD `life` TINYINT NOT NULL DEFAULT '0'; -- Calculo del inventario - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal + CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, + SUM(quantity) quantity, + SUM(quantity) visible FROM ( SELECT s.itemFk, - s.quantity quantity FROM sale s @@ -69,18 +72,13 @@ proc: BEGIN AND w.isComparative AND NOT e.isExcludedFromAvailable AND NOT e.isRaid - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.inventory = sub.Subtotal, - ai.visible = sub.Subtotal, - ai.avalaible = sub.Subtotal, - ai.sd = sub.Subtotal; + ) sub + GROUP BY itemFk; -- Cálculo del visible - UPDATE tmp.itemInventory ai + UPDATE tItemInventoryCalc iic JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal + SELECT itemFk, SUM(quantity) visible FROM ( SELECT s.itemFk, s.quantity FROM sale s @@ -117,8 +115,15 @@ proc: BEGIN AND w.isComparative ) sub2 GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.visible = ai.visible + sub.Subtotal; + ) sub ON sub.itemFk = iic.itemFk + SET iic.visible = iic.visible + sub.visible; + + UPDATE tmp.itemInventory ai + JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + SET ai.inventory = iic.quantity, + ai.visible = iic.visible, + ai.avalaible = iic.quantity, + ai.sd = iic.quantity; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc @@ -189,6 +194,7 @@ proc: BEGIN DROP TEMPORARY TABLE tmp.itemTravel, tmp.itemCalc, + tItemInventoryCalc, tmp.itemAtp; -END$$ -DELIMITER ; +END$$ +DELIMITER ; -- 2.40.1 From 746fa82f2a9d782e2989d4ee440d5fc6ad5924ee Mon Sep 17 00:00:00 2001 From: sergiodt Date: Thu, 27 Jun 2024 13:20:52 +0200 Subject: [PATCH 305/413] feat expeditionPalletPrint refs #5210 --- .../vn/procedures/expeditionPallet_printLabel.sql | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/expeditionPallet_printLabel.sql b/db/routines/vn/procedures/expeditionPallet_printLabel.sql index ada11daab..7aaf8cedb 100644 --- a/db/routines/vn/procedures/expeditionPallet_printLabel.sql +++ b/db/routines/vn/procedures/expeditionPallet_printLabel.sql @@ -9,7 +9,16 @@ BEGIN */ DECLARE vPrinterFk INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + DECLARE vIsInExpeditionPallet BOOL; + + SELECT COUNT(id) INTO vIsInExpeditionPallet + FROM expeditionPallet + WHERE id = vSelf; + + IF NOT vIsInExpeditionPallet THEN + CALL util.throw("ExpeditionPallet not exists"); + END IF; + SELECT o.labelerFk INTO vPrinterFk FROM operator o WHERE o.workerFk = vUserFk; -- 2.40.1 From 9164901eac6a512d59310dc4d356d8915d70b027 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 27 Jun 2024 13:26:59 +0200 Subject: [PATCH 306/413] refs #7640 Requested changes --- db/routines/vn/procedures/multipleInventory.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 1bbf4c6c7..ece57727d 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -119,11 +119,11 @@ proc: BEGIN SET iic.visible = iic.visible + sub.visible; UPDATE tmp.itemInventory ai - JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id - SET ai.inventory = iic.quantity, - ai.visible = iic.visible, - ai.avalaible = iic.quantity, - ai.sd = iic.quantity; + JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + SET ai.inventory = iic.quantity, + ai.visible = iic.visible, + ai.avalaible = iic.quantity, + ai.sd = iic.quantity; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc -- 2.40.1 From f1f57a388d8daf5b99f8032c7e6b5508c8b99560 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 28 Jun 2024 08:45:18 +0200 Subject: [PATCH 307/413] feat: refs #7296 drop column expeditionTruckFk --- db/versions/11117-blueGalax/00-firstScript.sql | 2 ++ modules/ticket/back/methods/ticket/addSale.js | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 db/versions/11117-blueGalax/00-firstScript.sql diff --git a/db/versions/11117-blueGalax/00-firstScript.sql b/db/versions/11117-blueGalax/00-firstScript.sql new file mode 100644 index 000000000..63ea40cd2 --- /dev/null +++ b/db/versions/11117-blueGalax/00-firstScript.sql @@ -0,0 +1,2 @@ +-- Place your SQL code here +ALTER TABLE vn.routesMonitor DROP COLUMN expeditionTruckFk; \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index 8dc7a633c..c0eb3b58b 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -70,7 +70,7 @@ module.exports = Self => { quantity: quantity }, myOptions); - await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id], myOptions); + await Self.rawSql('CALL vn.sale_calculateComponent(?, )', [newSale.id], myOptions); await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [id], myOptions); const sale = await models.Sale.findById(newSale.id, { -- 2.40.1 From ca3750ebac9397782e16eaee4561df84a92d9ffd Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 28 Jun 2024 08:46:54 +0200 Subject: [PATCH 308/413] feat: refs #7296 --- modules/ticket/back/methods/ticket/addSale.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index c0eb3b58b..8dc7a633c 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -70,7 +70,7 @@ module.exports = Self => { quantity: quantity }, myOptions); - await Self.rawSql('CALL vn.sale_calculateComponent(?, )', [newSale.id], myOptions); + await Self.rawSql('CALL vn.sale_calculateComponent(?, NULL)', [newSale.id], myOptions); await Self.rawSql('CALL vn.ticket_recalc(?, NULL)', [id], myOptions); const sale = await models.Sale.findById(newSale.id, { -- 2.40.1 From 94a73294cb57b40bc0e84b32e530afff29631d7c Mon Sep 17 00:00:00 2001 From: pablone Date: Fri, 28 Jun 2024 09:11:20 +0200 Subject: [PATCH 309/413] fix: refs #6404 get label --- back/methods/mrw-config/getLabel.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/methods/mrw-config/getLabel.js b/back/methods/mrw-config/getLabel.js index ae6bc8f21..aa9b87af1 100644 --- a/back/methods/mrw-config/getLabel.js +++ b/back/methods/mrw-config/getLabel.js @@ -4,7 +4,7 @@ module.exports = Self => { accessType: 'READ', accepts: [{ arg: 'shipmentId', - type: 'number', + type: 'string', required: true }], returns: { -- 2.40.1 From 8b617df13d6846670a9c5db69ee96b3f0a5a2ba6 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 28 Jun 2024 09:59:55 +0200 Subject: [PATCH 310/413] feat: refs #7116 create table --- db/versions/10960-silverRoebelini/00-firstScript.sql | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql index c72ce10a7..264e30791 100644 --- a/db/versions/10960-silverRoebelini/00-firstScript.sql +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -1,10 +1,7 @@ -- Place your SQL code here CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `code` varchar(50) DEFAULT NULL, - `description` varchar(50) DEFAULT NULL, - `isOrigin` tinyint(1) DEFAULT NULL, - PRIMARY KEY (`id`) + `agencyModeFk` int(11) NOT NULL AUTO_INCREMENT, + PRIMARY KEY (`agencyModeFk`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 -- 2.40.1 From 19bf606330b622c947a8056eb997703123ef276a Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 28 Jun 2024 12:57:27 +0200 Subject: [PATCH 311/413] refs #7644 First commit --- .../entry/back/methods/entry/entryLabel.js | 36 ++++++++ modules/entry/back/models/entry.js | 1 + .../reports/entry-label/assets/css/import.js | 12 +++ .../reports/entry-label/assets/css/style.css | 58 ++++++++++++ .../reports/entry-label/entry-label.html | 89 +++++++++++++++++++ .../reports/entry-label/entry-label.js | 36 ++++++++ .../reports/entry-label/locale/es.yml | 1 + .../reports/entry-label/options.json | 11 +++ .../reports/entry-label/sql/entry.sql | 17 ++++ 9 files changed, 261 insertions(+) create mode 100644 modules/entry/back/methods/entry/entryLabel.js create mode 100644 print/templates/reports/entry-label/assets/css/import.js create mode 100644 print/templates/reports/entry-label/assets/css/style.css create mode 100644 print/templates/reports/entry-label/entry-label.html create mode 100755 print/templates/reports/entry-label/entry-label.js create mode 100644 print/templates/reports/entry-label/locale/es.yml create mode 100644 print/templates/reports/entry-label/options.json create mode 100644 print/templates/reports/entry-label/sql/entry.sql diff --git a/modules/entry/back/methods/entry/entryLabel.js b/modules/entry/back/methods/entry/entryLabel.js new file mode 100644 index 000000000..50e82b54c --- /dev/null +++ b/modules/entry/back/methods/entry/entryLabel.js @@ -0,0 +1,36 @@ +module.exports = Self => { + Self.remoteMethodCtx('entryLabel', { + description: 'Returns the entry labels', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'The entry id', + http: {source: 'path'} + } + ], + returns: [ + { + arg: 'body', + type: 'file', + root: true + }, { + arg: 'Content-Type', + type: 'String', + http: {target: 'header'} + }, { + arg: 'Content-Disposition', + type: 'String', + http: {target: 'header'} + } + ], + http: { + path: '/:id/entry-label', + verb: 'GET' + } + }); + + Self.entryLabel = (ctx, id) => Self.printReport(ctx, id, 'entry-label'); +}; diff --git a/modules/entry/back/models/entry.js b/modules/entry/back/models/entry.js index 6148ae559..10f63b9f0 100644 --- a/modules/entry/back/models/entry.js +++ b/modules/entry/back/models/entry.js @@ -9,6 +9,7 @@ module.exports = Self => { require('../methods/entry/entryOrderPdf')(Self); require('../methods/entry/addFromPackaging')(Self); require('../methods/entry/addFromBuy')(Self); + require('../methods/entry/entryLabel')(Self); Self.observe('before save', async function(ctx, options) { if (ctx.isNewInstance) return; diff --git a/print/templates/reports/entry-label/assets/css/import.js b/print/templates/reports/entry-label/assets/css/import.js new file mode 100644 index 000000000..37a98dfdd --- /dev/null +++ b/print/templates/reports/entry-label/assets/css/import.js @@ -0,0 +1,12 @@ +const Stylesheet = require(`vn-print/core/stylesheet`); + +const path = require('path'); +const vnPrintPath = path.resolve('print'); + +module.exports = new Stylesheet([ + `${vnPrintPath}/common/css/spacing.css`, + `${vnPrintPath}/common/css/misc.css`, + `${vnPrintPath}/common/css/layout.css`, + `${vnPrintPath}/common/css/report.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/reports/entry-label/assets/css/style.css b/print/templates/reports/entry-label/assets/css/style.css new file mode 100644 index 000000000..ccafa7078 --- /dev/null +++ b/print/templates/reports/entry-label/assets/css/style.css @@ -0,0 +1,58 @@ +html { + height: 100%; + margin-top: -6px; +} +* { + box-sizing: border-box; + font-family: "Roboto", "Helvetica", "Arial", sans-serif; + font-size: 28px; +} +table { + border: 1px solid; + width: 100%; + font-size: inherit; +} +td { + border: 1px solid; + padding: 5px; + width: 100%; +} +#barcode { + text-align: center; +} +span { + font-size: 48px; + font-weight: bold; +} +.lbl { + color: gray; + font-weight: lighter; + font-size: 18px; + display: block; +} +.flex-container { + display: flex; + justify-content: space-between; +} +.flex-item { + flex: 1; +} +.section { + height: 50px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +#variant { + width: 314px; +} +#producer { + width: 471px; +} +.cell { + width: 157px; +} + +#leftBox { + border-right: 1px solid; +} \ No newline at end of file diff --git a/print/templates/reports/entry-label/entry-label.html b/print/templates/reports/entry-label/entry-label.html new file mode 100644 index 000000000..6973adbea --- /dev/null +++ b/print/templates/reports/entry-label/entry-label.html @@ -0,0 +1,89 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ Variedad: + {{buy.name}} +
+
+
+ Medida: + {{buy.size}} +
+
+
+ Categoría: + {{buy.category}} +
+
+
+ Color: + {{buy.color}} +
+
+
+ Origen: + {{buy.origin}} +
+
+
+ Packing: + {{buy.packing}} +
+
+
+ Grouping: + {{buy.grouping}} +
+
+
+ Und. venta: + {{buy.stems}} +
+
+
+ {{buy.id}} +
+
+ Productor: + {{buy.producer}} +
+
+
+
+ Control: + 06/11 +
+
+ Caja nº: + {{`${buy.labelNum} / ${maxLabelNum}`}} +
+
+
+ diff --git a/print/templates/reports/entry-label/entry-label.js b/print/templates/reports/entry-label/entry-label.js new file mode 100755 index 000000000..62186df4c --- /dev/null +++ b/print/templates/reports/entry-label/entry-label.js @@ -0,0 +1,36 @@ +const vnReport = require('../../../core/mixins/vn-report.js'); +const {DOMImplementation, XMLSerializer} = require('xmldom'); +const jsBarcode = require('jsbarcode'); + +module.exports = { + name: 'entry-label', + mixins: [vnReport], + async serverPrefetch() { + this.buys = await this.rawSqlFromDef('entry', [this.id]); + const maxLabelNum = Math.max(...this.buys.map(buy => buy.labelNum)); + this.maxLabelNum = maxLabelNum; + }, + methods: { + getBarcode(id) { + const xmlSerializer = new XMLSerializer(); + const document = new DOMImplementation().createDocument('http://www.w3.org/1999/xhtml', 'html', null); + const svgNode = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + + jsBarcode(svgNode, id, { + xmlDocument: document, + format: 'code128', + displayValue: false, + width: 3.8, + height: 115, + }); + return xmlSerializer.serializeToString(svgNode); + } + }, + props: { + id: { + type: Number, + required: true, + description: 'The entry id' + } + } +}; diff --git a/print/templates/reports/entry-label/locale/es.yml b/print/templates/reports/entry-label/locale/es.yml new file mode 100644 index 000000000..278946f3e --- /dev/null +++ b/print/templates/reports/entry-label/locale/es.yml @@ -0,0 +1 @@ +reportName: Etiqueta \ No newline at end of file diff --git a/print/templates/reports/entry-label/options.json b/print/templates/reports/entry-label/options.json new file mode 100644 index 000000000..d2ed03e32 --- /dev/null +++ b/print/templates/reports/entry-label/options.json @@ -0,0 +1,11 @@ +{ + "width": "10cm", + "height": "10.3cm", + "margin": { + "top": "0.17cm", + "right": "0.2cm", + "bottom": "0cm", + "left": "0cm" + }, + "printBackground": true +} \ No newline at end of file diff --git a/print/templates/reports/entry-label/sql/entry.sql b/print/templates/reports/entry-label/sql/entry.sql new file mode 100644 index 000000000..21511df64 --- /dev/null +++ b/print/templates/reports/entry-label/sql/entry.sql @@ -0,0 +1,17 @@ +SELECT ROW_NUMBER() OVER(ORDER BY b.id) labelNum, + i.name, + i.`size`, + i.category, + ink.id color, + o.code origin, + b.packing, + b.`grouping`, + i.stems, + b.id, + p.name producer + FROM buy b + JOIN item i ON i.id = b.itemFk + LEFT JOIN producer p ON p.id = i.producerFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN origin o ON o.id = i.originFk + WHERE b.entryFk = ? \ No newline at end of file -- 2.40.1 From 08c9d43b17e11725004a25e37ca00444920e3c95 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 28 Jun 2024 13:30:08 +0200 Subject: [PATCH 312/413] refs #7486 Declare exit handler fix collection_assign error --- .../ticket_splitItemPackingType.sql | 39 ++++++++++++------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index d6424efad..b28b16432 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -1,6 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitItemPackingType`(vTicketFk INT, vOriginalItemPackingTypeFk VARCHAR(1)) -proc:BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitItemPackingType`( + vTicketFk INT, + vOriginalItemPackingTypeFk VARCHAR(1) +) +BEGIN /** * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. * Respeta el id inicial para el tipo propuesto. @@ -22,22 +25,28 @@ proc:BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + DELETE FROM vn.sale WHERE quantity = 0 AND ticketFk = vTicketFk; - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale + CREATE OR REPLACE TEMPORARY TABLE tmp.sale (PRIMARY KEY (id)) + ENGINE = MEMORY SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id WHERE s.ticketFk = vTicketFk; - DROP TEMPORARY TABLE IF EXISTS tmp.saleGroup; - CREATE TEMPORARY TABLE tmp.saleGroup - SELECT itemPackingTypeFk , sum(litros) AS totalLitros + CREATE OR REPLACE TEMPORARY TABLE tmp.saleGroup + (PRIMARY KEY (itemPackingTypeFk)) + ENGINE = MEMORY + SELECT itemPackingTypeFk, SUM(litros) totalLitros FROM tmp.sale GROUP BY itemPackingTypeFk; @@ -45,10 +54,11 @@ proc:BEGIN FROM tmp.saleGroup WHERE itemPackingTypeFk IS NOT NULL; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketIPT; - CREATE TEMPORARY TABLE tmp.ticketIPT - (ticketFk INT, - itemPackingTypeFk VARCHAR(1)); + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT ( + ticketFk INT, + itemPackingTypeFk VARCHAR(1), + PRIMARY KEY (ticketFk) + ) ENGINE = MEMORY; CASE vPackingTypesToSplit WHEN 0 THEN @@ -89,7 +99,7 @@ proc:BEGIN SELECT itemPackingTypeFk INTO vItemPackingTypeFk FROM tmp.saleGroup sg - WHERE NOT ISNULL(sg.itemPackingTypeFk) + WHERE sg.itemPackingTypeFk IS NOT NULL ORDER BY sg.itemPackingTypeFk LIMIT 1; @@ -100,7 +110,8 @@ proc:BEGIN WHERE ts.itemPackingTypeFk IS NULL; END CASE; - DROP TEMPORARY TABLE tmp.sale; - DROP TEMPORARY TABLE tmp.saleGroup; + DROP TEMPORARY TABLE + tmp.sale, + tmp.saleGroup; END$$ DELIMITER ; -- 2.40.1 From 85c7336d923edccbac888dfd8f367744a8ed5a56 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 28 Jun 2024 14:52:19 +0200 Subject: [PATCH 313/413] refs #7644 Minor changes --- .../reports/entry-label/assets/css/style.css | 29 +++--------- .../reports/entry-label/entry-label.html | 46 +++++++++---------- .../reports/entry-label/entry-label.js | 3 +- .../reports/entry-label/options.json | 2 +- .../reports/entry-label/sql/entry.sql | 2 +- 5 files changed, 32 insertions(+), 50 deletions(-) diff --git a/print/templates/reports/entry-label/assets/css/style.css b/print/templates/reports/entry-label/assets/css/style.css index ccafa7078..0d4a2891d 100644 --- a/print/templates/reports/entry-label/assets/css/style.css +++ b/print/templates/reports/entry-label/assets/css/style.css @@ -1,10 +1,6 @@ html { - height: 100%; - margin-top: -6px; -} -* { - box-sizing: border-box; font-family: "Roboto", "Helvetica", "Arial", sans-serif; + margin-top: -7px; font-size: 28px; } table { @@ -17,9 +13,6 @@ td { padding: 5px; width: 100%; } -#barcode { - text-align: center; -} span { font-size: 48px; font-weight: bold; @@ -30,29 +23,19 @@ span { font-size: 18px; display: block; } -.flex-container { - display: flex; - justify-content: space-between; -} -.flex-item { - flex: 1; -} -.section { +.cell { + width: 157px; height: 50px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.barcode { + text-align: center; +} #variant { width: 314px; } #producer { width: 471px; -} -.cell { - width: 157px; -} - -#leftBox { - border-right: 1px solid; } \ No newline at end of file diff --git a/print/templates/reports/entry-label/entry-label.html b/print/templates/reports/entry-label/entry-label.html index 6973adbea..53980c534 100644 --- a/print/templates/reports/entry-label/entry-label.html +++ b/print/templates/reports/entry-label/entry-label.html @@ -4,14 +4,14 @@ -
- Variedad: +
+ Variedad {{buy.name}}
- Medida: + Medida {{buy.size}}
@@ -19,68 +19,68 @@
- Categoría: + Categoría {{buy.category}}
- Color: + Color {{buy.color}}
- Origen: - {{buy.origin}} + Origen + {{buy.code}}
- Packing: + Packing {{buy.packing}}
- Grouping: + Grouping {{buy.grouping}}
- Und. venta: + Ud. venta {{buy.stems}}
- +
{{buy.id}} -
- Productor: +
+ Productor {{buy.producer}}
- -
-
- Control: - 06/11 -
-
- Caja nº: - {{`${buy.labelNum} / ${maxLabelNum}`}} -
+ +
+ Control + 06 / 11 +
+ + +
+ Caja nº + {{`${buy.labelNum} / ${maxLabelNum}`}}
diff --git a/print/templates/reports/entry-label/entry-label.js b/print/templates/reports/entry-label/entry-label.js index 62186df4c..e3788261a 100755 --- a/print/templates/reports/entry-label/entry-label.js +++ b/print/templates/reports/entry-label/entry-label.js @@ -7,8 +7,7 @@ module.exports = { mixins: [vnReport], async serverPrefetch() { this.buys = await this.rawSqlFromDef('entry', [this.id]); - const maxLabelNum = Math.max(...this.buys.map(buy => buy.labelNum)); - this.maxLabelNum = maxLabelNum; + this.maxLabelNum = Math.max(...this.buys.map(buy => buy.labelNum)); }, methods: { getBarcode(id) { diff --git a/print/templates/reports/entry-label/options.json b/print/templates/reports/entry-label/options.json index d2ed03e32..4ed0461b3 100644 --- a/print/templates/reports/entry-label/options.json +++ b/print/templates/reports/entry-label/options.json @@ -1,6 +1,6 @@ { "width": "10cm", - "height": "10.3cm", + "height": "10cm", "margin": { "top": "0.17cm", "right": "0.2cm", diff --git a/print/templates/reports/entry-label/sql/entry.sql b/print/templates/reports/entry-label/sql/entry.sql index 21511df64..50b34bd03 100644 --- a/print/templates/reports/entry-label/sql/entry.sql +++ b/print/templates/reports/entry-label/sql/entry.sql @@ -3,7 +3,7 @@ SELECT ROW_NUMBER() OVER(ORDER BY b.id) labelNum, i.`size`, i.category, ink.id color, - o.code origin, + o.code, b.packing, b.`grouping`, i.stems, -- 2.40.1 From 355e426ccf8213b4795e93ed7971d77dc7158c67 Mon Sep 17 00:00:00 2001 From: jgallego Date: Mon, 1 Jul 2024 07:19:00 +0200 Subject: [PATCH 314/413] mail-alias-account con mixin --- modules/account/back/models/mail-alias-account.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/account/back/models/mail-alias-account.json b/modules/account/back/models/mail-alias-account.json index 54e986ef7..46d4793e6 100644 --- a/modules/account/back/models/mail-alias-account.json +++ b/modules/account/back/models/mail-alias-account.json @@ -6,6 +6,9 @@ "table": "account.mailAliasAccount" } }, + "mixins": { + "Loggable": true + }, "properties": { "id": { "type": "number", -- 2.40.1 From 00f3755de74a06fee0e4e38af775e16b59c60413 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 1 Jul 2024 07:46:49 +0200 Subject: [PATCH 315/413] feat: refs #7116 agencyIncoming --- db/versions/10960-silverRoebelini/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql index 264e30791..75fc5277f 100644 --- a/db/versions/10960-silverRoebelini/00-firstScript.sql +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -1,6 +1,6 @@ -- Place your SQL code here CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( - `agencyModeFk` int(11) NOT NULL AUTO_INCREMENT, + `agencyModeFk` int(11) NOT NULL, PRIMARY KEY (`agencyModeFk`) ) ENGINE=InnoDB -- 2.40.1 From 7bf55c68154aeaa4771c12621bae19c75af123b5 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 1 Jul 2024 08:00:27 +0200 Subject: [PATCH 316/413] refs #7644 Added control source --- print/templates/reports/entry-label/entry-label.html | 2 +- print/templates/reports/entry-label/entry-label.js | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/print/templates/reports/entry-label/entry-label.html b/print/templates/reports/entry-label/entry-label.html index 53980c534..65fbfb806 100644 --- a/print/templates/reports/entry-label/entry-label.html +++ b/print/templates/reports/entry-label/entry-label.html @@ -74,7 +74,7 @@
Control - 06 / 11 + {{`${weekNum} / ${dayNum}`}}
diff --git a/print/templates/reports/entry-label/entry-label.js b/print/templates/reports/entry-label/entry-label.js index e3788261a..08d2acc49 100755 --- a/print/templates/reports/entry-label/entry-label.js +++ b/print/templates/reports/entry-label/entry-label.js @@ -1,6 +1,7 @@ const vnReport = require('../../../core/mixins/vn-report.js'); const {DOMImplementation, XMLSerializer} = require('xmldom'); const jsBarcode = require('jsbarcode'); +const moment = require('moment'); module.exports = { name: 'entry-label', @@ -8,6 +9,9 @@ module.exports = { async serverPrefetch() { this.buys = await this.rawSqlFromDef('entry', [this.id]); this.maxLabelNum = Math.max(...this.buys.map(buy => buy.labelNum)); + const date = new Date(); + this.weekNum = moment(date).isoWeek(); + this.dayNum = moment(date).day(); }, methods: { getBarcode(id) { -- 2.40.1 From 5c8d8ba2800d3496956681bc6ebcdc4bf9f628a4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 1 Jul 2024 09:07:36 +0200 Subject: [PATCH 317/413] refs #7644 Added locales and changed name of method --- .../entry/{entryLabel.js => buyLabel.js} | 8 +++---- modules/entry/back/models/entry.js | 2 +- .../assets/css/import.js | 0 .../assets/css/style.css | 0 .../buy-label.html} | 22 +++++++++---------- .../entry-label.js => buy-label/buy-label.js} | 4 ++-- .../templates/reports/buy-label/locale/en.yml | 12 ++++++++++ .../templates/reports/buy-label/locale/es.yml | 12 ++++++++++ .../{entry-label => buy-label}/options.json | 0 .../sql/entry.sql => buy-label/sql/buys.sql} | 0 .../reports/entry-label/locale/es.yml | 1 - 11 files changed, 42 insertions(+), 19 deletions(-) rename modules/entry/back/methods/entry/{entryLabel.js => buyLabel.js} (78%) rename print/templates/reports/{entry-label => buy-label}/assets/css/import.js (100%) rename print/templates/reports/{entry-label => buy-label}/assets/css/style.css (100%) rename print/templates/reports/{entry-label/entry-label.html => buy-label/buy-label.html} (73%) rename print/templates/reports/{entry-label/entry-label.js => buy-label/buy-label.js} (93%) create mode 100644 print/templates/reports/buy-label/locale/en.yml create mode 100644 print/templates/reports/buy-label/locale/es.yml rename print/templates/reports/{entry-label => buy-label}/options.json (100%) rename print/templates/reports/{entry-label/sql/entry.sql => buy-label/sql/buys.sql} (100%) delete mode 100644 print/templates/reports/entry-label/locale/es.yml diff --git a/modules/entry/back/methods/entry/entryLabel.js b/modules/entry/back/methods/entry/buyLabel.js similarity index 78% rename from modules/entry/back/methods/entry/entryLabel.js rename to modules/entry/back/methods/entry/buyLabel.js index 50e82b54c..650b05c97 100644 --- a/modules/entry/back/methods/entry/entryLabel.js +++ b/modules/entry/back/methods/entry/buyLabel.js @@ -1,6 +1,6 @@ module.exports = Self => { - Self.remoteMethodCtx('entryLabel', { - description: 'Returns the entry labels', + Self.remoteMethodCtx('buyLabel', { + description: 'Returns the entry buys labels', accessType: 'READ', accepts: [ { @@ -27,10 +27,10 @@ module.exports = Self => { } ], http: { - path: '/:id/entry-label', + path: '/:id/buy-label', verb: 'GET' } }); - Self.entryLabel = (ctx, id) => Self.printReport(ctx, id, 'entry-label'); + Self.buyLabel = (ctx, id) => Self.printReport(ctx, id, 'buy-label'); }; diff --git a/modules/entry/back/models/entry.js b/modules/entry/back/models/entry.js index 10f63b9f0..6e27e1ece 100644 --- a/modules/entry/back/models/entry.js +++ b/modules/entry/back/models/entry.js @@ -9,7 +9,7 @@ module.exports = Self => { require('../methods/entry/entryOrderPdf')(Self); require('../methods/entry/addFromPackaging')(Self); require('../methods/entry/addFromBuy')(Self); - require('../methods/entry/entryLabel')(Self); + require('../methods/entry/buyLabel')(Self); Self.observe('before save', async function(ctx, options) { if (ctx.isNewInstance) return; diff --git a/print/templates/reports/entry-label/assets/css/import.js b/print/templates/reports/buy-label/assets/css/import.js similarity index 100% rename from print/templates/reports/entry-label/assets/css/import.js rename to print/templates/reports/buy-label/assets/css/import.js diff --git a/print/templates/reports/entry-label/assets/css/style.css b/print/templates/reports/buy-label/assets/css/style.css similarity index 100% rename from print/templates/reports/entry-label/assets/css/style.css rename to print/templates/reports/buy-label/assets/css/style.css diff --git a/print/templates/reports/entry-label/entry-label.html b/print/templates/reports/buy-label/buy-label.html similarity index 73% rename from print/templates/reports/entry-label/entry-label.html rename to print/templates/reports/buy-label/buy-label.html index 65fbfb806..494cdcbc5 100644 --- a/print/templates/reports/entry-label/entry-label.html +++ b/print/templates/reports/buy-label/buy-label.html @@ -5,13 +5,13 @@
- Variedad + {{$t('variety')}} {{buy.name}}
- Medida + {{$t('size')}} {{buy.size}}
@@ -19,19 +19,19 @@
- Categoría + {{$t('category')}} {{buy.category}}
- Color + {{$t('color')}} {{buy.color}}
- Origen + {{$t('origin')}} {{buy.code}}
@@ -39,19 +39,19 @@
- Packing + {{$t('packing')}} {{buy.packing}}
- Grouping + {{$t('grouping')}} {{buy.grouping}}
- Ud. venta + {{$t('saleUnit')}} {{buy.stems}}
@@ -65,7 +65,7 @@
- Productor + {{$t('producer')}} {{buy.producer}}
@@ -73,13 +73,13 @@
- Control + {{$t('control')}} {{`${weekNum} / ${dayNum}`}}
- Caja nº + {{$t('boxNum')}} {{`${buy.labelNum} / ${maxLabelNum}`}}
diff --git a/print/templates/reports/entry-label/entry-label.js b/print/templates/reports/buy-label/buy-label.js similarity index 93% rename from print/templates/reports/entry-label/entry-label.js rename to print/templates/reports/buy-label/buy-label.js index 08d2acc49..b6e0a5031 100755 --- a/print/templates/reports/entry-label/entry-label.js +++ b/print/templates/reports/buy-label/buy-label.js @@ -4,10 +4,10 @@ const jsBarcode = require('jsbarcode'); const moment = require('moment'); module.exports = { - name: 'entry-label', + name: 'buy-label', mixins: [vnReport], async serverPrefetch() { - this.buys = await this.rawSqlFromDef('entry', [this.id]); + this.buys = await this.rawSqlFromDef('buys', [this.id]); this.maxLabelNum = Math.max(...this.buys.map(buy => buy.labelNum)); const date = new Date(); this.weekNum = moment(date).isoWeek(); diff --git a/print/templates/reports/buy-label/locale/en.yml b/print/templates/reports/buy-label/locale/en.yml new file mode 100644 index 000000000..d48d00771 --- /dev/null +++ b/print/templates/reports/buy-label/locale/en.yml @@ -0,0 +1,12 @@ +reportName: Entry buys +variety: Bariety +size: Size +category: Category +color: Color +origin: Origin +packing: Packing +grouping: Grouping +unitSale: Un. sale +producer: Producer +control: Control +boxNum: Box no. \ No newline at end of file diff --git a/print/templates/reports/buy-label/locale/es.yml b/print/templates/reports/buy-label/locale/es.yml new file mode 100644 index 000000000..33a4a499d --- /dev/null +++ b/print/templates/reports/buy-label/locale/es.yml @@ -0,0 +1,12 @@ +reportName: Etiqueta de compras +variety: Variedad +size: Medida +category: Categoría +color: Color +origin: Origen +packing: Packing +grouping: Grouping +saleUnit: Sale un. +producer: Productor +control: Control +boxNum: Caja nº \ No newline at end of file diff --git a/print/templates/reports/entry-label/options.json b/print/templates/reports/buy-label/options.json similarity index 100% rename from print/templates/reports/entry-label/options.json rename to print/templates/reports/buy-label/options.json diff --git a/print/templates/reports/entry-label/sql/entry.sql b/print/templates/reports/buy-label/sql/buys.sql similarity index 100% rename from print/templates/reports/entry-label/sql/entry.sql rename to print/templates/reports/buy-label/sql/buys.sql diff --git a/print/templates/reports/entry-label/locale/es.yml b/print/templates/reports/entry-label/locale/es.yml deleted file mode 100644 index 278946f3e..000000000 --- a/print/templates/reports/entry-label/locale/es.yml +++ /dev/null @@ -1 +0,0 @@ -reportName: Etiqueta \ No newline at end of file -- 2.40.1 From 3ad23465042d1476ce47f97c403a7752a489640e Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 1 Jul 2024 09:25:00 +0200 Subject: [PATCH 318/413] feat refactor setParking REGEXP refs #7575 --- db/routines/vn/procedures/setParking.sql | 66 ++++++++++++------------ 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/db/routines/vn/procedures/setParking.sql b/db/routines/vn/procedures/setParking.sql index 97a40bbe0..d6def07de 100644 --- a/db/routines/vn/procedures/setParking.sql +++ b/db/routines/vn/procedures/setParking.sql @@ -22,40 +22,42 @@ proc: BEGIN CALL util.throw('parkingNotExist'); LEAVE proc; END IF; + + IF vParam REGEXP '^[0-9]+$' THEN + -- Se comprueba si es una preparación previa + SELECT COUNT(*) INTO vIsSaleGroup + FROM vn.saleGroup sg + WHERE sg.id = vParam; - -- Se comprueba si es una preparación previa - SELECT COUNT(*) INTO vIsSaleGroup - FROM vn.saleGroup sg - WHERE sg.id = vParam; + IF vIsSaleGroup THEN + CALL vn.saleGroup_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; - IF vIsSaleGroup THEN - CALL vn.saleGroup_setParking(vParam, vParkingFk); - LEAVE proc; + -- Se comprueba si es un ticket + SELECT COUNT(*) INTO vIsTicket + FROM vn.ticket t + WHERE t.id = vParam + AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + + IF vIsTicket THEN + CALL vn.ticket_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; + + -- Se comprueba si es una coleccion de tickets + SELECT COUNT(*) INTO vIsCollection + FROM vn.collection c + WHERE c.id = vParam + AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + + IF vIsCollection THEN + CALL vn.collection_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; + ELSE + -- Por descarte, se considera una matrícula + CALL vn.shelving_setParking(vParam, vParkingFk); END IF; - - -- Se comprueba si es un ticket - SELECT COUNT(*) INTO vIsTicket - FROM vn.ticket t - WHERE t.id = vParam - AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsTicket THEN - CALL vn.ticket_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Se comprueba si es una coleccion de tickets - SELECT COUNT(*) INTO vIsCollection - FROM vn.collection c - WHERE c.id = vParam - AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsCollection THEN - CALL vn.collection_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Por descarte, se considera una matrícula - CALL vn.shelving_setParking(vParam, vParkingFk); END$$ DELIMITER ; -- 2.40.1 From 2bf06d8add02bb222600727bd92ea8da0aac0045 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 1 Jul 2024 10:06:34 +0200 Subject: [PATCH 319/413] fix: refs #7552 Hotfix --- db/routines/vn/procedures/item_getSimilar.sql | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 762c25342..86791b926 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -15,11 +15,13 @@ BEGIN * @param vDated Fecha * @param vShowType Mostrar tipos */ - DECLARE vCalcFk INT; + DECLARE vAvailableCalcFk INT; + DECLARE vVisibleCalcFk INT; DECLARE vTypeFk INT; DECLARE vPriority INT DEFAULT 1; - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); + CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); + CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); -- Añadido temporalmente para que no se cuelgue la db SET vShowType = TRUE; @@ -65,21 +67,21 @@ BEGIN WHEN b.groupingMode = 'packing' THEN b.packing ELSE 1 END AS minQuantity, - iss.visible located, + v.visible located, b.price2 FROM vn.item i JOIN cache.available a ON a.item_id = i.id - AND a.calc_id = vCalcFk + AND a.calc_id = vAvailableCalcFk + LEFT JOIN cache.visible v ON v.item_id = i.id + AND v.calc_id = vVisibleCalcFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf LEFT JOIN vn.itemTag it ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.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 vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id - AND iss.warehouseFk = vWarehouseFk JOIN itemTags its WHERE a.available > 0 AND (i.typeFk = its.typeFk OR NOT vShowType) -- 2.40.1 From 8409ffa95064a8e131788350f985ce4a6bf4801b Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 1 Jul 2024 10:26:46 +0200 Subject: [PATCH 320/413] fix: refs #7552 Hotfix --- db/routines/vn/procedures/item_getSimilar.sql | 3 --- 1 file changed, 3 deletions(-) diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 86791b926..557d77bdf 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -23,9 +23,6 @@ BEGIN CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); - -- Añadido temporalmente para que no se cuelgue la db - SET vShowType = TRUE; - WITH itemTags AS ( SELECT i.id, typeFk, -- 2.40.1 From a23f485296c594c23779a8879ba9cc3e1b4a781e Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 1 Jul 2024 11:11:16 +0200 Subject: [PATCH 321/413] refactor: refs #7424 Component type refactor --- db/routines/bi/procedures/rutasAnalyze.sql | 2 +- .../bi/views/tarifa_componentes_series.sql | 2 +- db/routines/vn/procedures/sale_PriceFix.sql | 2 +- .../procedures/ticket_checkNoComponents.sql | 3 +- .../procedures/ticket_getFromFloramondo.sql | 4 +- db/routines/vn/views/saleCost.sql | 2 +- .../vn/views/sale_freightComponent.sql | 2 +- .../11119-tealGerbera/00-firstScript.sql | 9 ++ .../ticket/back/models/component-type.json | 2 +- modules/ticket/front/component/index.html | 2 +- modules/ticket/front/component/index.js | 2 +- .../reports/delivery-note/sql/sales.sql | 85 +++++++++---------- 12 files changed, 63 insertions(+), 54 deletions(-) create mode 100644 db/versions/11119-tealGerbera/00-firstScript.sql diff --git a/db/routines/bi/procedures/rutasAnalyze.sql b/db/routines/bi/procedures/rutasAnalyze.sql index 5f0d55c7a..e277968bf 100644 --- a/db/routines/bi/procedures/rutasAnalyze.sql +++ b/db/routines/bi/procedures/rutasAnalyze.sql @@ -59,7 +59,7 @@ BEGIN JOIN vn.saleComponent sc ON sc.saleFk = s.id JOIN vn.component c ON c.id = sc.componentFk JOIN vn.componentType ct ON ct.id = c.typeFk - WHERE ct.code = 'FREIGHT' + WHERE ct.code = 'freight' AND r.created BETWEEN vDatedFrom AND vDatedTo GROUP BY r.id ) sub ON sub.routeFk = r.Id_Ruta diff --git a/db/routines/bi/views/tarifa_componentes_series.sql b/db/routines/bi/views/tarifa_componentes_series.sql index f231ae420..ed2f8e29a 100644 --- a/db/routines/bi/views/tarifa_componentes_series.sql +++ b/db/routines/bi/views/tarifa_componentes_series.sql @@ -2,7 +2,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `bi`.`tarifa_componentes_series` AS SELECT `ct`.`id` AS `tarifa_componentes_series_id`, - `ct`.`type` AS `Serie`, + `ct`.`name` AS `Serie`, `ct`.`isBase` AS `base`, `ct`.`isMargin` AS `margen` FROM `vn`.`componentType` `ct` diff --git a/db/routines/vn/procedures/sale_PriceFix.sql b/db/routines/vn/procedures/sale_PriceFix.sql index 8ffa77070..5f956cba8 100644 --- a/db/routines/vn/procedures/sale_PriceFix.sql +++ b/db/routines/vn/procedures/sale_PriceFix.sql @@ -8,7 +8,7 @@ BEGIN JOIN vn.component c ON c.id = sc.componentFk JOIN vn.componentType ct ON ct.id = c.typeFk WHERE s.ticketFk = vTicketFk - AND ct.`type` = 'otros'; + AND ct.code = 'other'; UPDATE vn.sale s JOIN ( diff --git a/db/routines/vn/procedures/ticket_checkNoComponents.sql b/db/routines/vn/procedures/ticket_checkNoComponents.sql index 28fe333f0..b03427192 100644 --- a/db/routines/vn/procedures/ticket_checkNoComponents.sql +++ b/db/routines/vn/procedures/ticket_checkNoComponents.sql @@ -20,7 +20,8 @@ BEGIN 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 = 1 + JOIN componentType ct ON ct.id = c.typeFk + AND ct.code = 'cost' WHERE t.shipped BETWEEN vShippedFrom AND vShippedTo AND ic.merchandise; diff --git a/db/routines/vn/procedures/ticket_getFromFloramondo.sql b/db/routines/vn/procedures/ticket_getFromFloramondo.sql index 4d83d6dda..5f2bedbb1 100644 --- a/db/routines/vn/procedures/ticket_getFromFloramondo.sql +++ b/db/routines/vn/procedures/ticket_getFromFloramondo.sql @@ -66,7 +66,7 @@ BEGIN JOIN vn.componentType ct ON ct.id = c.typeFk JOIN vn.sale s ON s.id = sc.saleFk JOIN tmp.ticket t ON t.ticketFk = s.ticketFk - WHERE ct.code = 'FREIGHT' + WHERE ct.code = 'freight' GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk SET tf.freight = sb.freight; @@ -88,7 +88,7 @@ BEGIN -- Margin UPDATE tmp.ticketFloramondo tf - JOIN (SELECT SUM(IF(ct.code = 'COST',sc.value, 0)) cost, + JOIN (SELECT SUM(IF(ct.code = 'cost',sc.value, 0)) cost, SUM(IF(ct.isMargin, sc.value, 0)) margin, t.ticketFk FROM vn.saleComponent sc diff --git a/db/routines/vn/views/saleCost.sql b/db/routines/vn/views/saleCost.sql index 27265aa93..304b9e3a3 100644 --- a/db/routines/vn/views/saleCost.sql +++ b/db/routines/vn/views/saleCost.sql @@ -19,4 +19,4 @@ FROM ( ) JOIN `vn`.`componentType` `ct` ON(`ct`.`id` = `c`.`typeFk`) ) -WHERE `ct`.`type` = 'coste' +WHERE `ct`.`code` = 'cost' diff --git a/db/routines/vn/views/sale_freightComponent.sql b/db/routines/vn/views/sale_freightComponent.sql index 7a329e0ee..269a8cca1 100644 --- a/db/routines/vn/views/sale_freightComponent.sql +++ b/db/routines/vn/views/sale_freightComponent.sql @@ -16,6 +16,6 @@ FROM ( ) JOIN `vn`.`componentType` `ct` ON( `ct`.`id` = `c`.`typeFk` - AND `ct`.`type` = 'agencia' + AND `ct`.`code` = 'freight' ) ) diff --git a/db/versions/11119-tealGerbera/00-firstScript.sql b/db/versions/11119-tealGerbera/00-firstScript.sql new file mode 100644 index 000000000..40b3b0424 --- /dev/null +++ b/db/versions/11119-tealGerbera/00-firstScript.sql @@ -0,0 +1,9 @@ +ALTER TABLE vn.componentType + CHANGE code code varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL AFTER id; +ALTER TABLE vn.componentType + CHANGE `type` name varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL; +UPDATE IGNORE vn.componentType + SET code = LOWER(code); +UPDATE IGNORE vn.componentType + SET code = 'other' + WHERE id = 12; \ No newline at end of file diff --git a/modules/ticket/back/models/component-type.json b/modules/ticket/back/models/component-type.json index 26daf5216..735227a35 100644 --- a/modules/ticket/back/models/component-type.json +++ b/modules/ticket/back/models/component-type.json @@ -12,7 +12,7 @@ "type": "number", "description": "Identifier" }, - "type": { + "name": { "type": "string" }, "isBase":{ diff --git a/modules/ticket/front/component/index.html b/modules/ticket/front/component/index.html index 39b54b461..2a3a80f3e 100644 --- a/modules/ticket/front/component/index.html +++ b/modules/ticket/front/component/index.html @@ -51,7 +51,7 @@ ng-repeat="saleComponent in sale.components track by saleComponent.componentFk" class="components"> - {{::saleComponent.component.componentType.type}} + {{::saleComponent.component.componentType.name}} {{::saleComponent.component.name}} diff --git a/modules/ticket/front/component/index.js b/modules/ticket/front/component/index.js index 3f262f457..aa755e808 100644 --- a/modules/ticket/front/component/index.js +++ b/modules/ticket/front/component/index.js @@ -20,7 +20,7 @@ class Controller extends Section { include: { relation: 'componentType', scope: { - fields: ['type', 'isBase'] + fields: ['name', 'isBase'] } } } diff --git a/print/templates/reports/delivery-note/sql/sales.sql b/print/templates/reports/delivery-note/sql/sales.sql index c449030cf..636bbc228 100644 --- a/print/templates/reports/delivery-note/sql/sales.sql +++ b/print/templates/reports/delivery-note/sql/sales.sql @@ -1,43 +1,42 @@ -SELECT - s.id, - s.itemFk, - s.concept, - s.quantity, - s.price, - s.price - SUM(IF(ctr.id = 6, sc.value, 0)) netPrice, - s.discount, - i.size, - i.stems, - i.category, - it.id itemTypeId, - o.code AS origin, - i.inkFk, - s.ticketFk, - tcl.code vatType, - ib.ediBotanic botanical, - i.tag5, - i.value5, - i.tag6, - i.value6, - i.tag7, - i.value7 -FROM vn.sale s - LEFT JOIN saleComponent sc ON sc.saleFk = s.id - LEFT JOIN component cr ON cr.id = sc.componentFk - LEFT JOIN componentType ctr ON ctr.id = cr.typeFk - LEFT JOIN item i ON i.id = s.itemFk - LEFT JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN country c ON c.id = o.countryFk - LEFT JOIN supplier sp ON sp.id = t.companyFk - LEFT JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id - AND itc.countryFk = sp.countryFk - LEFT JOIN taxClass tcl ON tcl.id = itc.taxClassFk - LEFT JOIN itemBotanicalWithGenus ib ON ib.itemFk = i.id - AND ic.code = 'plant' - AND ib.ediBotanic IS NOT NULL -WHERE s.ticketFk = ? -GROUP BY s.id -ORDER BY (it.isPackaging), s.concept, s.itemFk \ No newline at end of file +SELECT s.id, + s.itemFk, + s.concept, + s.quantity, + s.price, + s.price - SUM(IF(ctr.code = 'freight', sc.value, 0)) netPrice, + s.discount, + i.size, + i.stems, + i.category, + it.id itemTypeId, + o.code origin, + i.inkFk, + s.ticketFk, + tcl.code vatType, + ib.ediBotanic botanical, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7 + FROM vn.sale s + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN component cr ON cr.id = sc.componentFk + LEFT JOIN componentType ctr ON ctr.id = cr.typeFk + LEFT JOIN item i ON i.id = s.itemFk + LEFT JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN country c ON c.id = o.countryFk + LEFT JOIN supplier sp ON sp.id = t.companyFk + LEFT JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN itemTaxCountry itc ON itc.itemFk = i.id + AND itc.countryFk = sp.countryFk + LEFT JOIN taxClass tcl ON tcl.id = itc.taxClassFk + LEFT JOIN itemBotanicalWithGenus ib ON ib.itemFk = i.id + AND ic.code = 'plant' + AND ib.ediBotanic IS NOT NULL + WHERE s.ticketFk = ? + GROUP BY s.id + ORDER BY (it.isPackaging), s.concept, s.itemFk \ No newline at end of file -- 2.40.1 From 0240734a4b99c4003ce909e7aeba121e2c062b8f Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 1 Jul 2024 11:50:37 +0200 Subject: [PATCH 322/413] refs #6897 fix filter --- modules/entry/back/methods/entry/filter.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 1cd12b737..f3f14e7c1 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -173,7 +173,8 @@ module.exports = Self => { s.name AS supplierName, s.nickname AS supplierAlias, co.code AS companyCode, - cu.code AS currencyCode + cu.code AS currencyCode, + t.ref AS travelRef FROM vn.entry e JOIN vn.supplier s ON s.id = e.supplierFk JOIN vn.travel t ON t.id = e.travelFk -- 2.40.1 From 9e5f416d55bc2b159c99c33498da8ed0d33b0967 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 1 Jul 2024 12:06:30 +0200 Subject: [PATCH 323/413] refactor: refs #7418 Item type refactor --- db/dump/fixtures.before.sql | 1 - db/routines/vn2008/views/Tipos.sql | 7 +------ db/versions/11120-brownTulip/00-firstScript.sql | 6 ++++++ 3 files changed, 7 insertions(+), 7 deletions(-) create mode 100644 db/versions/11120-brownTulip/00-firstScript.sql diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 27f84bdfb..61d46d133 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3232,7 +3232,6 @@ INSERT IGNORE INTO vn.itemType workerFk = 103, isInventory = TRUE, life = 10, - density = 250, itemPackingTypeFk = NULL, temperatureFk = 'warm'; diff --git a/db/routines/vn2008/views/Tipos.sql b/db/routines/vn2008/views/Tipos.sql index 4cde954f1..5b96c1766 100644 --- a/db/routines/vn2008/views/Tipos.sql +++ b/db/routines/vn2008/views/Tipos.sql @@ -9,14 +9,9 @@ AS SELECT `it`.`id` AS `tipo_id`, `it`.`workerFk` AS `Id_Trabajador`, `it`.`life` AS `life`, `it`.`isPackaging` AS `isPackaging`, - `it`.`density` AS `density`, `it`.`isInventory` AS `inventory`, `it`.`created` AS `odbc_date`, `it`.`making` AS `confeccion`, `it`.`temperatureFk` AS `Temperatura`, - `it`.`promo` AS `promo`, - `it`.`maneuver` AS `maneuver`, - `it`.`target` AS `target`, - `it`.`topMargin` AS `top_margin`, - `it`.`profit` AS `profit` + `it`.`promo` AS `promo` FROM `vn`.`itemType` `it` diff --git a/db/versions/11120-brownTulip/00-firstScript.sql b/db/versions/11120-brownTulip/00-firstScript.sql new file mode 100644 index 000000000..c4ded80bb --- /dev/null +++ b/db/versions/11120-brownTulip/00-firstScript.sql @@ -0,0 +1,6 @@ +ALTER TABLE vn.itemType + CHANGE maneuver maneuver__ double DEFAULT 0.21 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE target target__ double DEFAULT 0.15 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE topMargin topMargin__ double DEFAULT 0.3 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE profit profit__ double DEFAULT 0.02 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE density density__ double DEFAULT 167 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418 Almacena el valor por defecto de la densidad en kg/m3 para el calculo de los portes aereos, en articulos se guarda la correcta'; \ No newline at end of file -- 2.40.1 From 2ed31ee1d3702df9a7e3f31571b91f50f13e2b9e Mon Sep 17 00:00:00 2001 From: ivanm Date: Mon, 1 Jul 2024 13:26:59 +0200 Subject: [PATCH 324/413] refs #7651 Add editorFk and triggers --- .../account/triggers/mailAliasAccount_beforeInsert.sql | 8 ++++++++ .../account/triggers/mailAliasAccount_beforeUpdate.sql | 8 ++++++++ db/versions/11121-silverAralia/00-firstScript.sql | 4 ++++ 3 files changed, 20 insertions(+) create mode 100644 db/routines/account/triggers/mailAliasAccount_beforeInsert.sql create mode 100644 db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql create mode 100644 db/versions/11121-silverAralia/00-firstScript.sql diff --git a/db/routines/account/triggers/mailAliasAccount_beforeInsert.sql b/db/routines/account/triggers/mailAliasAccount_beforeInsert.sql new file mode 100644 index 000000000..a435832f2 --- /dev/null +++ b/db/routines/account/triggers/mailAliasAccount_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_beforeInsert` + BEFORE INSERT ON `mailAliasAccount` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql b/db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql new file mode 100644 index 000000000..471a34900 --- /dev/null +++ b/db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_beforeUpdate` + BEFORE UPDATE ON `mailAliasAccount` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/versions/11121-silverAralia/00-firstScript.sql b/db/versions/11121-silverAralia/00-firstScript.sql new file mode 100644 index 000000000..e74ca2e95 --- /dev/null +++ b/db/versions/11121-silverAralia/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE account.mailAliasAccount + ADD editorFk INT UNSIGNED NULL, + ADD CONSTRAINT mailAliasAccount_editorFk FOREIGN KEY (editorFk) + REFERENCES account.`user`(id); \ No newline at end of file -- 2.40.1 From a0ea742f9e523a9fec3ef12304a9399ec28840fa Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 1 Jul 2024 13:38:25 +0200 Subject: [PATCH 325/413] fix: refs #7486 Hotfix --- db/routines/vn/procedures/ticket_splitItemPackingType.sql | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index b28b16432..d6e8e8a53 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -44,7 +44,6 @@ BEGIN WHERE s.ticketFk = vTicketFk; CREATE OR REPLACE TEMPORARY TABLE tmp.saleGroup - (PRIMARY KEY (itemPackingTypeFk)) ENGINE = MEMORY SELECT itemPackingTypeFk, SUM(litros) totalLitros FROM tmp.sale @@ -56,8 +55,7 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT ( ticketFk INT, - itemPackingTypeFk VARCHAR(1), - PRIMARY KEY (ticketFk) + itemPackingTypeFk VARCHAR(1) ) ENGINE = MEMORY; CASE vPackingTypesToSplit -- 2.40.1 From f47197cd8085bb9a762fb98998bd3f8c6b2f3ca6 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 1 Jul 2024 14:06:28 +0200 Subject: [PATCH 326/413] Merge branch '7648_customerEntries' into 7648_dev_customerEntries --- .../11118-limeCymbidium/00-firstScript.sql | 10 ++++++ modules/entry/back/methods/entry/buyLabel.js | 3 +- modules/entry/back/methods/entry/filter.js | 8 +++-- modules/entry/back/methods/entry/getBuys.js | 34 +++++++++++++++---- .../back/methods/entry/specs/filter.spec.js | 18 ++++++---- .../back/methods/entry/specs/getBuys.spec.js | 9 ++++- .../back/methods/supplier/isSupplier.js | 28 +++++++++++++++ modules/supplier/back/models/supplier.js | 1 + 8 files changed, 95 insertions(+), 16 deletions(-) create mode 100644 db/versions/11118-limeCymbidium/00-firstScript.sql create mode 100644 modules/supplier/back/methods/supplier/isSupplier.js diff --git a/db/versions/11118-limeCymbidium/00-firstScript.sql b/db/versions/11118-limeCymbidium/00-firstScript.sql new file mode 100644 index 000000000..52ab2acbd --- /dev/null +++ b/db/versions/11118-limeCymbidium/00-firstScript.sql @@ -0,0 +1,10 @@ +-- Place your SQL code here +-- Auto-generated SQL script #202406281423 +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Entry','filter','READ','ALLOW','ROLE','$authenticated'); + +-- Auto-generated SQL script #202406281452 +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Entry','getBuys','READ','ALLOW','ROLE','$authenticated'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Entry','buyLabel','READ','ALLOW','ROLE','$authenticated'); diff --git a/modules/entry/back/methods/entry/buyLabel.js b/modules/entry/back/methods/entry/buyLabel.js index 650b05c97..d9b0ebf1d 100644 --- a/modules/entry/back/methods/entry/buyLabel.js +++ b/modules/entry/back/methods/entry/buyLabel.js @@ -29,7 +29,8 @@ module.exports = Self => { http: { path: '/:id/buy-label', verb: 'GET' - } + }, + accessScopes: ['DEFAULT', 'read:multimedia'] }); Self.buyLabel = (ctx, id) => Self.printReport(ctx, id, 'buy-label'); diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 1cd12b737..7d287b842 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -112,7 +112,7 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - + const isSupplier = await Self.app.models.Supplier.isSupplier(ctx, options); const conn = Self.dataSource.connector; const where = buildFilter(ctx.args, (param, value) => { switch (param) { @@ -146,7 +146,11 @@ module.exports = Self => { } }); filter = mergeFilters(ctx.args.filter, {where}); - + delete filter.order; + if (isSupplier) { + if (!filter.where) filter.where = {}; + filter.where.supplierFk = ctx.req.accessToken.userId; + } const stmts = []; let stmt; stmt = new ParameterizedSQL( diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index 0ed77e8d1..cfb065b83 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -1,7 +1,10 @@ +const ForbiddenError = require('vn-loopback/util/forbiddenError'); +const UserError = require('vn-loopback/util/user-error'); + const mergeFilters = require('vn-loopback/util/filter').mergeFilters; module.exports = Self => { - Self.remoteMethod('getBuys', { + Self.remoteMethodCtx('getBuys', { description: 'Returns buys for one entry', accessType: 'READ', accepts: [{ @@ -27,13 +30,18 @@ module.exports = Self => { } }); - Self.getBuys = async(id, filter, options) => { + Self.getBuys = async(ctx, id, filter, options) => { const models = Self.app.models; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); + const isSupplier = await Self.app.models.Supplier.isSupplier(ctx, options); + if (isSupplier) { + const isEntryOwner = (await Self.findById(id)).supplierFk === ctx.req.accessToken.userId; + if (! isEntryOwner) throw new UserError('Access Denied'); + } let defaultFilter = { where: {entryFk: id}, fields: [ @@ -49,9 +57,23 @@ module.exports = Self => { 'buyingValue', 'price2', 'price3', - 'printedStickers' + 'printedStickers', + 'entryFk' ], - include: { + include: [{ + relation: 'entry', + scope: { + fields: [ + 'id', 'supplierFk' + ], + include: { + relation: 'supplier', scope: { + fields: ['id'] + } + } + } + }, + { relation: 'item', scope: { fields: [ @@ -82,9 +104,9 @@ module.exports = Self => { } } } - } + }] }; - + delete filter.order; defaultFilter = mergeFilters(defaultFilter, filter); return models.Buy.find(defaultFilter, myOptions); diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index 28763bc81..e116d1c5f 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -9,7 +9,8 @@ describe('Entry filter()', () => { const ctx = { args: { search: 1 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); @@ -32,7 +33,8 @@ describe('Entry filter()', () => { const ctx = { args: { currencyFk: 1 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); @@ -54,7 +56,8 @@ describe('Entry filter()', () => { const ctx = { args: { supplierFk: 2 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); @@ -76,7 +79,8 @@ describe('Entry filter()', () => { const ctx = { args: { companyFk: 442 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); @@ -98,7 +102,8 @@ describe('Entry filter()', () => { const ctx = { args: { isBooked: true, - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); @@ -121,7 +126,8 @@ describe('Entry filter()', () => { args: { reference: 'movement', travelFk: '2' - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); diff --git a/modules/entry/back/methods/entry/specs/getBuys.spec.js b/modules/entry/back/methods/entry/specs/getBuys.spec.js index cf4462e48..44b2ff5bc 100644 --- a/modules/entry/back/methods/entry/specs/getBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/getBuys.spec.js @@ -7,7 +7,14 @@ describe('entry getBuys()', () => { const options = {transaction: tx}; try { - const result = await models.Entry.getBuys(entryId, options); + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 2}} + }; + + const result = await models.Entry.getBuys(ctx, entryId, options); const length = result.length; const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; diff --git a/modules/supplier/back/methods/supplier/isSupplier.js b/modules/supplier/back/methods/supplier/isSupplier.js new file mode 100644 index 000000000..d13f304a8 --- /dev/null +++ b/modules/supplier/back/methods/supplier/isSupplier.js @@ -0,0 +1,28 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('isSupplier', { + description: 'Check is supplierFk exists as supplier', + accessType: 'READ', + returns: { + type: 'boolean', + root: true + }, + http: { + path: `/isSupplier`, + verb: 'GET' + } + }); + + Self.isSupplier = async(ctx, options) => { + const myOptions = {validate: false}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const userId = ctx.req.accessToken.userId; + const exists = await Self.findById(userId); + + return !!exists; + }; +}; diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 2d3ffef3e..6094602b6 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -12,6 +12,7 @@ module.exports = Self => { require('../methods/supplier/campaignMetricsEmail')(Self); require('../methods/supplier/newSupplier')(Self); require('../methods/supplier/getItemsPackaging')(Self); + require('../methods/supplier/isSupplier')(Self); Self.validatesPresenceOf('name', { message: 'The social name cannot be empty' -- 2.40.1 From f0326860baaac84570a1e261cb1738860760bf4a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 1 Jul 2024 14:07:46 +0200 Subject: [PATCH 327/413] feat(salix): refs #7648 #7648 add new fields --- modules/entry/back/methods/entry/filter.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 7d287b842..929df8bd9 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -177,10 +177,15 @@ module.exports = Self => { s.name AS supplierName, s.nickname AS supplierAlias, co.code AS companyCode, - cu.code AS currencyCode + cu.code AS currencyCode, + t.shipped AS shipped, + t.landed AS landed, + t.warehouseInFk AS warehouseId, + w.name AS warehouseName FROM vn.entry e JOIN vn.supplier s ON s.id = e.supplierFk JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk JOIN vn.company co ON co.id = e.companyFk JOIN vn.currency cu ON cu.id = e.currencyFk` ); -- 2.40.1 From 29aecd62a527c203430e0b84ad3ffe466d4bff9f Mon Sep 17 00:00:00 2001 From: ivanm Date: Mon, 1 Jul 2024 14:51:32 +0200 Subject: [PATCH 328/413] refs #7651 add afterDelete trigger --- .../triggers/mailAliasAccount_afterDelete.sql | 12 ++++++++++++ db/versions/11121-silverAralia/00-firstScript.sql | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 db/routines/account/triggers/mailAliasAccount_afterDelete.sql diff --git a/db/routines/account/triggers/mailAliasAccount_afterDelete.sql b/db/routines/account/triggers/mailAliasAccount_afterDelete.sql new file mode 100644 index 000000000..83af7169c --- /dev/null +++ b/db/routines/account/triggers/mailAliasAccount_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_afterDelete` + AFTER DELETE ON `mailAliasAccount` + FOR EACH ROW +BEGIN + INSERT INTO userLog + SET `action` = 'delete', + `changedModel` = 'MailAliasAccount', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/versions/11121-silverAralia/00-firstScript.sql b/db/versions/11121-silverAralia/00-firstScript.sql index e74ca2e95..20b0e8195 100644 --- a/db/versions/11121-silverAralia/00-firstScript.sql +++ b/db/versions/11121-silverAralia/00-firstScript.sql @@ -1,4 +1,4 @@ ALTER TABLE account.mailAliasAccount - ADD editorFk INT UNSIGNED NULL, + ADD editorFk INT(10) UNSIGNED DEFAULT NULL, ADD CONSTRAINT mailAliasAccount_editorFk FOREIGN KEY (editorFk) REFERENCES account.`user`(id); \ No newline at end of file -- 2.40.1 From d9742afc9b4fdaaf143fe91c227527e684d3c931 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Mon, 1 Jul 2024 17:45:45 +0200 Subject: [PATCH 329/413] feat roadmap refs #7195 --- modules/route/back/models/roadmapStop.json | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/route/back/models/roadmapStop.json b/modules/route/back/models/roadmapStop.json index 74b02cd7a..93eae0113 100644 --- a/modules/route/back/models/roadmapStop.json +++ b/modules/route/back/models/roadmapStop.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "roadmapStop" + "table": "roadmapStop" } }, "properties": { @@ -28,16 +28,16 @@ "type": "number" } }, - "relations": { - "roadmap": { + "relations": { + "roadmap": { "type": "belongsTo", "model": "Roadmap", "foreignKey": "roadmapFk" }, "address": { "type": "belongsTo", - "model": "Address", + "model": "RoadmapAddress", "foreignKey": "addressFk" } - } -} + } +} \ No newline at end of file -- 2.40.1 From a0185dca0486a339ba41ab8822ff4e767e19be1b Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 1 Jul 2024 18:39:21 +0200 Subject: [PATCH 330/413] feat(salix): refs #7648 #7648 new supplier role --- .../11118-limeCymbidium/00-firstScript.sql | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/db/versions/11118-limeCymbidium/00-firstScript.sql b/db/versions/11118-limeCymbidium/00-firstScript.sql index 52ab2acbd..7f9a2432d 100644 --- a/db/versions/11118-limeCymbidium/00-firstScript.sql +++ b/db/versions/11118-limeCymbidium/00-firstScript.sql @@ -1,10 +1,15 @@ --- Place your SQL code here --- Auto-generated SQL script #202406281423 -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) - VALUES ('Entry','filter','READ','ALLOW','ROLE','$authenticated'); --- Auto-generated SQL script #202406281452 -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) +INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) + VALUES ('Entry','filter','READ','ALLOW','ROLE','supplier'); + +INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) VALUES ('Entry','getBuys','READ','ALLOW','ROLE','$authenticated'); -INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + +INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) VALUES ('Entry','buyLabel','READ','ALLOW','ROLE','$authenticated'); + +INSERT IGNORE INTO `account`.`role` (`name`,`description`,`hasLogin`,`created`,`modified`) + VALUES ('supplier','Proveedores',1,'2017-10-10 14:58:58.000','2017-10-10 14:59:20.000'); +SET @supplierFk =LAST_INSERT_ID(); +INSERT IGNORE INTO account.roleInherit (`role`,`inheritsFrom`) + VALUES (@supplierFk,2); -- 2.40.1 From f27bdec75822835be3db77ff496f686d524a826d Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 1 Jul 2024 21:14:27 +0200 Subject: [PATCH 331/413] feat(salix): refs #7648 #7648 changes requested --- .../11118-limeCymbidium/00-firstScript.sql | 9 ++++-- loopback/common/methods/schema/model-info.js | 1 + modules/entry/back/methods/entry/filter.js | 4 +-- modules/entry/back/methods/entry/getBuys.js | 8 +++--- .../back/methods/supplier/isSupplier.js | 28 ------------------- modules/supplier/back/models/supplier.js | 1 - 6 files changed, 14 insertions(+), 37 deletions(-) delete mode 100644 modules/supplier/back/methods/supplier/isSupplier.js diff --git a/db/versions/11118-limeCymbidium/00-firstScript.sql b/db/versions/11118-limeCymbidium/00-firstScript.sql index 7f9a2432d..0ed1337a0 100644 --- a/db/versions/11118-limeCymbidium/00-firstScript.sql +++ b/db/versions/11118-limeCymbidium/00-firstScript.sql @@ -3,13 +3,18 @@ INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`prin VALUES ('Entry','filter','READ','ALLOW','ROLE','supplier'); INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) - VALUES ('Entry','getBuys','READ','ALLOW','ROLE','$authenticated'); + VALUES ('Entry','getBuys','READ','ALLOW','ROLE','supplier'); INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) - VALUES ('Entry','buyLabel','READ','ALLOW','ROLE','$authenticated'); + VALUES ('Entry','buyLabel','READ','ALLOW','ROLE','supplier'); INSERT IGNORE INTO `account`.`role` (`name`,`description`,`hasLogin`,`created`,`modified`) VALUES ('supplier','Proveedores',1,'2017-10-10 14:58:58.000','2017-10-10 14:59:20.000'); SET @supplierFk =LAST_INSERT_ID(); INSERT IGNORE INTO account.roleInherit (`role`,`inheritsFrom`) VALUES (@supplierFk,2); + +UPDATE salix.ACL + SET principalId='$authenticated' + WHERE id=264; + diff --git a/loopback/common/methods/schema/model-info.js b/loopback/common/methods/schema/model-info.js index 0648deb80..74d764475 100644 --- a/loopback/common/methods/schema/model-info.js +++ b/loopback/common/methods/schema/model-info.js @@ -92,6 +92,7 @@ module.exports = Self => { const locale = modelLocale && modelLocale.get(lang); json[modelName] = { + http: model.sharedClass.http.path, properties: model.definition.rawProperties, validations: jsonValidations, locale diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 929df8bd9..2a127b496 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -112,7 +112,6 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const isSupplier = await Self.app.models.Supplier.isSupplier(ctx, options); const conn = Self.dataSource.connector; const where = buildFilter(ctx.args, (param, value) => { switch (param) { @@ -146,7 +145,8 @@ module.exports = Self => { } }); filter = mergeFilters(ctx.args.filter, {where}); - delete filter.order; + const userId = ctx.req.accessToken.userId; + const isSupplier = await Self.app.models.Supplier.findById(userId, options); if (isSupplier) { if (!filter.where) filter.where = {}; filter.where.supplierFk = ctx.req.accessToken.userId; diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index cfb065b83..e392ba3ce 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -31,16 +31,17 @@ module.exports = Self => { }); Self.getBuys = async(ctx, id, filter, options) => { + const userId = ctx.req.accessToken.userId; const models = Self.app.models; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - const isSupplier = await Self.app.models.Supplier.isSupplier(ctx, options); + const isSupplier = await Self.app.models.Supplier.findById(userId, options); if (isSupplier) { - const isEntryOwner = (await Self.findById(id)).supplierFk === ctx.req.accessToken.userId; + const isEntryOwner = (await Self.findById(id)).supplierFk === userId; - if (! isEntryOwner) throw new UserError('Access Denied'); + if (!isEntryOwner) throw new UserError('Access Denied'); } let defaultFilter = { where: {entryFk: id}, @@ -106,7 +107,6 @@ module.exports = Self => { } }] }; - delete filter.order; defaultFilter = mergeFilters(defaultFilter, filter); return models.Buy.find(defaultFilter, myOptions); diff --git a/modules/supplier/back/methods/supplier/isSupplier.js b/modules/supplier/back/methods/supplier/isSupplier.js deleted file mode 100644 index d13f304a8..000000000 --- a/modules/supplier/back/methods/supplier/isSupplier.js +++ /dev/null @@ -1,28 +0,0 @@ -const UserError = require('vn-loopback/util/user-error'); - -module.exports = Self => { - Self.remoteMethodCtx('isSupplier', { - description: 'Check is supplierFk exists as supplier', - accessType: 'READ', - returns: { - type: 'boolean', - root: true - }, - http: { - path: `/isSupplier`, - verb: 'GET' - } - }); - - Self.isSupplier = async(ctx, options) => { - const myOptions = {validate: false}; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - const userId = ctx.req.accessToken.userId; - const exists = await Self.findById(userId); - - return !!exists; - }; -}; diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 6094602b6..2d3ffef3e 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -12,7 +12,6 @@ module.exports = Self => { require('../methods/supplier/campaignMetricsEmail')(Self); require('../methods/supplier/newSupplier')(Self); require('../methods/supplier/getItemsPackaging')(Self); - require('../methods/supplier/isSupplier')(Self); Self.validatesPresenceOf('name', { message: 'The social name cannot be empty' -- 2.40.1 From 08cf79b09bc68104a2547e95e1f4b165b8ac6ea8 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 2 Jul 2024 08:39:42 +0200 Subject: [PATCH 332/413] feat roadmap refs #7195 --- .../back/methods/roadmapStop/getPalletMatchState.js | 9 ++++----- .../roadmapStop/specs/getPalletMatchState.spec.js | 4 ++-- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/modules/route/back/methods/roadmapStop/getPalletMatchState.js b/modules/route/back/methods/roadmapStop/getPalletMatchState.js index efed64327..138d62411 100644 --- a/modules/route/back/methods/roadmapStop/getPalletMatchState.js +++ b/modules/route/back/methods/roadmapStop/getPalletMatchState.js @@ -1,6 +1,6 @@ module.exports = Self => { Self.remoteMethod('getPalletMatchState', { - description: 'Get pallet', + description: 'Get list of pallet from roadMapStop with true or false if state is matched', accessType: 'WRITE', accepts: [{ arg: 'roadMapStopFk', @@ -32,7 +32,7 @@ module.exports = Self => { const result = await Self.rawSql(` WITH tPallet AS( - SELECT ep.truckFk roadMapStop,ep.id pallet, e.id expedition, e.stateTypeFk + SELECT ep.id pallet, e.id expedition, e.stateTypeFk FROM vn.expeditionPallet ep JOIN vn.expeditionScan es ON es.palletFk = ep.id JOIN expedition e ON e.id = es.expeditionFk @@ -48,9 +48,8 @@ module.exports = Self => { WHERE code = ? GROUP BY expedition ) - SELECT t.roadMapStop, - t.pallet, - IF (tpe.totalPalletExpedition = tpec.totalPalletExpeditionCode, 'TRUE', 'FALSE') hasMatchStateCode + SELECT t.pallet, + tpe.totalPalletExpedition = tpec.totalPalletExpeditionCode hasMatchStateCode FROM tPallet t LEFT JOIN totalPalletExpedition tpe ON tpe.expedition = t.expedition LEFT JOIN totalPalletExpeditionCode tpec ON tpec.expedition = t.expedition diff --git a/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js b/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js index ac782561a..3e89bd528 100644 --- a/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js +++ b/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js @@ -2,11 +2,11 @@ const {models} = require('vn-loopback/server/server'); describe('roadMapStop getPalletMatchState()', () => { - fit('should return list of pallet with true or false if state is matched', async() => { + it('should return list of pallet with true or false if state is matched', async() => { const roadmapStopFk = 1; const state = 'ON DELIVERY'; const result = await models.RoadmapStop.getPalletMatchState(roadmapStopFk, state); - expect(result[0].hasMatchStateCode).toBe('TRUE'); + expect(result[0].hasMatchStateCode).toBe(1); }); }); -- 2.40.1 From 89a394a10def74e4b9c11cd3986bf7b91b24aab2 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 2 Jul 2024 09:52:18 +0200 Subject: [PATCH 333/413] test(salix): refs #7648 #7648 entry.filter --- modules/entry/back/methods/entry/filter.js | 2 +- .../back/methods/entry/specs/filter.spec.js | 82 +++++++++++++++---- 2 files changed, 65 insertions(+), 19 deletions(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 2a127b496..700d251a2 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -149,7 +149,7 @@ module.exports = Self => { const isSupplier = await Self.app.models.Supplier.findById(userId, options); if (isSupplier) { if (!filter.where) filter.where = {}; - filter.where.supplierFk = ctx.req.accessToken.userId; + filter.where[`e.supplierFk`] = ctx.req.accessToken.userId; } const stmts = []; let stmt; diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index e116d1c5f..76dc7b786 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -describe('Entry filter()', () => { +fdescribe('Entry filter()', () => { it('should return the entry matching "search"', async() => { const tx = await models.Entry.beginTransaction({}); const options = {transaction: tx}; @@ -48,27 +48,73 @@ describe('Entry filter()', () => { } }); - it('should return the entry matching the supplier', async() => { - const tx = await models.Entry.beginTransaction({}); - const options = {transaction: tx}; + describe('should return the entry matching the supplier', () => { + it('when userId is supplier ', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; - try { - const ctx = { - args: { - supplierFk: 2 - }, - req: {accessToken: {userId: 9}} - }; + try { + const ctx = { + args: {}, + req: {accessToken: {userId: 2}} + }; - const result = await models.Entry.filter(ctx, options); + const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(6); + expect(result.length).toEqual(6); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('when userId is supplier fetching other supplier', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: { + supplierFk: 1 + }, + req: {accessToken: {userId: 2}} + }; + + const result = await models.Entry.filter(ctx, options); + + expect(result.length).toEqual(6); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('when userId is not supplier', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: { + supplierFk: 2 + }, + req: {accessToken: {userId: 9}} + }; + + const result = await models.Entry.filter(ctx, options); + + expect(result.length).toEqual(6); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); it('should return the entry matching the company', async() => { -- 2.40.1 From 30520cbe4895357a1026e236a0d8caa90442e6bf Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 2 Jul 2024 10:06:26 +0200 Subject: [PATCH 334/413] test(salix): refs #7648 #7648 getBuys.filter --- .../back/methods/entry/specs/getBuys.spec.js | 93 ++++++++++++++----- 1 file changed, 72 insertions(+), 21 deletions(-) diff --git a/modules/entry/back/methods/entry/specs/getBuys.spec.js b/modules/entry/back/methods/entry/specs/getBuys.spec.js index 44b2ff5bc..801cd6f1a 100644 --- a/modules/entry/back/methods/entry/specs/getBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/getBuys.spec.js @@ -1,31 +1,82 @@ +const UserError = require('vn-loopback/util/user-error'); const models = require('vn-loopback/server/server').models; -describe('entry getBuys()', () => { +fdescribe('entry getBuys()', () => { const entryId = 4; - it('should get the buys and items of an entry', async() => { - const tx = await models.Entry.beginTransaction({}); - const options = {transaction: tx}; + describe('should get the buys and items of an entry ', () => { + it('when is supplier and entry owner', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; - try { - const ctx = { - args: { - search: 1 - }, - req: {accessToken: {userId: 2}} - }; + try { + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 2}} + }; - const result = await models.Entry.getBuys(ctx, entryId, options); + const result = await models.Entry.getBuys(ctx, entryId, options); - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; - expect(result.length).toEqual(4); - expect(anyResult.item).toBeDefined(); + expect(result.length).toEqual(4); + expect(anyResult.item).toBeDefined(); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('when is supplier but not entry owner', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + const entryId = 1; + try { + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 2}} + }; + + const result = await models.Entry.getBuys(ctx, entryId, options); + + expect(result).toBeUndefined(); + } catch (error) { + expect(error).toBeInstanceOf(UserError); + expect(error.message).toBe('Access Denied'); + } + }); + + it('when is not supplier', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 9}} + }; + + const result = await models.Entry.getBuys(ctx, entryId, options); + + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(result.length).toEqual(4); + expect(anyResult.item).toBeDefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); }); -- 2.40.1 From 08612fc70cccafdc802673e96032cc3787913842 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 2 Jul 2024 10:07:23 +0200 Subject: [PATCH 335/413] perf(salix): refs #7648 #7648 fixtures and firstScript --- db/dump/fixtures.before.sql | 3 +++ db/versions/11118-limeCymbidium/00-firstScript.sql | 1 + 2 files changed, 4 insertions(+) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 27f84bdfb..b27bc8ef6 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3913,3 +3913,6 @@ INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, stree truckName, clientFk, phone, province, agency, m3, workerCode, itemFk, quantity, longName, shelvingFk, comments) VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, NULL, 'NCC', NULL); +UPDATE account.`user` + SET `role`=131 + WHERE id=2; diff --git a/db/versions/11118-limeCymbidium/00-firstScript.sql b/db/versions/11118-limeCymbidium/00-firstScript.sql index 0ed1337a0..3921a8a13 100644 --- a/db/versions/11118-limeCymbidium/00-firstScript.sql +++ b/db/versions/11118-limeCymbidium/00-firstScript.sql @@ -18,3 +18,4 @@ UPDATE salix.ACL SET principalId='$authenticated' WHERE id=264; + -- 2.40.1 From 3539b5a33e906cc182ae4468929a43790b76a53d Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 2 Jul 2024 10:08:51 +0200 Subject: [PATCH 336/413] test(salix): refs #7648 #7648 remove fdescribe --- modules/entry/back/methods/entry/specs/filter.spec.js | 2 +- modules/entry/back/methods/entry/specs/getBuys.spec.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index 76dc7b786..9d954cdc4 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -1,6 +1,6 @@ const models = require('vn-loopback/server/server').models; -fdescribe('Entry filter()', () => { +describe('Entry filter()', () => { it('should return the entry matching "search"', async() => { const tx = await models.Entry.beginTransaction({}); const options = {transaction: tx}; diff --git a/modules/entry/back/methods/entry/specs/getBuys.spec.js b/modules/entry/back/methods/entry/specs/getBuys.spec.js index 801cd6f1a..cb7f7cb80 100644 --- a/modules/entry/back/methods/entry/specs/getBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/getBuys.spec.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); const models = require('vn-loopback/server/server').models; -fdescribe('entry getBuys()', () => { +describe('entry getBuys()', () => { const entryId = 4; describe('should get the buys and items of an entry ', () => { it('when is supplier and entry owner', async() => { -- 2.40.1 From 028278ebcfd923335abff83b89da0148386a3130 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 2 Jul 2024 11:52:25 +0200 Subject: [PATCH 337/413] refs #6626 Hotfix --- .../vn/procedures/invoiceInTax_afterUpsert.sql | 13 ------------- db/routines/vn/procedures/invoiceIn_booking.sql | 13 +++++++++++++ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql b/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql index 60ec34696..962cc5224 100644 --- a/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql +++ b/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql @@ -8,7 +8,6 @@ BEGIN */ DECLARE vTaxRowLimit INT; DECLARE vLines INT; - DECLARE vHasDistinctTransactions INT; SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig; @@ -20,17 +19,5 @@ BEGIN IF vLines >= vTaxRowLimit THEN CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit)); END IF; - - SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN invoiceInSerial iis ON iis.code = ii.serial - WHERE ii.id = vInvoiceInFk - AND iis.taxAreaFk = 'CEE' - AND transactionTypeSageFk; - - IF vHasDistinctTransactions > 1 THEN - CALL util.throw ('This invoice does not allow different types of transactions'); - END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index ef124bb46..cd838861a 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -13,6 +13,19 @@ BEGIN * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo */ DECLARE vFiscalYear INT; + DECLARE vHasDistinctTransactions INT; + + SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + JOIN invoiceInSerial iis ON iis.code = ii.serial + WHERE ii.id = vSelf + AND iis.taxAreaFk = 'CEE' + AND transactionTypeSageFk; + + IF vHasDistinctTransactions > 1 THEN + CALL util.throw ('This invoice does not allow different types of transactions'); + END IF; CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY -- 2.40.1 From 7f213a7435550314bb71556a89c6f97062ef681e Mon Sep 17 00:00:00 2001 From: carlossa Date: Tue, 2 Jul 2024 12:02:44 +0200 Subject: [PATCH 338/413] refs #6952 fix producer --- print/templates/reports/delivery-note/delivery-note.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html index 540a80a3a..c1701e084 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -81,7 +81,7 @@ {{sale.tag5}} {{sale.value5}} {{sale.tag6}} {{sale.value6}} {{sale.tag7}} {{sale.value7}} - {{$t('producer')}} {{ sale.subName }} + {{$t('producer')}} {{ sale.subName }} -- 2.40.1 From e1b6ba4276dff0aa80476c9dfc33e33dfcd5b8d1 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Tue, 2 Jul 2024 12:03:21 +0200 Subject: [PATCH 339/413] feat roadmap refs #7195 --- .../back/methods/roadmapStop/getPalletMatchState.js | 10 +++++----- .../roadmapStop/specs/getPalletMatchState.spec.js | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/route/back/methods/roadmapStop/getPalletMatchState.js b/modules/route/back/methods/roadmapStop/getPalletMatchState.js index 138d62411..828dbb689 100644 --- a/modules/route/back/methods/roadmapStop/getPalletMatchState.js +++ b/modules/route/back/methods/roadmapStop/getPalletMatchState.js @@ -1,12 +1,12 @@ module.exports = Self => { Self.remoteMethod('getPalletMatchState', { - description: 'Get list of pallet from roadMapStop with true or false if state is matched', + description: 'Get list of pallet from truckFk with true or false if state is matched', accessType: 'WRITE', accepts: [{ - arg: 'roadMapStopFk', + arg: 'truckFk', type: 'number', required: true, - description: 'The roadmapFk id' + description: 'The truckFk id' }, { arg: 'state', @@ -24,7 +24,7 @@ module.exports = Self => { } }); - Self.getPalletMatchState = async(roadMapStopFk, state, options) => { + Self.getPalletMatchState = async(truckFk, state, options) => { const myOptions = {}; if (typeof options == 'object') @@ -54,7 +54,7 @@ module.exports = Self => { LEFT JOIN totalPalletExpedition tpe ON tpe.expedition = t.expedition LEFT JOIN totalPalletExpeditionCode tpec ON tpec.expedition = t.expedition GROUP BY t.pallet;`, - [roadMapStopFk, state], + [truckFk, state], myOptions); return result; diff --git a/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js b/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js index 3e89bd528..4a79b589e 100644 --- a/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js +++ b/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js @@ -3,9 +3,9 @@ const {models} = require('vn-loopback/server/server'); describe('roadMapStop getPalletMatchState()', () => { it('should return list of pallet with true or false if state is matched', async() => { - const roadmapStopFk = 1; + const truckFk = 1; const state = 'ON DELIVERY'; - const result = await models.RoadmapStop.getPalletMatchState(roadmapStopFk, state); + const result = await models.RoadmapStop.getPalletMatchState(truckFk, state); expect(result[0].hasMatchStateCode).toBe(1); }); -- 2.40.1 From 9708e79e5518addc77a0e447c65744d96a48a149 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 2 Jul 2024 12:41:51 +0200 Subject: [PATCH 340/413] build: increase version 2430 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 95d696fc3..ea126bce3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "24.28.0", + "version": "24.30.0", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", -- 2.40.1 From 0bb4439f85d07c6765d2873c0ca82f1b42a25358 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 2 Jul 2024 14:37:22 +0200 Subject: [PATCH 341/413] refs #7443 Deleted ekt barcode --- db/routines/edi/procedures/ekt_refresh.sql | 19 +++---------------- db/routines/edi/views/ektRecent.sql | 1 - db/routines/vn2008/views/buy_edi.sql | 1 - 3 files changed, 3 insertions(+), 18 deletions(-) diff --git a/db/routines/edi/procedures/ekt_refresh.sql b/db/routines/edi/procedures/ekt_refresh.sql index 0e9ed7d3c..8ba438c0a 100644 --- a/db/routines/edi/procedures/ekt_refresh.sql +++ b/db/routines/edi/procedures/ekt_refresh.sql @@ -7,7 +7,6 @@ BEGIN */ DECLARE vRewriteKop INT DEFAULT NULL; DECLARE vTruncatePutOrder INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; DECLARE vKop INT; DECLARE vPutOrderFk BIGINT; @@ -16,17 +15,6 @@ BEGIN FROM ekt WHERE id = vSelf; - -- Generates the barcode - - SELECT CONCAT( - LPAD(IFNULL(auction,0), 3, 0), - LPAD(IFNULL(klo, 99), 2, 0), - LPAD(DAYOFYEAR(fec), 3, 0), - COALESCE(agj, RIGHT(batchNumber,7), id)) - INTO vBarcode - FROM ekt - WHERE id = vSelf; - -- Rewrites the kop parameter IF vKop IS NULL THEN @@ -46,10 +34,9 @@ BEGIN -- Refresh EKT - UPDATE ekt SET - barcode = vBarcode - ,kop = vKop - ,putOrderFk = vTruncatePutOrder + UPDATE ekt + SET kop = vKop, + putOrderFk = vTruncatePutOrder WHERE id = vSelf; END$$ DELIMITER ; diff --git a/db/routines/edi/views/ektRecent.sql b/db/routines/edi/views/ektRecent.sql index 3e41490ab..66ff7875e 100644 --- a/db/routines/edi/views/ektRecent.sql +++ b/db/routines/edi/views/ektRecent.sql @@ -2,7 +2,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `edi`.`ektRecent` AS SELECT `e`.`id` AS `id`, - `e`.`barcode` AS `barcode`, `e`.`entryYear` AS `entryYear`, `e`.`batchNumber` AS `batchNumber`, `e`.`deliveryNumber` AS `deliveryNumber`, diff --git a/db/routines/vn2008/views/buy_edi.sql b/db/routines/vn2008/views/buy_edi.sql index 0d194c89e..d00196e95 100644 --- a/db/routines/vn2008/views/buy_edi.sql +++ b/db/routines/vn2008/views/buy_edi.sql @@ -2,7 +2,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn2008`.`buy_edi` AS SELECT `t`.`id` AS `id`, - `t`.`barcode` AS `barcode`, `t`.`entryYear` AS `entry_year`, `t`.`deliveryNumber` AS `delivery_number`, `t`.`fec` AS `fec`, -- 2.40.1 From 0d70cb892909348e98086e07d564ea3df8f5fa0c Mon Sep 17 00:00:00 2001 From: jgallego Date: Tue, 2 Jul 2024 17:39:46 +0200 Subject: [PATCH 342/413] fix: informatica no necesita este correo --- db/routines/vn/procedures/XDiario_check.sql | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/db/routines/vn/procedures/XDiario_check.sql b/db/routines/vn/procedures/XDiario_check.sql index 0fb1c410d..ef969924b 100644 --- a/db/routines/vn/procedures/XDiario_check.sql +++ b/db/routines/vn/procedures/XDiario_check.sql @@ -6,19 +6,6 @@ BEGIN * identificando y notificando los asientos descuadrados * y ajustando los saldos en caso necesario. */ - INSERT INTO mail (receiver, subject, body) - SELECT 'cau@verdnatura.es', - 'Asientos descuadrados', - GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n') - FROM ( - SELECT ASIEN, - SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon - FROM XDiario - WHERE NOT enlazado - GROUP BY ASIEN - HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01 - ) sub - HAVING COUNT(*); UPDATE XDiario xd JOIN ( -- 2.40.1 From cc004a864a58397e0e2701aa7f7bbac29ad02575 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Tue, 2 Jul 2024 20:41:53 +0200 Subject: [PATCH 343/413] feat(salix): refs #7648 #7648 rename some travel fields --- modules/entry/back/methods/entry/filter.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 700d251a2..c25a7527e 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -178,10 +178,10 @@ module.exports = Self => { s.nickname AS supplierAlias, co.code AS companyCode, cu.code AS currencyCode, - t.shipped AS shipped, - t.landed AS landed, - t.warehouseInFk AS warehouseId, - w.name AS warehouseName + t.shipped, + t.landed, + t.warehouseInFk, + w.name AS warehouseInName FROM vn.entry e JOIN vn.supplier s ON s.id = e.supplierFk JOIN vn.travel t ON t.id = e.travelFk -- 2.40.1 From adbbe4aef9c57513be79fb8e4804d9bf40a8f9fe Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 3 Jul 2024 01:46:01 +0200 Subject: [PATCH 344/413] fix(salix): refs #7648 #7648 solve big bug --- modules/entry/back/methods/entry/getBuys.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index e392ba3ce..444e6cb14 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -1,4 +1,3 @@ -const ForbiddenError = require('vn-loopback/util/forbiddenError'); const UserError = require('vn-loopback/util/user-error'); const mergeFilters = require('vn-loopback/util/filter').mergeFilters; @@ -37,7 +36,7 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const isSupplier = await Self.app.models.Supplier.findById(userId, options); + const isSupplier = await Self.app.models.Supplier.findById(userId, myOptions); if (isSupplier) { const isEntryOwner = (await Self.findById(id)).supplierFk === userId; -- 2.40.1 From 946d6f553af0be220e5b9d882397c6fda4252daf Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 3 Jul 2024 08:16:55 +0200 Subject: [PATCH 345/413] perf(salix): refs #7648 #7648 sql conventions --- modules/entry/back/methods/entry/filter.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index c25a7527e..9bbce1c95 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -162,7 +162,7 @@ module.exports = Self => { e.invoiceNumber, e.isBooked, e.isExcludedFromAvailable, - e.evaNotes AS observation, + e.evaNotes observation, e.isConfirmed, e.isOrdered, e.isRaid, @@ -174,14 +174,14 @@ module.exports = Self => { e.gestDocFk, e.invoiceInFk, t.landed, - s.name AS supplierName, - s.nickname AS supplierAlias, - co.code AS companyCode, - cu.code AS currencyCode, + s.name supplierName, + s.nickname supplierAlias, + co.code companyCode, + cu.code currencyCode, t.shipped, t.landed, t.warehouseInFk, - w.name AS warehouseInName + w.name warehouseInName FROM vn.entry e JOIN vn.supplier s ON s.id = e.supplierFk JOIN vn.travel t ON t.id = e.travelFk -- 2.40.1 From 19c378d6bd675b7e2079a6785477fd4b78ab66b0 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 3 Jul 2024 08:48:24 +0200 Subject: [PATCH 346/413] =?UTF-8?q?feat:=20refs=20#7116=20a=C3=B1adir=20co?= =?UTF-8?q?mentario?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/versions/10960-silverRoebelini/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql index 75fc5277f..228e0b014 100644 --- a/db/versions/10960-silverRoebelini/00-firstScript.sql +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -5,4 +5,4 @@ CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 -COLLATE=utf8mb3_unicode_ci; \ No newline at end of file +COLLATE=utf8mb3_unicode_ci COMMENT='Agencias de entrada de mercancias';; \ No newline at end of file -- 2.40.1 From beff905e02bfb6b2d074eb122d0e01f8c9668ec8 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 3 Jul 2024 08:54:58 +0200 Subject: [PATCH 347/413] perf(salix): refs #7648 #7648 remove change role for user 2 --- db/dump/fixtures.before.sql | 4 ---- 1 file changed, 4 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index b27bc8ef6..359410564 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3912,7 +3912,3 @@ VALUES(1, ''); INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, street, postalCode, city, shopName, isPrinted, created, printerFk, routeFk, parkingCode, truckName, clientFk, phone, province, agency, m3, workerCode, itemFk, quantity, longName, shelvingFk, comments) VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, NULL, 'NCC', NULL); - -UPDATE account.`user` - SET `role`=131 - WHERE id=2; -- 2.40.1 From 1561e15d5ed1e567996319ad00bf47d7d7889417 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Wed, 3 Jul 2024 09:21:58 +0200 Subject: [PATCH 348/413] feat roadmap refs #7195 --- back/models/warehouse.json | 107 ++++++++------ .../11081-wheatRaphis/00-firstScript.sql | 8 + .../roadmapStop/getPalletMatchState.js | 62 ++++++++ .../specs/getPalletMatchState.spec.js | 12 ++ modules/route/back/models/roadmap.json | 138 ++++++++++-------- modules/route/back/models/roadmapStop.js | 3 + modules/route/back/models/roadmapStop.json | 86 +++++------ 7 files changed, 262 insertions(+), 154 deletions(-) create mode 100644 db/versions/11081-wheatRaphis/00-firstScript.sql create mode 100644 modules/route/back/methods/roadmapStop/getPalletMatchState.js create mode 100644 modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js create mode 100644 modules/route/back/models/roadmapStop.js diff --git a/back/models/warehouse.json b/back/models/warehouse.json index f12b5e86e..756a538c0 100644 --- a/back/models/warehouse.json +++ b/back/models/warehouse.json @@ -1,48 +1,59 @@ -{ - "name": "Warehouse", - "description": "Warehouses from where orders are sent", - "base": "VnModel", - "options": { - "mysql": { - "table": "warehouse" - } - }, - "properties": { - "id": { - "id": true, - "type": "number", - "forceId": false - }, - "name": { - "type": "string" - }, - "code": { - "type": "string" - }, - "isInventory": { - "type": "number" - }, - "isManaged":{ - "type": "boolean" - }, - "countryFk": { - "type": "number" - } - }, - "relations": { - "country": { - "type": "belongsTo", - "model": "Country", - "foreignKey": "countryFk" - } - }, - "acls": [ - { - "accessType": "READ", - "principalType": "ROLE", - "principalId": "$everyone", - "permission": "ALLOW" - } - ], - "scope" : {"where": {"isForTicket": {"neq": 0}}} -} +{ + "name": "Warehouse", + "description": "Warehouses from where orders are sent", + "base": "VnModel", + "options": { + "mysql": { + "table": "warehouse" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "forceId": false + }, + "name": { + "type": "string" + }, + "code": { + "type": "string" + }, + "isInventory": { + "type": "number" + }, + "isManaged": { + "type": "boolean" + }, + "countryFk": { + "type": "number" + } + }, + "relations": { + "country": { + "type": "belongsTo", + "model": "Country", + "foreignKey": "countryFk" + }, + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ], + "scope": { + "where": { + "isForTicket": { + "neq": 0 + } + } + } +} \ No newline at end of file diff --git a/db/versions/11081-wheatRaphis/00-firstScript.sql b/db/versions/11081-wheatRaphis/00-firstScript.sql new file mode 100644 index 000000000..2e4424c5a --- /dev/null +++ b/db/versions/11081-wheatRaphis/00-firstScript.sql @@ -0,0 +1,8 @@ +-- Place your SQL code here + +USE vn; + +ALTER TABLE vn.roadmap ADD kmStart mediumint(9) DEFAULT NULL NULL; +ALTER TABLE vn.roadmap ADD kmEnd mediumint(9) DEFAULT NULL NULL; +ALTER TABLE vn.roadmap ADD started DATETIME NULL; +ALTER TABLE vn.roadmap ADD finished DATETIME NULL; diff --git a/modules/route/back/methods/roadmapStop/getPalletMatchState.js b/modules/route/back/methods/roadmapStop/getPalletMatchState.js new file mode 100644 index 000000000..234c254c4 --- /dev/null +++ b/modules/route/back/methods/roadmapStop/getPalletMatchState.js @@ -0,0 +1,62 @@ +module.exports = Self => { + Self.remoteMethod('getPalletMatchState', { + description: 'Get list of pallet from truckFk with true or false if state is matched', + accessType: 'WRITE', + accepts: [{ + arg: 'truckFk', + type: 'number', + required: true, + description: 'The truckFk id' + }, + { + arg: 'state', + type: 'string', + required: true, + description: 'State code' + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/getPalletMatchState`, + verb: 'GET' + } + }); + + Self.getPalletMatchState = async(truckFk, state, options) => { + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + const result = await Self.rawSql(` + WITH tPallet AS( + SELECT ep.id pallet, e.id expedition, e.stateTypeFk + FROM vn.expeditionPallet ep + JOIN vn.expeditionScan es ON es.palletFk = ep.id + JOIN expedition e ON e.id = es.expeditionFk + WHERE ep.truckFk = ? + ),totalPalletExpedition AS( + SELECT t.*, COUNT(expedition) totalPalletExpedition + FROM tPallet t + GROUP BY expedition + ),totalPalletExpeditionCode AS( + SELECT t.*, COUNT(expedition) totalPalletExpeditionCode + FROM tPallet t + JOIN vn.expeditionStateType est ON est.id = t.stateTypeFk + WHERE code = ? + GROUP BY expedition + ) + SELECT t.pallet, + tpe.totalPalletExpedition = tpec.totalPalletExpeditionCode hasMatchStateCode + FROM tPallet t + LEFT JOIN totalPalletExpedition tpe ON tpe.expedition = t.expedition + LEFT JOIN totalPalletExpeditionCode tpec ON tpec.expedition = t.expedition + GROUP BY t.pallet;`, + [truckFk, state], + myOptions); + + return result; + }; +}; diff --git a/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js b/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js new file mode 100644 index 000000000..24f742c76 --- /dev/null +++ b/modules/route/back/methods/roadmapStop/specs/getPalletMatchState.spec.js @@ -0,0 +1,12 @@ + +const {models} = require('vn-loopback/server/server'); + +describe('roadMapStop getPalletMatchState()', () => { + it('should return list of pallet with true or false if state is matched', async() => { + const truckFk = 1; + const state = 'ON DELIVERY'; + const result = await models.RoadmapStop.getPalletMatchState(truckFk, state); + + expect(result[0].hasMatchStateCode).toBe(1); + }); +}); diff --git a/modules/route/back/models/roadmap.json b/modules/route/back/models/roadmap.json index 01572d718..dcac035ce 100644 --- a/modules/route/back/models/roadmap.json +++ b/modules/route/back/models/roadmap.json @@ -1,63 +1,75 @@ -{ - "name": "Roadmap", - "base": "VnModel", - "options": { - "mysql": { - "table": "roadmap" - } - }, - "properties": { - "id": { - "type": "number", - "id": true, - "description": "Identifier" - }, - "name": { - "type": "string" - }, - "tractorPlate": { - "type": "string" - }, - "trailerPlate": { - "type": "string" - }, - "phone": { - "type": "string" - }, - "supplierFk": { - "type": "number" - }, - "etd": { - "type": "date" - }, - "observations": { - "type": "string" - }, - "userFk": { - "type": "number" - }, - "price": { - "type": "number" - }, - "driverName": { - "type": "string" - } - }, - "relations": { - "worker": { - "type": "belongsTo", - "model": "Worker", - "foreignKey": "id" - }, - "supplier": { - "type": "belongsTo", - "model": "Supplier", - "foreignKey": "supplierFk" - }, - "roadmapStop": { - "type": "hasMany", - "model": "RoadmapStop", - "foreignKey": "roadmapFk" - } - } -} +{ + "name": "Roadmap", + "base": "VnModel", + "options": { + "mysql": { + "table": "roadmap" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "name": { + "type": "string" + }, + "tractorPlate": { + "type": "string" + }, + "trailerPlate": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "supplierFk": { + "type": "number" + }, + "etd": { + "type": "date" + }, + "observations": { + "type": "string" + }, + "userFk": { + "type": "number" + }, + "price": { + "type": "number" + }, + "driverName": { + "type": "string" + }, + "kmStart": { + "type": "number" + }, + "kmEnd": { + "type": "number" + }, + "started": { + "type": "date" + }, + "finished": { + "type": "date" + } + }, + "relations": { + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "id" + }, + "supplier": { + "type": "belongsTo", + "model": "Supplier", + "foreignKey": "supplierFk" + }, + "roadmapStop": { + "type": "hasMany", + "model": "RoadmapStop", + "foreignKey": "roadmapFk" + } + } +} \ No newline at end of file diff --git a/modules/route/back/models/roadmapStop.js b/modules/route/back/models/roadmapStop.js new file mode 100644 index 000000000..1ce3f409e --- /dev/null +++ b/modules/route/back/models/roadmapStop.js @@ -0,0 +1,3 @@ +module.exports = Self => { + require('../methods/roadmapStop/getPalletMatchState')(Self); +}; diff --git a/modules/route/back/models/roadmapStop.json b/modules/route/back/models/roadmapStop.json index 74b02cd7a..edd615aae 100644 --- a/modules/route/back/models/roadmapStop.json +++ b/modules/route/back/models/roadmapStop.json @@ -1,43 +1,43 @@ -{ - "name": "RoadmapStop", - "base": "VnModel", - "options": { - "mysql": { - "table": "roadmapStop" - } - }, - "properties": { - "id": { - "type": "number", - "id": true, - "description": "Identifier" - }, - "roadmapFk": { - "type": "number" - }, - "addressFk": { - "type": "number" - }, - "eta": { - "type": "date" - }, - "description": { - "type": "string" - }, - "userFk": { - "type": "number" - } - }, - "relations": { - "roadmap": { - "type": "belongsTo", - "model": "Roadmap", - "foreignKey": "roadmapFk" - }, - "address": { - "type": "belongsTo", - "model": "Address", - "foreignKey": "addressFk" - } - } -} +{ + "name": "RoadmapStop", + "base": "VnModel", + "options": { + "mysql": { + "table": "roadmapStop" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "roadmapFk": { + "type": "number" + }, + "addressFk": { + "type": "number" + }, + "eta": { + "type": "date" + }, + "description": { + "type": "string" + }, + "userFk": { + "type": "number" + } + }, + "relations": { + "roadmap": { + "type": "belongsTo", + "model": "Roadmap", + "foreignKey": "roadmapFk" + }, + "address": { + "type": "belongsTo", + "model": "RoadmapAddress", + "foreignKey": "addressFk" + } + } +} \ No newline at end of file -- 2.40.1 From d1ef1c80f8271026905e45fd2790160984ae5de1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 09:36:20 +0200 Subject: [PATCH 349/413] feat: refs #7382 Added unique key --- db/versions/11127-silverMoss/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11127-silverMoss/00-firstScript.sql diff --git a/db/versions/11127-silverMoss/00-firstScript.sql b/db/versions/11127-silverMoss/00-firstScript.sql new file mode 100644 index 000000000..aae2e857e --- /dev/null +++ b/db/versions/11127-silverMoss/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.invoiceInTax ADD CONSTRAINT invoiceInTax_unique UNIQUE KEY (invoiceInFk,expenseFk); -- 2.40.1 From 77d86c9fd979fe92aaa4b416c73c07a25f392f3d Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 09:55:14 +0200 Subject: [PATCH 350/413] feat: refs #7664 Added created in calendar table --- db/versions/11128-turquoiseCymbidium/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11128-turquoiseCymbidium/00-firstScript.sql diff --git a/db/versions/11128-turquoiseCymbidium/00-firstScript.sql b/db/versions/11128-turquoiseCymbidium/00-firstScript.sql new file mode 100644 index 000000000..4f6cafcf8 --- /dev/null +++ b/db/versions/11128-turquoiseCymbidium/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.calendar ADD created timestamp DEFAULT current_timestamp() NOT NULL AFTER dated; -- 2.40.1 From aaca2d12c5e2eda72d92a0fc109806b6ae4e3336 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 10:20:20 +0200 Subject: [PATCH 351/413] refactor: refs #7504 Rename id greuge --- db/versions/11129-limeHydrangea/00-firstScript.sql | 1 + 1 file changed, 1 insertion(+) create mode 100644 db/versions/11129-limeHydrangea/00-firstScript.sql diff --git a/db/versions/11129-limeHydrangea/00-firstScript.sql b/db/versions/11129-limeHydrangea/00-firstScript.sql new file mode 100644 index 000000000..eb2320ee1 --- /dev/null +++ b/db/versions/11129-limeHydrangea/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.greuge CHANGE Id id int(10) unsigned auto_increment NOT NULL; -- 2.40.1 From fafebb4339c76ea80d4d29ccc34165a66e244db6 Mon Sep 17 00:00:00 2001 From: carlossa Date: Wed, 3 Jul 2024 12:13:40 +0200 Subject: [PATCH 352/413] refs #6897 fix filter --- modules/entry/back/methods/entry/filter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index df5fef1bc..69bcb46da 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -180,7 +180,7 @@ module.exports = Self => { cu.code currencyCode, t.shipped, t.landed, - t.ref AS travelRef + t.ref AS travelRef, t.warehouseInFk, w.name warehouseInName FROM vn.entry e -- 2.40.1 From 900fa2de5ed71fb921517578787e930a35e889c7 Mon Sep 17 00:00:00 2001 From: jorgep Date: Wed, 3 Jul 2024 13:03:19 +0200 Subject: [PATCH 353/413] fix: refs #7648 add myOpts --- modules/entry/back/methods/entry/filter.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 69bcb46da..5989494a4 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -146,7 +146,7 @@ module.exports = Self => { }); filter = mergeFilters(ctx.args.filter, {where}); const userId = ctx.req.accessToken.userId; - const isSupplier = await Self.app.models.Supplier.findById(userId, options); + const isSupplier = await Self.app.models.Supplier.findById(userId, myOptions); if (isSupplier) { if (!filter.where) filter.where = {}; filter.where[`e.supplierFk`] = ctx.req.accessToken.userId; -- 2.40.1 From 4f9552379ed043f5d334e588fc9678085e7a9929 Mon Sep 17 00:00:00 2001 From: robert Date: Wed, 3 Jul 2024 13:46:19 +0200 Subject: [PATCH 354/413] feat: refs #7654 entry_splitByShelving --- .../vn/procedures/entry_splitByShelving.sql | 170 ++++++++---------- .../11131-brownPhormium/00-firstScript.sql | 1 + 2 files changed, 80 insertions(+), 91 deletions(-) create mode 100644 db/versions/11131-brownPhormium/00-firstScript.sql diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index 2898141ea..839bf02d1 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -9,70 +9,81 @@ BEGIN * @param vToEntryFk Entrada destino */ DECLARE vBuyFk INT; - DECLARE vIshStickers INT; - DECLARE vBuyStickers INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; - - DECLARE cur CURSOR FOR - SELECT bb.id buyFk, - FLOOR(ish.visible / ish.packing) ishStickers, - bb.stickers buyStickers - FROM vn.itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - AND bb.stickers >= FLOOR(ish.visible / ish.packing) - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci - GROUP BY ish.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE vIshStickers INT; + DECLARE vBuyStickers INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; - -- Cantidades de la matrícula que exceden la de las entradas - SELECT ish.itemFk, - i.longName, - FLOOR(ish.visible / ish.packing) AS etiEnMatricula, - bb.stickers etiEnEntrada - FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - LEFT JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci - AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing) - GROUP BY ish.id; - - OPEN cur; - - read_loop: LOOP - SET vDone = FALSE; + DECLARE cur CURSOR FOR + SELECT bb.id buyFk, + FLOOR(ish.visible / ish.packing) ishStickers, + bb.stickers buyStickers + FROM itemShelving ish + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM buy b + WHERE b.entryFk = vFromEntryFk + ORDER BY b.stickers DESC + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + AND bb.stickers >= FLOOR(ish.visible / ish.packing) + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + AND NOT ish.isSplit + GROUP BY ish.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; + OPEN cur; - IF vDone THEN - LEAVE read_loop; - END IF; + read_loop: LOOP + SET vDone = FALSE; - IF vIshStickers = vBuyStickers THEN - UPDATE vn.buy - SET entryFk = vToEntryFk - WHERE id = vBuyFk; - ELSE - UPDATE vn.buy - SET stickers = stickers - vIshStickers, - quantity = stickers * packing - WHERE id = vBuyFk; - - INSERT INTO vn.buy(entryFk, + FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; + + IF vDone THEN + LEAVE read_loop; + END IF; + + IF vIshStickers = vBuyStickers THEN + UPDATE buy + SET entryFk = vToEntryFk + WHERE id = vBuyFk; + ELSE + UPDATE buy + SET stickers = stickers - vIshStickers, + quantity = stickers * packing + WHERE id = vBuyFk; + + INSERT INTO buy(entryFk, + itemFk, + quantity, + buyingValue, + freightValue, + isIgnored, + stickers, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + location, + packagingFk, + price1, + price2, + price3, + minPrice, + workerFk, + isChecked, + isPickedOff, + ektFk, + weight, + deliveryFk, + itemOriginalFk) + SELECT + vToEntryFk, itemFk, - quantity, + vIshStickers * packing, buyingValue, freightValue, isIgnored, - stickers, + vIshStickers, packing, `grouping`, groupingMode, @@ -90,40 +101,17 @@ BEGIN ektFk, weight, deliveryFk, - itemOriginalFk) - SELECT - vToEntryFk, - itemFk, - vIshStickers * packing, - buyingValue, - freightValue, - isIgnored, - vIshStickers, - packing, - `grouping`, - groupingMode, - comissionValue, - packageValue, - location, - packagingFk, - price1, - price2, - price3, - minPrice, - workerFk, - isChecked, - isPickedOff, - ektFk, - weight, - deliveryFk, - itemOriginalFk - FROM vn.buy - WHERE id = vBuyFk; - - UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); - END IF; - END LOOP; - - CLOSE cur; + itemOriginalFk + FROM buy + WHERE id = vBuyFk; + + UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); + END IF; + + UPDATE itemShelving + SET isSplit = TRUE + WHERE shelvingFk = vShelvingFk; + END LOOP; + CLOSE cur; END$$ DELIMITER ; diff --git a/db/versions/11131-brownPhormium/00-firstScript.sql b/db/versions/11131-brownPhormium/00-firstScript.sql new file mode 100644 index 000000000..341c9f1a3 --- /dev/null +++ b/db/versions/11131-brownPhormium/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.itemShelving ADD isSplit tinyint(1) NULL COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda'; \ No newline at end of file -- 2.40.1 From 2278b9a05aa25835ded18b6f2ff784ba5d88ff3f Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 14:20:43 +0200 Subject: [PATCH 355/413] feat: refs #7382 Changes --- .../vn/procedures/invoiceIn_booking.sql | 25 +++++++++++++------ .../11127-silverMoss/00-firstScript.sql | 1 - 2 files changed, 18 insertions(+), 8 deletions(-) delete mode 100644 db/versions/11127-silverMoss/00-firstScript.sql diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index cd838861a..decbb7b1a 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -13,20 +13,31 @@ BEGIN * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo */ DECLARE vFiscalYear INT; - DECLARE vHasDistinctTransactions INT; + DECLARE vDistinctTransactions INT; + DECLARE vHasRepeatedTransactions BOOL; - SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + SELECT COUNT(DISTINCT iit.transactionTypeSageFk) INTO vDistinctTransactions + FROM invoiceInTax iit JOIN invoiceInSerial iis ON iis.code = ii.serial - WHERE ii.id = vSelf + WHERE iit.invoiceInFk = vSelf AND iis.taxAreaFk = 'CEE' - AND transactionTypeSageFk; + AND iit.transactionTypeSageFk; - IF vHasDistinctTransactions > 1 THEN + IF vDistinctTransactions > 1 THEN CALL util.throw ('This invoice does not allow different types of transactions'); END IF; + SELECT TRUE INTO vHasRepeatedTransactions + FROM invoiceInTax + WHERE invoiceInFk = vSelf + GROUP BY transactionTypeSageFk + HAVING COUNT(transactionTypeSageFk) > 1 + LIMIT 1; + + IF vHasRepeatedTransactions THEN + CALL util.throw ('This invoice contains repeated types of transactions'); + END IF; + CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY SELECT ii.bookEntried, diff --git a/db/versions/11127-silverMoss/00-firstScript.sql b/db/versions/11127-silverMoss/00-firstScript.sql deleted file mode 100644 index aae2e857e..000000000 --- a/db/versions/11127-silverMoss/00-firstScript.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE vn.invoiceInTax ADD CONSTRAINT invoiceInTax_unique UNIQUE KEY (invoiceInFk,expenseFk); -- 2.40.1 From 246b34571d786f8fbf635038304135629ab16077 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 3 Jul 2024 14:24:26 +0200 Subject: [PATCH 356/413] feat: refs #7382 Fix --- db/routines/vn/procedures/invoiceIn_booking.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index decbb7b1a..c194a774d 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -17,7 +17,8 @@ BEGIN DECLARE vHasRepeatedTransactions BOOL; SELECT COUNT(DISTINCT iit.transactionTypeSageFk) INTO vDistinctTransactions - FROM invoiceInTax iit + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id JOIN invoiceInSerial iis ON iis.code = ii.serial WHERE iit.invoiceInFk = vSelf AND iis.taxAreaFk = 'CEE' -- 2.40.1 From 1ec7cd9540dc3e1d003cbb8d31e3b291383af0fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 16:59:01 +0200 Subject: [PATCH 357/413] Hotfix sale_getProblems --- db/routines/vn/procedures/sale_getProblems.sql | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index 9944ab0c2..f198be54b 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -278,12 +278,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk, problem, saleFk + SELECT ticketFk,problem , saleFk FROM ( SELECT tl.ticketFk, - s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, - MOD(s.quantity, b.`grouping`) hasRounding + s.id saleFk, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk @@ -291,9 +290,9 @@ BEGIN JOIN item i ON i.id = s.itemFk JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk JOIN buy b ON b.id = bu.buyFk + WHERE MOD(s.quantity, b.`grouping`) GROUP BY tl.ticketFk - HAVING hasRounding - ) sub + )sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; -- 2.40.1 From 097350adb66a233515018f2e8a17b86065fdef54 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 17:07:25 +0200 Subject: [PATCH 358/413] Hotfix sale_getProblems --- db/routines/vn/procedures/sale_getProblems.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index f198be54b..ba4ff5857 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -278,11 +278,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk,problem , saleFk + SELECT ticketFk, problem ,saleFk FROM ( SELECT tl.ticketFk, s.id saleFk, - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk -- 2.40.1 From d65af6aaaac6c5cb85856d2f44f97bf327b26a43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 18:00:28 +0200 Subject: [PATCH 359/413] feat: Avisar cuando no hay posibilidad de fichar refs #7669 --- .../vn/procedures/workerTimeControl_direction.sql | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/db/routines/vn/procedures/workerTimeControl_direction.sql b/db/routines/vn/procedures/workerTimeControl_direction.sql index f7a68e1e4..807dc46c6 100644 --- a/db/routines/vn/procedures/workerTimeControl_direction.sql +++ b/db/routines/vn/procedures/workerTimeControl_direction.sql @@ -9,6 +9,8 @@ BEGIN */ DECLARE vLastIn DATETIME ; DECLARE vIsMiddleOdd BOOLEAN ; + DECLARE vMailTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); @@ -57,5 +59,18 @@ BEGIN VALUES('in', NULL); END IF; + IF (SELECT option1 IS NULL AND option2 IS NULL FROM tmp.workerTimeControlDirection) THEN + SELECT CONCAT(u.name, '@verdnatura.es'), CONCAT(w.firstName, ' ', w.lastName) + INTO vMailTo, vUserName + FROM account.user u + JOIN worker w ON w.bossFk = u.id + WHERE w.id = vWorkerFk; + + CALL mail_insert( + vMailTo, + vMailTo, + 'Error al fichar', + CONCAT(vUserName, ' tiene problemas para fichar'); + END IF; END$$ DELIMITER ; -- 2.40.1 From 989fa5ac5a3f2b101a38b85413f1552be9c3111f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Andr=C3=A9s?= Date: Wed, 3 Jul 2024 18:10:02 +0200 Subject: [PATCH 360/413] feat: Avisar cuando no hay posibilidad de fichar refs #7669 --- db/routines/vn/procedures/workerTimeControl_direction.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/workerTimeControl_direction.sql b/db/routines/vn/procedures/workerTimeControl_direction.sql index 807dc46c6..8e807084c 100644 --- a/db/routines/vn/procedures/workerTimeControl_direction.sql +++ b/db/routines/vn/procedures/workerTimeControl_direction.sql @@ -70,7 +70,7 @@ BEGIN vMailTo, vMailTo, 'Error al fichar', - CONCAT(vUserName, ' tiene problemas para fichar'); + CONCAT(vUserName, ' tiene problemas para fichar')); END IF; END$$ DELIMITER ; -- 2.40.1 From d59cab13d8556a12135a8a0540ea4de5d3fdfa34 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 3 Jul 2024 23:02:28 +0200 Subject: [PATCH 361/413] feat(salix): refs #7380 #7380 client.substitutionAllowed new field --- db/versions/11132-aquaDracena/00-firstScript.sql | 1 + modules/client/back/models/client.json | 3 +++ 2 files changed, 4 insertions(+) create mode 100644 db/versions/11132-aquaDracena/00-firstScript.sql diff --git a/db/versions/11132-aquaDracena/00-firstScript.sql b/db/versions/11132-aquaDracena/00-firstScript.sql new file mode 100644 index 000000000..d309098c5 --- /dev/null +++ b/db/versions/11132-aquaDracena/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.client ADD substitutionAllowed BOOL DEFAULT false NULL; diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index f3eb9919b..97c2a3624 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -53,6 +53,9 @@ "isActive": { "type": "boolean" }, + "substitutionAllowed": { + "type": "boolean" + }, "credit": { "type": "number" }, -- 2.40.1 From 17e7dc8c7ee35b0ae9f9a1914b7c9ad2b3f114b0 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Wed, 3 Jul 2024 23:02:47 +0200 Subject: [PATCH 362/413] feat(salix): refs #7380 #7380 new typeObservation --- db/versions/11132-aquaDracena/00-firstScript.sql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/db/versions/11132-aquaDracena/00-firstScript.sql b/db/versions/11132-aquaDracena/00-firstScript.sql index d309098c5..1b304c1d0 100644 --- a/db/versions/11132-aquaDracena/00-firstScript.sql +++ b/db/versions/11132-aquaDracena/00-firstScript.sql @@ -1 +1,4 @@ +INSERT IGNORE INTO vn.observationType (`description`,code,hasNewBornMessage) + VALUES ('Sustitución','substitution',0); + ALTER TABLE vn.client ADD substitutionAllowed BOOL DEFAULT false NULL; -- 2.40.1 From a7b653c42a5f886d8eba1507fff24bcbc8dbdb4d Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 07:34:41 +0200 Subject: [PATCH 363/413] refs #7486 Fix collection_new --- .../vn/procedures/collection_assign.sql | 4 +- db/routines/vn/procedures/collection_get.sql | 45 ++++++++++--------- .../vn/procedures/productionControl.sql | 8 +++- db/routines/vn/procedures/ticket_Clone.sql | 5 +++ 4 files changed, 39 insertions(+), 23 deletions(-) diff --git a/db/routines/vn/procedures/collection_assign.sql b/db/routines/vn/procedures/collection_assign.sql index 84067e7d8..bf130b2c6 100644 --- a/db/routines/vn/procedures/collection_assign.sql +++ b/db/routines/vn/procedures/collection_assign.sql @@ -47,9 +47,9 @@ BEGIN INTO vHasTooMuchCollections, vLockName FROM productionConfig pc - LEFT JOIN tCollection ON TRUE; + LEFT JOIN tmp.collection ON TRUE; - DROP TEMPORARY TABLE tCollection; + DROP TEMPORARY TABLE tmp.collection; IF vHasTooMuchCollections THEN CALL util.throw('Hay colecciones pendientes'); diff --git a/db/routines/vn/procedures/collection_get.sql b/db/routines/vn/procedures/collection_get.sql index 372d963c0..d29f14ca9 100644 --- a/db/routines/vn/procedures/collection_get.sql +++ b/db/routines/vn/procedures/collection_get.sql @@ -7,27 +7,32 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tCollection; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; - CREATE TEMPORARY TABLE tCollection - SELECT c.id collectionFk, - date(c.created) created, - COUNT(DISTINCT tc.ticketFk) ticketTotalCount - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk - JOIN ticketState ts ON ts.ticketFk = tc.ticketFk - JOIN state s2 ON s2.id = ts.stateFk - JOIN productionConfig pc - JOIN vn.state ss on ss.code = 'PREPARED' - LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk - AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge - AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder - GROUP BY c.id - HAVING COUNT(*) > COUNT(DISTINCT st.id); + CREATE OR REPLACE TEMPORARY TABLE tmp.collection + ENGINE = MEMORY + SELECT c.id collectionFk, + DATE(c.created) created, + COUNT(DISTINCT tc.ticketFk) ticketTotalCount + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk + JOIN ticketState ts ON ts.ticketFk = tc.ticketFk + JOIN state s2 ON s2.id = ts.stateFk + JOIN productionConfig pc + JOIN vn.state ss ON ss.code = 'PREPARED' + LEFT JOIN vn.saleTracking st ON st.saleFk = s.id + AND st.stateFk = ss.id + WHERE c.workerFk = vWorkerFk + AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge + AND s.quantity + AND s2.order < pc.pendingCollectionsOrder + GROUP BY c.id + HAVING COUNT(*) > COUNT(DISTINCT st.id); - SELECT * FROM tCollection; + SELECT * FROM tmp.collection; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index 09c01d1ef..dad46393d 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -15,6 +15,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY INTO vEndingDate FROM productionConfig; @@ -31,7 +36,8 @@ proc: BEGIN CALL prepareClientList(); CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems - (INDEX (ticketFk)) ENGINE = MEMORY + (INDEX (ticketFk)) + ENGINE = MEMORY SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped FROM tmp.productionTicket tt JOIN ticket t ON t.id = tt.ticketFk; diff --git a/db/routines/vn/procedures/ticket_Clone.sql b/db/routines/vn/procedures/ticket_Clone.sql index 7670e832e..d22d3c7ff 100644 --- a/db/routines/vn/procedures/ticket_Clone.sql +++ b/db/routines/vn/procedures/ticket_Clone.sql @@ -9,6 +9,11 @@ BEGIN */ DECLARE vStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO ticket ( clientFk, shipped, -- 2.40.1 From 897da1e48a70570d6fc172f301b7ac347bc84622 Mon Sep 17 00:00:00 2001 From: robert Date: Thu, 4 Jul 2024 08:59:22 +0200 Subject: [PATCH 364/413] feat: refs #7654 --- .../vn/procedures/entry_splitByShelving.sql | 164 +++++++++--------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index 839bf02d1..eb07c12b7 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -9,81 +9,55 @@ BEGIN * @param vToEntryFk Entrada destino */ DECLARE vBuyFk INT; - DECLARE vIshStickers INT; - DECLARE vBuyStickers INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vIshStickers INT; + DECLARE vBuyStickers INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + + DECLARE cur CURSOR FOR + SELECT bb.id buyFk, + FLOOR(ish.visible / ish.packing) ishStickers, + bb.stickers buyStickers + FROM itemShelving ish + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM buy b + WHERE b.entryFk = vFromEntryFk + ORDER BY b.stickers DESC + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + AND bb.stickers >= FLOOR(ish.visible / ish.packing) + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + AND NOT ish.isSplit + GROUP BY ish.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN cur; + + read_loop: LOOP + SET vDone = FALSE; - DECLARE cur CURSOR FOR - SELECT bb.id buyFk, - FLOOR(ish.visible / ish.packing) ishStickers, - bb.stickers buyStickers - FROM itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM buy b - WHERE b.entryFk = vFromEntryFk - ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - AND bb.stickers >= FLOOR(ish.visible / ish.packing) - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci - AND NOT ish.isSplit - GROUP BY ish.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - OPEN cur; - - read_loop: LOOP - SET vDone = FALSE; - - FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; - - IF vDone THEN - LEAVE read_loop; - END IF; - - IF vIshStickers = vBuyStickers THEN - UPDATE buy - SET entryFk = vToEntryFk - WHERE id = vBuyFk; - ELSE - UPDATE buy - SET stickers = stickers - vIshStickers, - quantity = stickers * packing - WHERE id = vBuyFk; - - INSERT INTO buy(entryFk, - itemFk, - quantity, - buyingValue, - freightValue, - isIgnored, - stickers, - packing, - `grouping`, - groupingMode, - comissionValue, - packageValue, - location, - packagingFk, - price1, - price2, - price3, - minPrice, - workerFk, - isChecked, - isPickedOff, - ektFk, - weight, - deliveryFk, - itemOriginalFk) - SELECT - vToEntryFk, + FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; + + IF vDone THEN + LEAVE read_loop; + END IF; + + IF vIshStickers = vBuyStickers THEN + UPDATE buy + SET entryFk = vToEntryFk + WHERE id = vBuyFk; + ELSE + UPDATE buy + SET stickers = stickers - vIshStickers, + quantity = stickers * packing + WHERE id = vBuyFk; + + INSERT INTO buy(entryFk, itemFk, - vIshStickers * packing, + quantity, buyingValue, freightValue, isIgnored, - vIshStickers, + stickers, packing, `grouping`, groupingMode, @@ -101,17 +75,43 @@ BEGIN ektFk, weight, deliveryFk, - itemOriginalFk - FROM buy - WHERE id = vBuyFk; - - UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); - END IF; - - UPDATE itemShelving - SET isSplit = TRUE - WHERE shelvingFk = vShelvingFk; - END LOOP; - CLOSE cur; + itemOriginalFk) + SELECT + vToEntryFk, + itemFk, + vIshStickers * packing, + buyingValue, + freightValue, + isIgnored, + vIshStickers, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + location, + packagingFk, + price1, + price2, + price3, + minPrice, + workerFk, + isChecked, + isPickedOff, + ektFk, + weight, + deliveryFk, + itemOriginalFk + FROM buy + WHERE id = vBuyFk; + + UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); + END IF; + + UPDATE itemShelving + SET isSplit = TRUE + WHERE shelvingFk = vShelvingFk; + END LOOP; + CLOSE cur; END$$ DELIMITER ; -- 2.40.1 From 009dcd8fc7d3aabf91166752c09dd67749ce8caa Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 09:23:57 +0200 Subject: [PATCH 365/413] refs #7486 Fix tests --- db/dump/.dump/structure.sql | 3404 +++++++++++++++++------------------ 1 file changed, 1702 insertions(+), 1702 deletions(-) diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index cd5b6aa3b..6797c01a5 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -3109,55 +3109,55 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); - - DELETE FROM analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO analisis_ventas ( - Familia, - Reino, - Comercial, - Comprador, - Provincia, - almacen, - Año, - Mes, - Semana, - Vista, - Importe - ) - SELECT - it.name, - ic.name, - w.code, - w2.code, - p.name, - wa.name, - tm.year, - tm.month, - tm.week, - dm.description, - bt.importe - FROM bs.ventas bt - LEFT JOIN vn.itemType it ON it.id = bt.tipo_id - LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN vn.client c on c.id = bt.Id_Cliente - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.worker w2 ON w2.id = it.workerFk - JOIN vn.time tm ON tm.dated = bt.fecha - JOIN vn.sale s ON s.id = bt.Id_Movimiento - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - LEFT JOIN vn.address a ON a.id = t.addressFk - LEFT JOIN vn.province p ON p.id = a.provinceFk - LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk - WHERE bt.fecha >= vLastMonth AND ic.merchandise; +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + it.name, + ic.name, + w.code, + w2.code, + p.name, + wa.name, + tm.year, + tm.month, + tm.week, + dm.description, + bt.importe + FROM bs.ventas bt + LEFT JOIN vn.itemType it ON it.id = bt.tipo_id + LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN vn.client c on c.id = bt.Id_Cliente + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.worker w2 ON w2.id = it.workerFk + JOIN vn.time tm ON tm.dated = bt.fecha + JOIN vn.sale s ON s.id = bt.Id_Movimiento + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + LEFT JOIN vn.address a ON a.id = t.addressFk + LEFT JOIN vn.province p ON p.id = a.provinceFk + LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk + WHERE bt.fecha >= vLastMonth AND ic.merchandise; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3355,21 +3355,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); - - DELETE FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - - DELETE FROM bi.defaulters WHERE `date` < vDateLong; - DELETE FROM bi.defaulting WHERE `date` < vDateLong; +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3558,18 +3558,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bs.clientAnnualConsumption; - - REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) - SELECT clientFk, avg(Facturacion) - FROM ( - SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion - FROM vn.invoiceOut - WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bs.clientAnnualConsumption; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4934,29 +4934,29 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en la tabla @bs.carteras las ventas desde el año pasado - * agrupadas por trabajador, año y mes - */ - DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; - - DELETE FROM bs.carteras WHERE Año >= vYear; - - CALL util.time_generate( - MAKEDATE(vYear, 1), - (SELECT MAX(fecha) FROM ventas) - ); - - INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) - SELECT t.`year`, t.`month`, w.code, SUM(v.importe) - FROM tmp.time t - JOIN ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - GROUP BY w.code, t.`year`, t.`month`; - - DROP TEMPORARY TABLE tmp.time; +BEGIN +/** + * Inserta en la tabla @bs.carteras las ventas desde el año pasado + * agrupadas por trabajador, año y mes + */ + DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; + + DELETE FROM bs.carteras WHERE Año >= vYear; + + CALL util.time_generate( + MAKEDATE(vYear, 1), + (SELECT MAX(fecha) FROM ventas) + ); + + INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) + SELECT t.`year`, t.`month`, w.code, SUM(v.importe) + FROM tmp.time t + JOIN ventas v on t.dated = v.fecha + JOIN vn.client c on c.id = v.Id_Cliente + JOIN vn.worker w ON w.id = c.salesPersonFk + GROUP BY w.code, t.`year`, t.`month`; + + DROP TEMPORARY TABLE tmp.time; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5881,82 +5881,82 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `nightTask_launchAll`() -BEGIN -/** - * Runs all nightly tasks. - */ - DECLARE vDone BOOL; - DECLARE vError VARCHAR(255); - DECLARE vErrorCode VARCHAR(255); - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vLogMail VARCHAR(255); - DECLARE vNightTaskFk INT; - - DECLARE vQueue CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask - WHERE finished <= util.VN_CURDATE() - OR finished IS NULL - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SET max_sp_recursion_depth = 3; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - OPEN vQueue; - l: LOOP - SET vDone = FALSE; - FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; - - IF vDone THEN - LEAVE l; - END IF; - - UPDATE nightTask - SET `started` = util.VN_NOW(), - `finished` = NULL, - `error` = NULL, - `errorCode` = NULL - WHERE id = vNightTaskFk; - - SET vError = NULL; - CALL nightTask_launchTask( - vSchema, - vProcedure, - vError, - vErrorCode - ); - - IF vError IS NOT NULL THEN - IF vLogMail IS NOT NULL THEN - CALL vn.mail_insert( - vLogMail, - NULL, - CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), - CONCAT( - '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break - 'See ', SCHEMA(), '.nightTask table for more info.' - ) - ); - END IF; - - UPDATE nightTask - SET `error` = vError, - `errorCode` = vErrorCode - WHERE id = vNightTaskFk; - ELSE - UPDATE nightTask - SET finished = util.VN_NOW(), - lastFinished = util.VN_NOW() - WHERE id = vNightTaskFk; - END IF; - END LOOP; - CLOSE vQueue; +BEGIN +/** + * Runs all nightly tasks. + */ + DECLARE vDone BOOL; + DECLARE vError VARCHAR(255); + DECLARE vErrorCode VARCHAR(255); + DECLARE vSchema VARCHAR(255); + DECLARE vProcedure VARCHAR(255); + DECLARE vLogMail VARCHAR(255); + DECLARE vNightTaskFk INT; + + DECLARE vQueue CURSOR FOR + SELECT id, `schema`, `procedure` + FROM nightTask + WHERE finished <= util.VN_CURDATE() + OR finished IS NULL + ORDER BY `order`; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET max_sp_recursion_depth = 3; + + SELECT logMail INTO vLogMail + FROM nightTaskConfig LIMIT 1; + + OPEN vQueue; + l: LOOP + SET vDone = FALSE; + FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE nightTask + SET `started` = util.VN_NOW(), + `finished` = NULL, + `error` = NULL, + `errorCode` = NULL + WHERE id = vNightTaskFk; + + SET vError = NULL; + CALL nightTask_launchTask( + vSchema, + vProcedure, + vError, + vErrorCode + ); + + IF vError IS NOT NULL THEN + IF vLogMail IS NOT NULL THEN + CALL vn.mail_insert( + vLogMail, + NULL, + CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), + CONCAT( + '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break + 'See ', SCHEMA(), '.nightTask table for more info.' + ) + ); + END IF; + + UPDATE nightTask + SET `error` = vError, + `errorCode` = vErrorCode + WHERE id = vNightTaskFk; + ELSE + UPDATE nightTask + SET finished = util.VN_NOW(), + lastFinished = util.VN_NOW() + WHERE id = vNightTaskFk; + END IF; + END LOOP; + CLOSE vQueue; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6336,8 +6336,8 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`() -BEGIN - CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); +BEGIN + CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7589,27 +7589,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7627,89 +7627,89 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - DECLARE vLastRefresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires, ca.last_refresh - INTO v_cache_id, v_calc, v_expires, vLastRefresh - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + DECLARE vLastRefresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires, ca.last_refresh + INTO v_cache_id, v_calc, v_expires, vLastRefresh + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10228,524 +10228,524 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`() -proc: BEGIN - DECLARE vLanded DATETIME; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vFreeId INT; - DECLARE vSupplyResponseFk INT; - DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; - DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; - DECLARE vDayRange INT; - - DECLARE cur1 CURSOR FOR - SELECT id - FROM edi.item_free; - - DECLARE cur2 CURSOR FOR - SELECT srId - FROM itemToInsert; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); - SET @isTriggerDisabled = FALSE; - RESIGNAL; - END; - - IF 'test' = (SELECT environment FROM util.config) THEN - LEAVE proc; - END IF; - - IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN - LEAVE proc; - END IF; - - SELECT dayRange INTO vDayRange - FROM offerRefreshConfig; - - IF vDayRange IS NULL THEN - CALL util.throw("Variable vDayRange not declared"); - END IF; - - SET vStartingTime = util.VN_NOW(); - - TRUNCATE edi.offerList; - - INSERT INTO edi.offerList(supplier, total) - SELECT v.name, COUNT(DISTINCT sr.ID) total - FROM edi.supplyResponse sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE sr.NumberOfUnits > 0 - AND sr.EmbalageCode != 999 - GROUP BY sr.vmpID; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(*) total - FROM edi.supplyOffer sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.`filter` = sub.total; - - -- Elimina de la lista de items libres aquellos que ya existen - DELETE itf.* - FROM edi.item_free itf - JOIN vn.item i ON i.id = itf.id; - - CREATE OR REPLACE TEMPORARY TABLE tmp - (INDEX (`Item_ArticleCode`)) - ENGINE = MEMORY - SELECT t.* - FROM ( - SELECT * - FROM edi.supplyOffer - ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, - NumberOfUnits DESC LIMIT 10000000000000000000) t - GROUP BY t.srId; - - CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), - INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), - INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) - ENGINE = MEMORY - SELECT so.*, - ev1.type_description s1Value, - ev2.type_description s2Value, - ev3.type_description s3Value, - ev4.type_description s4Value, - ev5.type_description s5Value, - ev6.type_description s6Value, - eif1.feature ef1, - eif2.feature ef2, - eif3.feature ef3, - eif4.feature ef4, - eif5.feature ef5, - eif6.feature ef6 - FROM tmp so - LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode - AND eif1.presentation_order = 1 - AND eif1.expiry_date IS NULL - LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode - AND eif2.presentation_order = 2 - AND eif2.expiry_date IS NULL - LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode - AND eif3.presentation_order = 3 - AND eif3.expiry_date IS NULL - LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode - AND eif4.presentation_order = 4 - AND eif4.expiry_date IS NULL - LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode - AND eif5.presentation_order = 5 - AND eif5.expiry_date IS NULL - LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode - AND eif6.presentation_order = 6 - AND eif6.expiry_date IS NULL - LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature - AND so.s1 = ev1.type_value - LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature - AND so.s2 = ev2.type_value - LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature - AND so.s3 = ev3.type_value - LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature - AND so.s4 = ev4.type_value - LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature - AND so.s5 = ev5.type_value - LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature - AND so.s6 = ev6.type_value - ORDER BY Price; - - DROP TEMPORARY TABLE tmp; - - DELETE o - FROM edi.offer o - LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' - LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' - LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' - LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' - LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' - LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' - JOIN vn.floramondoConfig fc ON TRUE - WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) - OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) - OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) - OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) - OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) - OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); - - START TRANSACTION; - - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos - UPDATE IGNORE edi.offer o - JOIN vn.item i - ON i.name = o.product_name - AND i.subname <=> o.company_name - AND i.value5 <=> o.s1Value - AND i.value6 <=> o.s2Value - AND i.value7 <=> o.s3Value - AND i.value8 <=> o.s4Value - AND i.value9 <=> o.s5Value - AND i.value10 <=> o.s6Value - AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask - AND i.EmbalageCode <=> o.EmbalageCode - AND i.quality <=> o.Quality - JOIN vn.itemType it ON it.id = i.typeFk - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) - LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk - AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) - SET i.supplyResponseFk = o.srID - WHERE (sr.ID IS NULL - OR sr.NumberOfUnits = 0 - OR di.LatestOrderDateTime < util.VN_NOW() - OR di.ID IS NULL) - AND it.isInventory - AND t.id IS NULL - AND po.id IS NULL; - - CREATE OR REPLACE TEMPORARY TABLE itemToInsert - ENGINE = MEMORY - SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk - FROM edi.offer o - LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId - WHERE i.id IS NULL - LIMIT vMaxNewItems; - - -- Reciclado de nº de item - OPEN cur1; - OPEN cur2; - - read_loop: LOOP - - FETCH cur2 INTO vSupplyResponseFk; - FETCH cur1 INTO vFreeId; - - IF vDone THEN - LEAVE read_loop; - END IF; - - UPDATE itemToInsert - SET itemFk = vFreeId - WHERE srId = vSupplyResponseFk; - - END LOOP; - - CLOSE cur1; - CLOSE cur2; - - -- Insertamos todos los items en Articles de la oferta - INSERT INTO vn.item(id, - `name`, - longName, - subName, - expenseFk, - typeFk, - intrastatFk, - originFk, - supplyResponseFk, - numberOfItemsPerCask, - embalageCode, - quality, - isFloramondo) - SELECT iti.itemFk, - iti.product_name, - iti.product_name, - iti.company_name, - iti.expenseFk, - iti.itemTypeFk, - iti.intrastatFk, - iti.originFk, - iti.`srId`, - iti.NumberOfItemsPerCask, - iti.EmbalageCode, - iti.Quality, - TRUE - FROM itemToInsert iti; - - -- Inserta la foto de los articulos nuevos (prioridad alta) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) - SELECT i.id, PictureReference - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.srId - WHERE PictureReference IS NOT NULL - AND i.image IS NULL; - - INSERT INTO edi.`log`(tableName, fieldName,fieldValue) - SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) - FROM vn.itemImageQueue - WHERE attempts = 0; - - -- Inserta si se añadiesen tags nuevos - INSERT IGNORE INTO vn.tag (name, ediTypeFk) - SELECT description, type_id FROM edi.type; - - -- Desabilita el trigger para recalcular los tags al final - SET @isTriggerDisabled = TRUE; - - -- Inserta los tags sólo en los articulos nuevos - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.product_name, 1 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Producto' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.product_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.Quality, 3 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Calidad' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.Quality IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.company_name, 4 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Productor' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.company_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s1Value, 5 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef1 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s1Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s2Value, 6 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef2 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s2Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s3Value, 7 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef3 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s3Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s4Value, 8 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef4 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s4Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s5Value, 9 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef5 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s5Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s6Value, 10 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef6 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s6Value IS NULL; - - INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id - AND tp.`description` = 'Hoofdkleur 1' - LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value - LEFT JOIN vn.itemInk ik ON ik.longName = i.longName - WHERE ink.name IS NOT NULL - OR ik.color IS NOT NULL; - - CREATE OR REPLACE TABLE tmp.item - (PRIMARY KEY (id)) - SELECT i.id FROM vn.item i - JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; - - CALL vn.item_refreshTags(); - - DROP TABLE tmp.item; - - SELECT MIN(LatestDeliveryDateTime) INTO vLanded - FROM edi.supplyResponse sr - JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.floramondoConfig fc - WHERE mp.isLatestOrderDateTimeRelevant - AND di.LatestOrderDateTime > IF( - fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), - util.VN_CURDATE(), - util.VN_CURDATE() + INTERVAL 1 DAY); - - UPDATE vn.floramondoConfig - SET nextLanded = vLanded - WHERE vLanded IS NOT NULL; - - -- Elimina la oferta obsoleta - UPDATE vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID - LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk - SET b.quantity = 0 - WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() - OR i.supplyResponseFk IS NULL - OR sr.NumberOfUnits = 0) - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - -- Localiza las entradas de cada almacen - UPDATE edi.warehouseFloramondo - SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); - - IF vLanded IS NOT NULL THEN - -- Actualiza la oferta existente - UPDATE vn.buy b - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.offer o ON i.supplyResponseFk = o.`srId` - SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, - b.buyingValue = o.price - WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask - OR b.buyingValue <> o.price); - - -- Inserta el resto - SET vLastInserted := util.VN_NOW(); - - -- Inserta la oferta - INSERT INTO vn.buy ( - entryFk, - itemFk, - quantity, - buyingValue, - stickers, - packing, - `grouping`, - groupingMode, - packagingFk, - deliveryFk) - SELECT wf.entryFk, - i.id, - o.NumberOfUnits * o.NumberOfItemsPerCask quantity, - o.Price, - o.NumberOfUnits etiquetas, - o.NumberOfItemsPerCask packing, - GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, - 'packing', - o.embalageCode, - o.diId - FROM edi.offer o - JOIN vn.item i ON i.supplyResponseFk = o.srId - JOIN edi.warehouseFloramondo wf - JOIN vn.packaging p ON p.id - LIKE o.embalageCode - LEFT JOIN vn.buy b ON b.itemFk = i.id - AND b.entryFk = wf.entryFk - WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL - - INSERT INTO vn.itemCost( - itemFk, - warehouseFk, - cm3, - cm3delivery) - SELECT b.itemFk, - wf.warehouseFk, - @cm3 := vn.buy_getUnitVolume(b.id), - IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) - FROM warehouseFloramondo wf - JOIN vn.volumeConfig vc - JOIN vn.buy b ON b.entryFk = wf.entryFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk - AND ic.warehouseFk = wf.warehouseFk - WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) - ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); - - CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc - SELECT b.id - FROM vn.buy b - JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk - WHERE b.created >= vLastInserted; - - CALL vn.buy_recalcPrices(); - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'VNH' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.vnh = sub.total; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'ALGEMESI' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.algemesi = sub.total; - END IF; - - DROP TEMPORARY TABLE - edi.offer, - itemToInsert; - - SET @isTriggerDisabled = FALSE; - - COMMIT; - - -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias - UPDATE vn.item i - SET typeFk = 121 - WHERE i.longName LIKE 'Rosa Garden %' - AND typeFk = 17; - - UPDATE vn.item i - SET typeFk = 156 - WHERE i.longName LIKE 'Rosa ec %' - AND typeFk = 17; - - -- Refresca las fotos de los items existentes que mostramos (prioridad baja) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) - SELECT i.id, sr.PictureReference, 100 - FROM edi.supplyResponse sr - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN edi.supplyOffer so ON so.srId = sr.ID - JOIN hedera.image i2 ON i2.name = i.image - AND i2.collectionFk = 'catalog' - WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) - AND sr.NumberOfUnits; - - INSERT INTO edi.`log` - SET tableName = 'floramondo_offerRefresh', - fieldName = 'Tiempo de proceso', - fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); - - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); +proc: BEGIN + DECLARE vLanded DATETIME; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vFreeId INT; + DECLARE vSupplyResponseFk INT; + DECLARE vLastInserted DATETIME; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vStartingTime DATETIME; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vDayRange INT; + + DECLARE cur1 CURSOR FOR + SELECT id + FROM edi.item_free; + + DECLARE cur2 CURSOR FOR + SELECT srId + FROM itemToInsert; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); + SET @isTriggerDisabled = FALSE; + RESIGNAL; + END; + + IF 'test' = (SELECT environment FROM util.config) THEN + LEAVE proc; + END IF; + + IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN + LEAVE proc; + END IF; + + SELECT dayRange INTO vDayRange + FROM offerRefreshConfig; + + IF vDayRange IS NULL THEN + CALL util.throw("Variable vDayRange not declared"); + END IF; + + SET vStartingTime = util.VN_NOW(); + + TRUNCATE edi.offerList; + + INSERT INTO edi.offerList(supplier, total) + SELECT v.name, COUNT(DISTINCT sr.ID) total + FROM edi.supplyResponse sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + WHERE sr.NumberOfUnits > 0 + AND sr.EmbalageCode != 999 + GROUP BY sr.vmpID; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(*) total + FROM edi.supplyOffer sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.`filter` = sub.total; + + -- Elimina de la lista de items libres aquellos que ya existen + DELETE itf.* + FROM edi.item_free itf + JOIN vn.item i ON i.id = itf.id; + + CREATE OR REPLACE TEMPORARY TABLE tmp + (INDEX (`Item_ArticleCode`)) + ENGINE = MEMORY + SELECT t.* + FROM ( + SELECT * + FROM edi.supplyOffer + ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, + NumberOfUnits DESC LIMIT 10000000000000000000) t + GROUP BY t.srId; + + CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), + INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), + INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) + ENGINE = MEMORY + SELECT so.*, + ev1.type_description s1Value, + ev2.type_description s2Value, + ev3.type_description s3Value, + ev4.type_description s4Value, + ev5.type_description s5Value, + ev6.type_description s6Value, + eif1.feature ef1, + eif2.feature ef2, + eif3.feature ef3, + eif4.feature ef4, + eif5.feature ef5, + eif6.feature ef6 + FROM tmp so + LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode + AND eif1.presentation_order = 1 + AND eif1.expiry_date IS NULL + LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode + AND eif2.presentation_order = 2 + AND eif2.expiry_date IS NULL + LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode + AND eif3.presentation_order = 3 + AND eif3.expiry_date IS NULL + LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode + AND eif4.presentation_order = 4 + AND eif4.expiry_date IS NULL + LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode + AND eif5.presentation_order = 5 + AND eif5.expiry_date IS NULL + LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode + AND eif6.presentation_order = 6 + AND eif6.expiry_date IS NULL + LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature + AND so.s1 = ev1.type_value + LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature + AND so.s2 = ev2.type_value + LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature + AND so.s3 = ev3.type_value + LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature + AND so.s4 = ev4.type_value + LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature + AND so.s5 = ev5.type_value + LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature + AND so.s6 = ev6.type_value + ORDER BY Price; + + DROP TEMPORARY TABLE tmp; + + DELETE o + FROM edi.offer o + LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' + LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' + LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' + LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' + LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' + LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' + JOIN vn.floramondoConfig fc ON TRUE + WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) + OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) + OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) + OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) + OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) + OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); + + START TRANSACTION; + + -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos + UPDATE IGNORE edi.offer o + JOIN vn.item i + ON i.name = o.product_name + AND i.subname <=> o.company_name + AND i.value5 <=> o.s1Value + AND i.value6 <=> o.s2Value + AND i.value7 <=> o.s3Value + AND i.value8 <=> o.s4Value + AND i.value9 <=> o.s5Value + AND i.value10 <=> o.s6Value + AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask + AND i.EmbalageCode <=> o.EmbalageCode + AND i.quality <=> o.Quality + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) + LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk + AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) + SET i.supplyResponseFk = o.srID + WHERE (sr.ID IS NULL + OR sr.NumberOfUnits = 0 + OR di.LatestOrderDateTime < util.VN_NOW() + OR di.ID IS NULL) + AND it.isInventory + AND t.id IS NULL + AND po.id IS NULL; + + CREATE OR REPLACE TEMPORARY TABLE itemToInsert + ENGINE = MEMORY + SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk + FROM edi.offer o + LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId + WHERE i.id IS NULL + LIMIT vMaxNewItems; + + -- Reciclado de nº de item + OPEN cur1; + OPEN cur2; + + read_loop: LOOP + + FETCH cur2 INTO vSupplyResponseFk; + FETCH cur1 INTO vFreeId; + + IF vDone THEN + LEAVE read_loop; + END IF; + + UPDATE itemToInsert + SET itemFk = vFreeId + WHERE srId = vSupplyResponseFk; + + END LOOP; + + CLOSE cur1; + CLOSE cur2; + + -- Insertamos todos los items en Articles de la oferta + INSERT INTO vn.item(id, + `name`, + longName, + subName, + expenseFk, + typeFk, + intrastatFk, + originFk, + supplyResponseFk, + numberOfItemsPerCask, + embalageCode, + quality, + isFloramondo) + SELECT iti.itemFk, + iti.product_name, + iti.product_name, + iti.company_name, + iti.expenseFk, + iti.itemTypeFk, + iti.intrastatFk, + iti.originFk, + iti.`srId`, + iti.NumberOfItemsPerCask, + iti.EmbalageCode, + iti.Quality, + TRUE + FROM itemToInsert iti; + + -- Inserta la foto de los articulos nuevos (prioridad alta) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) + SELECT i.id, PictureReference + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.srId + WHERE PictureReference IS NOT NULL + AND i.image IS NULL; + + INSERT INTO edi.`log`(tableName, fieldName,fieldValue) + SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) + FROM vn.itemImageQueue + WHERE attempts = 0; + + -- Inserta si se añadiesen tags nuevos + INSERT IGNORE INTO vn.tag (name, ediTypeFk) + SELECT description, type_id FROM edi.type; + + -- Desabilita el trigger para recalcular los tags al final + SET @isTriggerDisabled = TRUE; + + -- Inserta los tags sólo en los articulos nuevos + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.product_name, 1 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Producto' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.product_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.Quality, 3 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Calidad' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.Quality IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.company_name, 4 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Productor' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.company_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s1Value, 5 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef1 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s1Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s2Value, 6 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef2 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s2Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s3Value, 7 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef3 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s3Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s4Value, 8 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef4 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s4Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s5Value, 9 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef5 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s5Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s6Value, 10 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef6 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s6Value IS NULL; + + INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + JOIN vn.tag t ON t.`name` = 'Color' + LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode + LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id + AND tp.`description` = 'Hoofdkleur 1' + LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value + LEFT JOIN vn.itemInk ik ON ik.longName = i.longName + WHERE ink.name IS NOT NULL + OR ik.color IS NOT NULL; + + CREATE OR REPLACE TABLE tmp.item + (PRIMARY KEY (id)) + SELECT i.id FROM vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; + + CALL vn.item_refreshTags(); + + DROP TABLE tmp.item; + + SELECT MIN(LatestDeliveryDateTime) INTO vLanded + FROM edi.supplyResponse sr + JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.floramondoConfig fc + WHERE mp.isLatestOrderDateTimeRelevant + AND di.LatestOrderDateTime > IF( + fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), + util.VN_CURDATE(), + util.VN_CURDATE() + INTERVAL 1 DAY); + + UPDATE vn.floramondoConfig + SET nextLanded = vLanded + WHERE vLanded IS NOT NULL; + + -- Elimina la oferta obsoleta + UPDATE vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID + LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk + SET b.quantity = 0 + WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() + OR i.supplyResponseFk IS NULL + OR sr.NumberOfUnits = 0) + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + -- Localiza las entradas de cada almacen + UPDATE edi.warehouseFloramondo + SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); + + IF vLanded IS NOT NULL THEN + -- Actualiza la oferta existente + UPDATE vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, + b.buyingValue = o.price + WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask + OR b.buyingValue <> o.price); + + -- Inserta el resto + SET vLastInserted := util.VN_NOW(); + + -- Inserta la oferta + INSERT INTO vn.buy ( + entryFk, + itemFk, + quantity, + buyingValue, + stickers, + packing, + `grouping`, + groupingMode, + packagingFk, + deliveryFk) + SELECT wf.entryFk, + i.id, + o.NumberOfUnits * o.NumberOfItemsPerCask quantity, + o.Price, + o.NumberOfUnits etiquetas, + o.NumberOfItemsPerCask packing, + GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, + 'packing', + o.embalageCode, + o.diId + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN edi.warehouseFloramondo wf + JOIN vn.packaging p ON p.id + LIKE o.embalageCode + LEFT JOIN vn.buy b ON b.itemFk = i.id + AND b.entryFk = wf.entryFk + WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL + + INSERT INTO vn.itemCost( + itemFk, + warehouseFk, + cm3, + cm3delivery) + SELECT b.itemFk, + wf.warehouseFk, + @cm3 := vn.buy_getUnitVolume(b.id), + IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) + FROM warehouseFloramondo wf + JOIN vn.volumeConfig vc + JOIN vn.buy b ON b.entryFk = wf.entryFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk + AND ic.warehouseFk = wf.warehouseFk + WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) + ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); + + CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc + SELECT b.id + FROM vn.buy b + JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk + WHERE b.created >= vLastInserted; + + CALL vn.buy_recalcPrices(); + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'VNH' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.vnh = sub.total; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.algemesi = sub.total; + END IF; + + DROP TEMPORARY TABLE + edi.offer, + itemToInsert; + + SET @isTriggerDisabled = FALSE; + + COMMIT; + + -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias + UPDATE vn.item i + SET typeFk = 121 + WHERE i.longName LIKE 'Rosa Garden %' + AND typeFk = 17; + + UPDATE vn.item i + SET typeFk = 156 + WHERE i.longName LIKE 'Rosa ec %' + AND typeFk = 17; + + -- Refresca las fotos de los items existentes que mostramos (prioridad baja) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) + SELECT i.id, sr.PictureReference, 100 + FROM edi.supplyResponse sr + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN edi.supplyOffer so ON so.srId = sr.ID + JOIN hedera.image i2 ON i2.name = i.image + AND i2.collectionFk = 'catalog' + WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) + AND sr.NumberOfUnits; + + INSERT INTO edi.`log` + SET tableName = 'floramondo_offerRefresh', + fieldName = 'Tiempo de proceso', + fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); + + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11324,28 +11324,28 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( - vName VARCHAR(100), - vPhone VARCHAR(15), - vEmail VARCHAR(100), +CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( + vName VARCHAR(100), + vPhone VARCHAR(15), + vEmail VARCHAR(100), vMessage TEXT) READS SQL DATA -BEGIN -/** - * Set actions for contact request - * - * @param vName Name - * @param vPhone Phone number - * @param vEmail e-mail - * @param vMessage text of the message - */ - - CALL vn.mail_insert( - 'floranet@verdnatura.es', - vEmail, - 'Contact request', - CONCAT('Phone: ',vPhone, ' Message: ', vMessage) - ); +BEGIN +/** + * Set actions for contact request + * + * @param vName Name + * @param vPhone Phone number + * @param vEmail e-mail + * @param vMessage text of the message + */ + + CALL vn.mail_insert( + 'floranet@verdnatura.es', + vEmail, + 'Contact request', + CONCAT('Phone: ',vPhone, ' Message: ', vMessage) + ); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11364,27 +11364,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryDate_get`(vPostalCode VARCHAR(15)) READS SQL DATA -BEGIN -/** - * Returns available dates for this postalCode, in the next seven days. - * - * @param vPostalCode Delivery address postal code - */ - DECLARE vCurrentDayOfWeek INT; - - SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); - - SELECT DISTINCT nextDay - FROM ( - SELECT CURDATE() + INTERVAL IF( - apc.dayOfWeek >= vCurrentDayOfWeek, - apc.dayOfWeek - vCurrentDayOfWeek, - 7 - apc.dayOfWeek - ) DAY nextDay, - NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime - FROM addressPostCode apc - WHERE apc.postCode = vPostalCode - HAVING nextDay > minDeliveryTime) sub; +BEGIN +/** + * Returns available dates for this postalCode, in the next seven days. + * + * @param vPostalCode Delivery address postal code + */ + DECLARE vCurrentDayOfWeek INT; + + SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); + + SELECT DISTINCT nextDay + FROM ( + SELECT CURDATE() + INTERVAL IF( + apc.dayOfWeek >= vCurrentDayOfWeek, + apc.dayOfWeek - vCurrentDayOfWeek, + 7 - apc.dayOfWeek + ) DAY nextDay, + NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime + FROM addressPostCode apc + WHERE apc.postCode = vPostalCode + HAVING nextDay > minDeliveryTime) sub; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41995,9 +41995,9 @@ DELIMITER ;; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN - DELETE FROM itemImageQueue - WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN + DELETE FROM itemImageQueue + WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -42689,37 +42689,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `client_getDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2) READS SQL DATA -BEGIN -/** - * Returns the risk of a customer. - * - * @param vClient client id - * @param vDate date to check the risk - * @return Client risk - */ - DECLARE vDebt DECIMAL(10,2); - DECLARE vHasDebt BOOLEAN; - - SELECT COUNT(*) INTO vHasDebt - FROM `client` c - WHERE c.id = vClient AND c.typeFk = 'normal'; - - IF NOT vHasDebt THEN - RETURN 0; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); - INSERT INTO tmp.clientGetDebt SET clientFk = vClient; - - CALL vn.client_getDebt(vDate); - - SELECT risk INTO vDebt FROM tmp.risk; - - DROP TEMPORARY TABLE - tmp.clientGetDebt, - tmp.risk; - - RETURN vDebt; +BEGIN +/** + * Returns the risk of a customer. + * + * @param vClient client id + * @param vDate date to check the risk + * @return Client risk + */ + DECLARE vDebt DECIMAL(10,2); + DECLARE vHasDebt BOOLEAN; + + SELECT COUNT(*) INTO vHasDebt + FROM `client` c + WHERE c.id = vClient AND c.typeFk = 'normal'; + + IF NOT vHasDebt THEN + RETURN 0; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); + INSERT INTO tmp.clientGetDebt SET clientFk = vClient; + + CALL vn.client_getDebt(vDate); + + SELECT risk INTO vDebt FROM tmp.risk; + + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.risk; + + RETURN vDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43744,8 +43744,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `getInventoryDate`() RETURNS date DETERMINISTIC -BEGIN - RETURN (SELECT inventoried FROM config LIMIT 1); +BEGIN + RETURN (SELECT inventoried FROM config LIMIT 1); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51378,82 +51378,82 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( - vUserFk INT, - OUT vCollectionFk INT +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( + vUserFk INT, + OUT vCollectionFk INT ) -BEGIN -/** - * Comprueba si existen colecciones libres que se ajustan - * al perfil del usuario y le asigna la más antigua. - * Añade un registro al semillero de colecciones. - * - * @param vUserFk Id de usuario - * @param vCollectionFk Id de colección - */ - DECLARE vHasTooMuchCollections BOOL; - - -- Si hay colecciones sin terminar, sale del proceso - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections - FROM productionConfig pc - LEFT JOIN tCollection ON TRUE; - - DROP TEMPORARY TABLE tCollection; - - IF vHasTooMuchCollections THEN - CALL util.throw('Hay colecciones pendientes'); - END IF; - - -- Se eliminan las colecciones sin asignar que estan obsoletas - INSERT INTO ticketTracking(stateFk, ticketFk) - SELECT s.id, tc.ticketFk - FROM `collection` c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN `state` s ON s.code = 'PRINTED_AUTO' - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - DELETE c.* - FROM `collection` c - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - INSERT INTO collectionHotbed(userFk) - VALUES(vUserFk); - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) INTO vCollectionFk - FROM `collection` c - JOIN operator o - ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk - AND c.workerFk IS NULL - AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) - JOIN ( - SELECT tc.collectionFk, SUM(sv.volume) volume - FROM ticketCollection tc - JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk - WHERE sv.shipped >= util.VN_CURDATE() - GROUP BY tc.collectionFk - ) sub ON sub.collectionFk = c.id - AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) - WHERE o.workerFk = vUserFk; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - END IF; - - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan + * al perfil del usuario y le asigna la más antigua. + * Añade un registro al semillero de colecciones. + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 + INTO vHasTooMuchCollections + FROM productionConfig pc + LEFT JOIN tmp.collection ON TRUE; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('Hay colecciones pendientes'); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM `collection` c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN `state` s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c.* + FROM `collection` c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed(userFk) + VALUES(vUserFk); + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM `collection` c + JOIN operator o + ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + JOIN ( + SELECT tc.collectionFk, SUM(sv.volume) volume + FROM ticketCollection tc + JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) sub ON sub.collectionFk = c.id + AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51478,9 +51478,9 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tCollection; + DROP TEMPORARY TABLE IF EXISTS tmp.collection; - CREATE TEMPORARY TABLE tCollection + CREATE TEMPORARY TABLE tmp.collection SELECT c.id collectionFk, date(c.created) created, COUNT(DISTINCT tc.ticketFk) ticketTotalCount @@ -51499,7 +51499,7 @@ BEGIN GROUP BY c.id HAVING COUNT(*) > COUNT(DISTINCT st.id); - SELECT * FROM tCollection; + SELECT * FROM tmp.collection; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60631,167 +60631,167 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) -BEGIN - - /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. - * - * @param vShelvingFk Matrícula del carro o pallet - */ - - DECLARE vWarehouseFk INT; - DECLARE vStockScopeDays INT; - - SELECT s.warehouseFk, stockScopeDays - INTO vWarehouseFk, vStockScopeDays - FROM sector s - JOIN operator o ON s.id = o.sectorFk - JOIN productionConfig pc - WHERE o.workerFk = account.myUser_getId(); - - IF vWarehouseFk IS NULL - THEN CALL util.throw('WarehouseFk not setted'); - END IF; - - IF vStockScopeDays IS NULL - THEN CALL util.throw('StockScopeDays not setted'); - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tItems - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT itemFk, SUM(visible) visible - FROM itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay - (INDEX (itemFk, dated)) - ENGINE = MEMORY - SELECT dated, - SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, - t3.itemFk - FROM ( - SELECT t.itemFk, dated, SUM(amount) amount - FROM ( - SELECT t2.itemFk, t2.amount, t2.dated - FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock s - JOIN tmp.tItems i ON i.itemFk = s.item_id - WHERE s.warehouse_id = vWarehouseFk - UNION ALL - SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() - FROM itemShelving ish - JOIN tmp.tItems i ON i.itemFk = ish.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id - JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve - GROUP BY ish.itemFk - UNION ALL - SELECT iei.itemFk, SUM(quantity), landed - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND iei.warehouseInFk = vWarehouseFk - AND NOT isVirtualStock - GROUP BY iei.itemFk, iei.landed - UNION ALL - SELECT ieo.itemFk, SUM(quantity), shipped - FROM itemEntryOut ieo - JOIN tmp.tItems i ON i.itemFk = ieo.itemFk - WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ieo.warehouseOutFk = vWarehouseFk - GROUP BY ieo.itemFk, ieo.shipped - UNION ALL - SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) - FROM itemTicketOut ito - JOIN tmp.tItems i ON i.itemFk = ito.itemFk - WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ito.warehouseFk = vWarehouseFk - GROUP BY ito.itemFk, ito.shipped - ) t2 - JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t - GROUP BY t.itemFk, dated - ) t3; - - -- Se restan las entradas de hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed = util.VN_CURDATE() - AND iei.warehouseInFk = vWarehouseFk - AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock - sub.todayEntry - WHERE sbd.dated = util.VN_CURDATE(); - - -- Se añaden las lineas de venta servidas - UPDATE tmp.tStockByDay sbd - JOIN (SELECT s.itemFK, SUM(quantity) amount - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - WHERE t.warehouseFk = vWarehouseFk - AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() - AND s.isPicked - GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - -- Se añaden los items ubicados hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT ish.itemFK, SUM(ish.visible) amount - 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 - WHERE s.warehouseFk = vWarehouseFk - AND NOT s.isReserve - AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() - GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - SELECT ts.itemFk, - i.longName, - IF(ts.stock<=0, ts.dated, NULL) dated, - ts.stock, - sub4.visible, - sub4.shelvingFk - FROM( - SELECT IFNULL(sub2.minDated, sub.minDated) dated, - IFNULL(sub2.itemFk, sub.itemFk) itemFk - FROM(SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - GROUP BY itemFk)sub - LEFT JOIN ( - SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - WHERE sbd.stock <= 0 - GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk - WHERE sub2.itemFk IS NOT NULL - OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 - LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated - JOIN (SELECT ish.itemFk, - ish.visible, - p.sectorFk, - ish.shelvingFk - FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN parking p ON p.id = parkingFk - LEFT JOIN vn.sector s ON s.id = p.sectorFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - ) sub4 ON sub4.itemFk = ts.itemFk - LEFT JOIN sector s ON s.id = sub4.sectorFk - LEFT JOIN item i ON i.id = ts.itemFk - WHERE NOT s.isReserve; - - DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; - +BEGIN + + /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. + * + * @param vShelvingFk Matrícula del carro o pallet + */ + + DECLARE vWarehouseFk INT; + DECLARE vStockScopeDays INT; + + SELECT s.warehouseFk, stockScopeDays + INTO vWarehouseFk, vStockScopeDays + FROM sector s + JOIN operator o ON s.id = o.sectorFk + JOIN productionConfig pc + WHERE o.workerFk = account.myUser_getId(); + + IF vWarehouseFk IS NULL + THEN CALL util.throw('WarehouseFk not setted'); + END IF; + + IF vStockScopeDays IS NULL + THEN CALL util.throw('StockScopeDays not setted'); + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tItems + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(visible) visible + FROM itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + GROUP BY itemFk; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay + (INDEX (itemFk, dated)) + ENGINE = MEMORY + SELECT dated, + SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, + t3.itemFk + FROM ( + SELECT t.itemFk, dated, SUM(amount) amount + FROM ( + SELECT t2.itemFk, t2.amount, t2.dated + FROM ( + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock s + JOIN tmp.tItems i ON i.itemFk = s.item_id + WHERE s.warehouse_id = vWarehouseFk + UNION ALL + SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() + FROM itemShelving ish + JOIN tmp.tItems i ON i.itemFk = ish.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id + JOIN sector s ON s.id = p.sectorFk + WHERE s.isReserve + GROUP BY ish.itemFk + UNION ALL + SELECT iei.itemFk, SUM(quantity), landed + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND iei.warehouseInFk = vWarehouseFk + AND NOT isVirtualStock + GROUP BY iei.itemFk, iei.landed + UNION ALL + SELECT ieo.itemFk, SUM(quantity), shipped + FROM itemEntryOut ieo + JOIN tmp.tItems i ON i.itemFk = ieo.itemFk + WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ieo.warehouseOutFk = vWarehouseFk + GROUP BY ieo.itemFk, ieo.shipped + UNION ALL + SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) + FROM itemTicketOut ito + JOIN tmp.tItems i ON i.itemFk = ito.itemFk + WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ito.warehouseFk = vWarehouseFk + GROUP BY ito.itemFk, ito.shipped + ) t2 + JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t + GROUP BY t.itemFk, dated + ) t3; + + -- Se restan las entradas de hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed = util.VN_CURDATE() + AND iei.warehouseInFk = vWarehouseFk + AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock - sub.todayEntry + WHERE sbd.dated = util.VN_CURDATE(); + + -- Se añaden las lineas de venta servidas + UPDATE tmp.tStockByDay sbd + JOIN (SELECT s.itemFK, SUM(quantity) amount + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWarehouseFk + AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() + AND s.isPicked + GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + -- Se añaden los items ubicados hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT ish.itemFK, SUM(ish.visible) amount + 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 + WHERE s.warehouseFk = vWarehouseFk + AND NOT s.isReserve + AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() + GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + SELECT ts.itemFk, + i.longName, + IF(ts.stock<=0, ts.dated, NULL) dated, + ts.stock, + sub4.visible, + sub4.shelvingFk + FROM( + SELECT IFNULL(sub2.minDated, sub.minDated) dated, + IFNULL(sub2.itemFk, sub.itemFk) itemFk + FROM(SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + GROUP BY itemFk)sub + LEFT JOIN ( + SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + WHERE sbd.stock <= 0 + GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk + WHERE sub2.itemFk IS NOT NULL + OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 + LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated + JOIN (SELECT ish.itemFk, + ish.visible, + p.sectorFk, + ish.shelvingFk + FROM itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = parkingFk + LEFT JOIN vn.sector s ON s.id = p.sectorFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + ) sub4 ON sub4.itemFk = ts.itemFk + LEFT JOIN sector s ON s.id = sub4.sectorFk + LEFT JOIN item i ON i.id = ts.itemFk + WHERE NOT s.isReserve; + + DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62333,50 +62333,50 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getAtp`(vDated DATE) -BEGIN -/** - * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y - * almacén. - * - * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 - * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) - * @return tmp.itemAtp(itemFk, warehouseFk, quantity) - */ - CREATE OR REPLACE TEMPORARY TABLE tItemOrdered - (UNIQUE(itemFk, warehouseFk, dated)) - ENGINE = MEMORY - SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity - FROM ( - SELECT itemFk, warehouseFk, dated, quantity - FROM tmp.itemCalc - UNION ALL - SELECT itemFk, warehouseFk, vDated, 0 - FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 - ) t1 - GROUP BY itemFk, warehouseFk, dated - ORDER BY itemFk, warehouseFk, dated; - - SET @lastItemFk := 0; - SET @lastWareHouseFk := 0; - SET @lastQuantity := 0; - - CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp - (INDEX (itemFk, wareHouseFk)) - SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity - FROM ( - SELECT - itemFk, - IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, - @lastQuantity := quantity, - @lastQuantity := @lastQuantity + quantity) quantityAccumulated, - wareHouseFk, - @lastItemFk := itemFk, - @lastWareHouseFk := wareHouseFk - FROM tItemOrdered - )sub - GROUP BY itemFk, wareHouseFk; - - DROP TEMPORARY TABLE tItemOrdered; +BEGIN +/** + * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y + * almacén. + * + * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 + * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) + * @return tmp.itemAtp(itemFk, warehouseFk, quantity) + */ + CREATE OR REPLACE TEMPORARY TABLE tItemOrdered + (UNIQUE(itemFk, warehouseFk, dated)) + ENGINE = MEMORY + SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity + FROM ( + SELECT itemFk, warehouseFk, dated, quantity + FROM tmp.itemCalc + UNION ALL + SELECT itemFk, warehouseFk, vDated, 0 + FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 + ) t1 + GROUP BY itemFk, warehouseFk, dated + ORDER BY itemFk, warehouseFk, dated; + + SET @lastItemFk := 0; + SET @lastWareHouseFk := 0; + SET @lastQuantity := 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp + (INDEX (itemFk, wareHouseFk)) + SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity + FROM ( + SELECT + itemFk, + IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, + @lastQuantity := quantity, + @lastQuantity := @lastQuantity + quantity) quantityAccumulated, + wareHouseFk, + @lastItemFk := itemFk, + @lastWareHouseFk := wareHouseFk + FROM tItemOrdered + )sub + GROUP BY itemFk, wareHouseFk; + + DROP TEMPORARY TABLE tItemOrdered; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64541,197 +64541,197 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( - vDate DATE, - vWarehouseFk TINYINT, - vMaxDays TINYINT +CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( + vDate DATE, + vWarehouseFk TINYINT, + vMaxDays TINYINT ) -proc: BEGIN - DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; - DECLARE vDateFrom DATE DEFAULT vDate; - DECLARE vDateTo DATETIME; - DECLARE vDateToTomorrow DATETIME; - DECLARE vDefaultDayRange INT; - - IF vDate < util.VN_CURDATE() THEN - LEAVE proc; - END IF; - - IF vDate = util.VN_CURDATE() THEN - SELECT inventoried INTO vDateFrom - FROM config; - END IF; - - SELECT defaultDayRange INTO vDefaultDayRange - FROM comparativeConfig; - - SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; - SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; - - ALTER TABLE tmp.itemInventory - ADD `avalaible` INT NOT NULL, - ADD `sd` INT NOT NULL, - ADD `rest` INT NOT NULL, - ADD `expected` INT NOT NULL, - ADD `inventory` INT NOT NULL, - ADD `visible` INT NOT NULL, - ADD `life` TINYINT NOT NULL DEFAULT '0'; - - -- Calculo del inventario - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.inventory = sub.Subtotal, - ai.visible = sub.Subtotal, - ai.avalaible = sub.Subtotal, - ai.sd = sub.Subtotal; - - -- Cálculo del visible - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.visible = ai.visible + sub.Subtotal; - - -- Calculo del disponible - CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT sub.itemFk, - vWarehouseFk warehouseFk, - sub.dated, - SUM(sub.quantity) quantity - FROM ( - SELECT s.itemFk, - DATE(t.shipped) dated, - - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, t.landed, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, t.shipped, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub - GROUP BY sub.itemFk, sub.dated; - - CALL item_getAtp(vDate); - CALL travel_upcomingArrivals(vWarehouseFk, vDate); - - UPDATE tmp.itemInventory ai - JOIN ( - SELECT it.itemFk, - SUM(it.quantity) quantity, - im.quantity minQuantity - FROM tmp.itemCalc it - JOIN tmp.itemAtp im ON im.itemFk = it.itemFk - JOIN item i ON i.id = it.itemFk - LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk - WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, - t.landing, - vDateToTomorrow) - GROUP BY it.itemFk - ) sub ON sub.itemFk = ai.id - SET ai.avalaible = IF(sub.minQuantity > 0, - ai.avalaible, - ai.avalaible + sub.minQuantity), - ai.sd = ai.inventory + sub.quantity; - - DROP TEMPORARY TABLE - tmp.itemTravel, - tmp.itemCalc, - tmp.itemAtp; +proc: BEGIN + DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; + DECLARE vDateFrom DATE DEFAULT vDate; + DECLARE vDateTo DATETIME; + DECLARE vDateToTomorrow DATETIME; + DECLARE vDefaultDayRange INT; + + IF vDate < util.VN_CURDATE() THEN + LEAVE proc; + END IF; + + IF vDate = util.VN_CURDATE() THEN + SELECT inventoried INTO vDateFrom + FROM config; + END IF; + + SELECT defaultDayRange INTO vDefaultDayRange + FROM comparativeConfig; + + SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; + SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; + + ALTER TABLE tmp.itemInventory + ADD `avalaible` INT NOT NULL, + ADD `sd` INT NOT NULL, + ADD `rest` INT NOT NULL, + ADD `expected` INT NOT NULL, + ADD `inventory` INT NOT NULL, + ADD `visible` INT NOT NULL, + ADD `life` TINYINT NOT NULL DEFAULT '0'; + + -- Calculo del inventario + UPDATE tmp.itemInventory ai + JOIN ( + SELECT itemFk Id_Article, SUM(quantity) Subtotal + FROM ( + SELECT s.itemFk, - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub2 + GROUP BY itemFk + ) sub ON ai.id = sub.Id_Article + SET ai.inventory = sub.Subtotal, + ai.visible = sub.Subtotal, + ai.avalaible = sub.Subtotal, + ai.sd = sub.Subtotal; + + -- Cálculo del visible + UPDATE tmp.itemInventory ai + JOIN ( + SELECT itemFk Id_Article, SUM(quantity) Subtotal + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk + ) sub ON ai.id = sub.Id_Article + SET ai.visible = ai.visible + sub.Subtotal; + + -- Calculo del disponible + CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT sub.itemFk, + vWarehouseFk warehouseFk, + sub.dated, + SUM(sub.quantity) quantity + FROM ( + SELECT s.itemFk, + DATE(t.shipped) dated, + - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, t.landed, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, t.shipped, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY sub.itemFk, sub.dated; + + CALL item_getAtp(vDate); + CALL travel_upcomingArrivals(vWarehouseFk, vDate); + + UPDATE tmp.itemInventory ai + JOIN ( + SELECT it.itemFk, + SUM(it.quantity) quantity, + im.quantity minQuantity + FROM tmp.itemCalc it + JOIN tmp.itemAtp im ON im.itemFk = it.itemFk + JOIN item i ON i.id = it.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk + WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, + t.landing, + vDateToTomorrow) + GROUP BY it.itemFk + ) sub ON sub.itemFk = ai.id + SET ai.avalaible = IF(sub.minQuantity > 0, + ai.avalaible, + ai.avalaible + sub.minQuantity), + ai.sd = ai.inventory + sub.quantity; + + DROP TEMPORARY TABLE + tmp.itemTravel, + tmp.itemCalc, + tmp.itemAtp; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67555,43 +67555,43 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT) -BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; - - START TRANSACTION; - - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET s.quantity = newQuantity - WHERE s.ticketFk = vTicketFk; - - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND stp.id IS NULL - AND it.isMergeable; - - COMMIT; - - DROP TEMPORARY TABLE tSalesToPreserve; +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND it.isMergeable + GROUP BY s.itemFk, s.price, s.discount; + + START TRANSACTION; + + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET s.quantity = newQuantity + WHERE s.ticketFk = vTicketFk; + + DELETE s.* + FROM sale s + LEFT JOIN tSalesToPreserve stp ON stp.id = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND stp.id IS NULL + AND it.isMergeable; + + COMMIT; + + DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69404,30 +69404,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73367,59 +73367,59 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) -BEGIN -/** - * Splita las lineas de ticket que no estan ubicadas - * - * @param vTicketFk Id ticket - */ - DECLARE vNewTicketFk INT; - DECLARE vTotalLines INT; - DECLARE vLinesToSplit INT; - - DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - - SELECT COUNT(*) INTO vTotalLines - FROM sale - WHERE ticketFk = vTicketFk; - - CREATE TEMPORARY TABLE tmp.SalesToSplit - SELECT s.id saleFk - FROM ticket t - JOIN sale s ON t.id = s.ticketFk - LEFT JOIN ( - SELECT ish.itemFk itemFk, - SUM(ish.visible) visible, - s.warehouseFk warehouseFk - 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 - GROUP BY ish.itemFk, - s.warehouseFk - ) issw ON issw.itemFk = s.itemFk - AND issw.warehouseFk = t.warehouseFk - WHERE s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND NOT s.isPicked - AND NOT s.reserved - AND t.id = vTicketFk; - - SELECT COUNT(*) INTO vLinesToSplit - FROM tmp.SalesToSplit; - - IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - SET vNewTicketFk = vTicketFk; - ELSE - CALL ticket_Clone(vTicketFk, vNewTicketFk); - UPDATE sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id - SET s.ticketFk = vNewTicketFk; - END IF; - - CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); - - DROP TEMPORARY TABLE tmp.SalesToSplit; +BEGIN +/** + * Splita las lineas de ticket que no estan ubicadas + * + * @param vTicketFk Id ticket + */ + DECLARE vNewTicketFk INT; + DECLARE vTotalLines INT; + DECLARE vLinesToSplit INT; + + DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; + + SELECT COUNT(*) INTO vTotalLines + FROM sale + WHERE ticketFk = vTicketFk; + + CREATE TEMPORARY TABLE tmp.SalesToSplit + SELECT s.id saleFk + FROM ticket t + JOIN sale s ON t.id = s.ticketFk + LEFT JOIN ( + SELECT ish.itemFk itemFk, + SUM(ish.visible) visible, + s.warehouseFk warehouseFk + 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 + GROUP BY ish.itemFk, + s.warehouseFk + ) issw ON issw.itemFk = s.itemFk + AND issw.warehouseFk = t.warehouseFk + WHERE s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND NOT s.isPicked + AND NOT s.reserved + AND t.id = vTicketFk; + + SELECT COUNT(*) INTO vLinesToSplit + FROM tmp.SalesToSplit; + + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN + SET vNewTicketFk = vTicketFk; + ELSE + CALL ticket_Clone(vTicketFk, vNewTicketFk); + UPDATE sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + SET s.ticketFk = vNewTicketFk; + END IF; + + CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); + + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73437,84 +73437,84 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT) -BEGIN -/** -* Crea u actualiza la información del CMR asociado con -* un ticket específico en caso de que sea necesario. -* -* @param vSelf El id del ticket -*/ - DECLARE vCmrFk INT; - SELECT cmrFk INTO vCmrFk - FROM ticket - WHERE id = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tTicket - SELECT wo.firstName, - v.numberPlate, - com.id companyFk, - a.id addressFk, - c2.defaultAddressFk, - IFNULL(sat.supplierFk, su.id) supplierFk, - t.landed - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN company com ON com.id = t.companyFk - JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk - JOIN supplier su ON su.id = sa.supplierFk - LEFT JOIN route r ON r.id = t.routeFk - LEFT JOIN worker wo ON wo.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk - LEFT JOIN agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN agency ag ON ag.id = am.agencyFk - LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id - AND wo.isFreelance - WHERE al.code IN ('PACKED', 'DELIVERED') - AND co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND t.id = vSelf - GROUP BY t.id; - - IF vCmrFk THEN - UPDATE cmr c - JOIN tTicket t - SET c.senderInstruccions = t.firstName, - c.truckPlate = t.numberPlate, - c.companyFk = t.companyFk, - c.addressToFk = t.addressFk, - c.addressFromFk = t.defaultAddressFk, - c.supplierFk = t.supplierFk, - c.ead = t.landed - WHERE id = vCmrFk; - ELSE - INSERT INTO cmr ( - senderInstruccions, - truckPlate, - companyFk, - addressToFk, - addressFromFk, - supplierFk, - ead - ) - SELECT * FROM tTicket; - - IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN - UPDATE ticket - SET cmrFk = LAST_INSERT_ID() - WHERE id = vSelf; - END IF; - END IF; - - DROP TEMPORARY TABLE tTicket; +BEGIN +/** +* Crea u actualiza la información del CMR asociado con +* un ticket específico en caso de que sea necesario. +* +* @param vSelf El id del ticket +*/ + DECLARE vCmrFk INT; + SELECT cmrFk INTO vCmrFk + FROM ticket + WHERE id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tTicket + SELECT wo.firstName, + v.numberPlate, + com.id companyFk, + a.id addressFk, + c2.defaultAddressFk, + IFNULL(sat.supplierFk, su.id) supplierFk, + t.landed + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN company com ON com.id = t.companyFk + JOIN client c2 ON c2.id = com.clientFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplier su ON su.id = sa.supplierFk + LEFT JOIN route r ON r.id = t.routeFk + LEFT JOIN worker wo ON wo.id = r.workerFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency ag ON ag.id = am.agencyFk + LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id + AND wo.isFreelance + WHERE al.code IN ('PACKED', 'DELIVERED') + AND co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND t.id = vSelf + GROUP BY t.id; + + IF vCmrFk THEN + UPDATE cmr c + JOIN tTicket t + SET c.senderInstruccions = t.firstName, + c.truckPlate = t.numberPlate, + c.companyFk = t.companyFk, + c.addressToFk = t.addressFk, + c.addressFromFk = t.defaultAddressFk, + c.supplierFk = t.supplierFk, + c.ead = t.landed + WHERE id = vCmrFk; + ELSE + INSERT INTO cmr ( + senderInstruccions, + truckPlate, + companyFk, + addressToFk, + addressFromFk, + supplierFk, + ead + ) + SELECT * FROM tTicket; + + IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN + UPDATE ticket + SET cmrFk = LAST_INSERT_ID() + WHERE id = vSelf; + END IF; + END IF; + + DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80930,126 +80930,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255), + vHasInsert BOOL ) -BEGIN -/** - * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. - * @param vSelf Id de la zona - * @param vParentFk Id del geo a calcular - * @param vSearch Cadena a buscar - * @param vHasInsert Indica si inserta en tmp.zoneNodes - * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; - - CREATE OR REPLACE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id - FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk - FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - CREATE OR REPLACE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM tNodes; - - CREATE OR REPLACE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF NOT ROW_COUNT() THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE tChilds, tParents; - END IF; - - IF NOT vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tZones - SELECT g.id, - g.name, - g.parentFk, - g.sons, - NOT g.sons OR `type` = 'country' isChecked, - i.isIncluded selected, - g.`depth`, - vSelf - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i ON i.geoFk = g.id - AND i.zoneFk = vSelf - ORDER BY g.`depth`, selected DESC, g.name; - - IF vHasInsert THEN - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT id, - name, - parentFk, - sons, - isChecked, - vSelf - FROM tZones - WHERE selected - OR (selected IS NULL AND vParentFk IS NOT NULL); - ELSE - SELECT id, - name, - parentFk, - sons, - selected - FROM tZones - ORDER BY `depth`, selected DESC, name; - END IF; - - DROP TEMPORARY TABLE tNodes, tZones; +BEGIN +/** + * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch Cadena a buscar + * @param vHasInsert Indica si inserta en tmp.zoneNodes + * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; + + CREATE OR REPLACE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id + FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk + FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + CREATE OR REPLACE TEMPORARY TABLE tChilds + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM tNodes; + + CREATE OR REPLACE TEMPORARY TABLE tParents + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF NOT ROW_COUNT() THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE tChilds, tParents; + END IF; + + IF NOT vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id + FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tZones + SELECT g.id, + g.name, + g.parentFk, + g.sons, + NOT g.sons OR `type` = 'country' isChecked, + i.isIncluded selected, + g.`depth`, + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i ON i.geoFk = g.id + AND i.zoneFk = vSelf + ORDER BY g.`depth`, selected DESC, g.name; + + IF vHasInsert THEN + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT id, + name, + parentFk, + sons, + isChecked, + vSelf + FROM tZones + WHERE selected + OR (selected IS NULL AND vParentFk IS NOT NULL); + ELSE + SELECT id, + name, + parentFk, + sons, + selected + FROM tZones + ORDER BY `depth`, selected DESC, name; + END IF; + + DROP TEMPORARY TABLE tNodes, tZones; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81232,48 +81232,48 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) -BEGIN -/** - * Devuelve los códigos postales incluidos en una zona - */ - DECLARE vGeoFk INT DEFAULT NULL; - - CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( - geoFk INT, - name VARCHAR(100), - parentFk INT, - sons INT, - isChecked BOOL DEFAULT 0, - zoneFk INT, - PRIMARY KEY zoneNodesPk (zoneFk, geoFk), - INDEX(geoFk)) - ENGINE = MEMORY; - - CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - - UPDATE tmp.zoneNodes - SET isChecked = 0 - WHERE parentFk IS NULL; - - myLoop: LOOP - SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes - WHERE NOT isChecked - LIMIT 1; - - CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); - UPDATE tmp.zoneNodes - SET isChecked = TRUE - WHERE geoFk = vGeoFk; - - IF vGeoFk IS NULL THEN - LEAVE myLoop; - END IF; - END LOOP; - - DELETE FROM tmp.zoneNodes - WHERE sons > 0; +BEGIN +/** + * Devuelve los códigos postales incluidos en una zona + */ + DECLARE vGeoFk INT DEFAULT NULL; + + CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneNodesPk (zoneFk, geoFk), + INDEX(geoFk)) + ENGINE = MEMORY; + + CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); + + UPDATE tmp.zoneNodes + SET isChecked = 0 + WHERE parentFk IS NULL; + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes + WHERE NOT isChecked + LIMIT 1; + + CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + END LOOP; + + DELETE FROM tmp.zoneNodes + WHERE sons > 0; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; -- 2.40.1 From 108a62f73870e319ce1aab5132a317101fe4f817 Mon Sep 17 00:00:00 2001 From: guillermo Date: Thu, 4 Jul 2024 09:32:56 +0200 Subject: [PATCH 366/413] refs #7486 Fix tests --- db/routines/vn/procedures/collection_getAssigned.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/collection_getAssigned.sql b/db/routines/vn/procedures/collection_getAssigned.sql index bfaa3096b..947b53229 100644 --- a/db/routines/vn/procedures/collection_getAssigned.sql +++ b/db/routines/vn/procedures/collection_getAssigned.sql @@ -34,10 +34,10 @@ BEGIN pc.collection_assign_lockname INTO vHasTooMuchCollections, vLockName - FROM tCollection tc + FROM tmp.collection c JOIN productionConfig pc; - DROP TEMPORARY TABLE tCollection; + DROP TEMPORARY TABLE tmp.collection; IF vHasTooMuchCollections THEN CALL util.throw('There are pending collections'); -- 2.40.1 From fcec3bc0ae24f5972281e3ce417a650671407b57 Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 4 Jul 2024 09:54:09 +0200 Subject: [PATCH 367/413] refs #5525 fix sql accountDetail --- print/templates/reports/sepa-core/sepa-core.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/print/templates/reports/sepa-core/sepa-core.js b/print/templates/reports/sepa-core/sepa-core.js index 96c512a9d..f32fd92e7 100755 --- a/print/templates/reports/sepa-core/sepa-core.js +++ b/print/templates/reports/sepa-core/sepa-core.js @@ -27,7 +27,8 @@ module.exports = { FROM supplierAccount sa JOIN company co ON co.supplierAccountFk = sa.id JOIN supplier s ON sa.supplierFk = s.id - WHERE co.id = ?`) [this.companyId]; + WHERE co.id = ? + AND ad.accountDetailTypeFk = 3`) [this.companyId]; } } -- 2.40.1 From 776fd0564869de1019dd70df6972585fc894ee66 Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 4 Jul 2024 12:45:52 +0200 Subject: [PATCH 368/413] fix: send rocket after commit cau 199307 --- modules/ticket/back/methods/sale/deleteSales.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/ticket/back/methods/sale/deleteSales.js b/modules/ticket/back/methods/sale/deleteSales.js index 0207815a9..0290b2b9d 100644 --- a/modules/ticket/back/methods/sale/deleteSales.js +++ b/modules/ticket/back/methods/sale/deleteSales.js @@ -66,6 +66,10 @@ module.exports = Self => { promises.push(deletedSale); } + const deletedSales = await Promise.all(promises); + + if (tx) await tx.commit(); + const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { const url = await Self.app.models.Url.getUrl(); @@ -75,13 +79,9 @@ module.exports = Self => { ticketUrl: `${url}ticket/${ticketId}/sale`, deletions: deletions }); - await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); } - const deletedSales = await Promise.all(promises); - - if (tx) await tx.commit(); - return deletedSales; } catch (e) { if (tx) await tx.rollback(); -- 2.40.1 From cf621071d07c849b072173ce1baf718eaa0c1c0c Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 4 Jul 2024 16:50:54 +0200 Subject: [PATCH 369/413] refs #5525 fixear sql, fixtures, js --- db/dump/fixtures.before.sql | 15 +++++++++++++++ print/templates/reports/sepa-core/sepa-core.html | 3 +-- print/templates/reports/sepa-core/sepa-core.js | 15 +++++++++------ .../templates/reports/sepa-core/sql/supplier.sql | 14 ++++++++------ 4 files changed, 33 insertions(+), 14 deletions(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index b6275d03c..05c1bbaa7 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -3884,3 +3884,18 @@ INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHoli (1, '2001-05-17', 1, 5), (1, '2001-05-18', 1, 5); +INSERT INTO vn.accountDetail +(id, value, accountDetailTypeFk, supplierAccountFk) +VALUES + (21, 'ES12345B12345678', 3, 241), + (35, 'ES12346B12345679', 3, 241); + +INSERT INTO vn.accountDetailType +(id, description) +VALUES + (1, 'IBAN'), + (2, 'SWIFT'), + (3, 'Referencia Remesas'), + (4, 'Referencia Transferencias'), + (5, 'Referencia Nominas'), + (6, 'ABA'); diff --git a/print/templates/reports/sepa-core/sepa-core.html b/print/templates/reports/sepa-core/sepa-core.html index 363ebdfe5..e5d14d06c 100644 --- a/print/templates/reports/sepa-core/sepa-core.html +++ b/print/templates/reports/sepa-core/sepa-core.html @@ -27,8 +27,7 @@ {{$t('supplier.identifier')}} -
{{supplier.iban}}
-
{{supplier.nif}}
+
{{supplier.accountDetailValue.join(', ')}}
diff --git a/print/templates/reports/sepa-core/sepa-core.js b/print/templates/reports/sepa-core/sepa-core.js index f32fd92e7..6b941556e 100755 --- a/print/templates/reports/sepa-core/sepa-core.js +++ b/print/templates/reports/sepa-core/sepa-core.js @@ -7,7 +7,11 @@ module.exports = { async serverPrefetch() { this.client = await this.findOneFromDef('client', [this.companyId, this.companyId, this.id]); this.checkMainEntity(this.client); - this.supplier = await this.findOneFromDef('supplier', [this.companyId, this.companyId, this.id]); + const suppliers = await this.rawSqlFromDef('supplier', [this.companyId, this.companyId, this.id]); + this.supplier = { + ...suppliers[0], + accountDetailValue: suppliers.map(val => val?.accountDetailValue) + }; }, props: { id: { @@ -23,12 +27,11 @@ module.exports = { methods: { getSupplierCif() { return db.findOne(` - SELECT sa.iban, s.nif + SELECT DISTINCT ad.value FROM supplierAccount sa - JOIN company co ON co.supplierAccountFk = sa.id - JOIN supplier s ON sa.supplierFk = s.id - WHERE co.id = ? - AND ad.accountDetailTypeFk = 3`) [this.companyId]; + JOIN accountDetail ad ON ad.supplierAccountFk = sa.id + JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 + WHERE sa.supplierFk = ?`) [this.companyId]; } } diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index 156fc71c0..a49896244 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -1,15 +1,16 @@ SELECT - m.code mandateCode, + m.code AS mandateCode, s.name, s.street, - sc.name country, + sc.name AS country, s.postCode, s.city, - sp.name province, + sp.name AS province, s.nif, sa.iban, sa.supplierFk, - be.name bankName + be.name AS bankName, + ad.value AS accountDetailValue FROM client c LEFT JOIN mandate m ON m.clientFk = c.id AND m.companyFk = ? AND m.finished IS NULL @@ -19,9 +20,10 @@ FROM LEFT JOIN province p ON p.id = c.provinceFk LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id LEFT JOIN bankEntity be ON sa.bankEntityFk = be.id + LEFT JOIN accountDetail ad ON ad.supplierAccountFk = sa.id + LEFT JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 WHERE (m.companyFk = ? OR m.companyFk IS NULL) AND (c.id = ? OR (c.id IS NULL AND c.countryFk = sa.countryFk)) ORDER BY - m.created DESC -LIMIT 1; + m.created DESC; -- 2.40.1 From 64f5ad0e1960155c66c334a3b893a4a2d55c40fe Mon Sep 17 00:00:00 2001 From: carlossa Date: Thu, 4 Jul 2024 16:54:57 +0200 Subject: [PATCH 370/413] refs #5525 remove AS --- print/templates/reports/sepa-core/sql/supplier.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index a49896244..a32d311de 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -1,16 +1,16 @@ SELECT - m.code AS mandateCode, + m.code mandateCode, s.name, s.street, - sc.name AS country, + sc.name country, s.postCode, s.city, - sp.name AS province, + sp.name province, s.nif, sa.iban, sa.supplierFk, - be.name AS bankName, - ad.value AS accountDetailValue + be.name bankName, + ad.value accountDetailValue FROM client c LEFT JOIN mandate m ON m.clientFk = c.id AND m.companyFk = ? AND m.finished IS NULL -- 2.40.1 From 859f610f43a1760631bd24bc16fe013b3ea8a526 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 5 Jul 2024 08:43:45 +0200 Subject: [PATCH 371/413] hotFix itemNewer refs #6964 --- .../methods/item-shelving/getListItemNewer.js | 2 +- .../specs/getListItemNewer.spec.js | 25 +++++-------------- 2 files changed, 7 insertions(+), 20 deletions(-) diff --git a/modules/item/back/methods/item-shelving/getListItemNewer.js b/modules/item/back/methods/item-shelving/getListItemNewer.js index 1702bb05b..dafefe712 100644 --- a/modules/item/back/methods/item-shelving/getListItemNewer.js +++ b/modules/item/back/methods/item-shelving/getListItemNewer.js @@ -63,7 +63,7 @@ module.exports = Self => { FROM tItemShelving ti JOIN tItemInSector tis ON tis.itemFk = ti.itemFk JOIN vn.productionConfig pc - WHERE ti.created > tis.created + INTERVAL pc.itemOlderReviewHours HOUR;`, + WHERE ti.created + INTERVAL pc.itemOlderReviewHours HOUR < tis.created ;`, [shelvingFk, shelvingFk], myOptions); return result; }; diff --git a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js index 15c480992..9287a179d 100644 --- a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js @@ -2,30 +2,17 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getListItemNewer()', () => { - it('should return true because there is an older item', async() => { - const shelving = 'NCC'; - const parking = 'A-47-1'; + fit('should return true because there is an older item', async() => { + const shelving = 'NBB'; + const parking = '700-01'; - const sectorCamHighCode = 'CAMARA SECTOR D'; - const sectorCamCode = 'NAVE ALGEMESI'; - - const sectorCamCodeHighId = 1; - const sectorCamCodeId = 9991; + const sectorCamHighCode = 'FIRST'; + const sectorCamCode = 'NS'; const tx = await models.Sector.beginTransaction({}); const myOptions = {transaction: tx}; try { - const sectorHighCam = await models.Sector.findById(sectorCamCodeHighId, null, myOptions); - await sectorHighCam.updateAttributes({ - code: sectorCamHighCode - }); - - const sectorCam = await models.Sector.findById(sectorCamCodeId, null, myOptions); - await sectorCam.updateAttributes({ - code: sectorCamCode - }); - const config = await models.ProductionConfig.findOne(); await config.updateAttributes({ @@ -35,7 +22,7 @@ describe('itemShelving getListItemNewer()', () => { const result = await models.ItemShelving.getListItemNewer(shelving, parking, myOptions); - expect(result.length).toEqual(2); + expect(result.length).toEqual(3); await tx.rollback(); } catch (e) { await tx.rollback(); -- 2.40.1 From 159f2f5f1c4b73a48fc994c1a17d97a48038e1b6 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 5 Jul 2024 08:44:09 +0200 Subject: [PATCH 372/413] hotFix itemNewer refs #6964 --- .../back/methods/item-shelving/specs/getListItemNewer.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js index 9287a179d..962863095 100644 --- a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js @@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getListItemNewer()', () => { - fit('should return true because there is an older item', async() => { + it('should return true because there is an older item', async() => { const shelving = 'NBB'; const parking = '700-01'; -- 2.40.1 From 923efadf6a760bbeb207e096acf20861cc83bc50 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 5 Jul 2024 09:00:40 +0200 Subject: [PATCH 373/413] fix: refs #6371 restore table Series --- db/dump/.dump/structure.sql | 44 +++++++++---------- .../11134-silverRaphis/00-firstScript.sql | 42 ++++++++++++++++++ 2 files changed, 64 insertions(+), 22 deletions(-) create mode 100644 db/versions/11134-silverRaphis/00-firstScript.sql diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 6797c01a5..5755ce085 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -19,7 +19,7 @@ -- Current Database: `account` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 */ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `account`; @@ -2230,7 +2230,7 @@ DELIMITER ; -- Current Database: `bi` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bi`; @@ -4000,7 +4000,7 @@ DELIMITER ; -- Current Database: `bs` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bs`; @@ -6967,7 +6967,7 @@ DELIMITER ; -- Current Database: `cache` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `cache`; @@ -8087,7 +8087,7 @@ DELIMITER ; -- Current Database: `dipole` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `dipole`; @@ -8316,7 +8316,7 @@ DELIMITER ; -- Current Database: `edi` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `edi`; @@ -11054,7 +11054,7 @@ DELIMITER ; -- Current Database: `floranet` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `floranet`; @@ -11638,7 +11638,7 @@ DELIMITER ; -- Current Database: `hedera` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `hedera`; @@ -15833,7 +15833,7 @@ DELIMITER ; -- Current Database: `pbx` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `pbx`; @@ -16499,7 +16499,7 @@ DELIMITER ; -- Current Database: `psico` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `psico`; @@ -16834,7 +16834,7 @@ DELIMITER ; -- Current Database: `sage` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 */ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `sage`; @@ -19146,7 +19146,7 @@ DELIMITER ; -- Current Database: `salix` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `salix`; @@ -19440,7 +19440,7 @@ DELIMITER ; -- Current Database: `srt` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `srt`; @@ -22991,7 +22991,7 @@ DELIMITER ; -- Current Database: `stock` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 */ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `stock`; @@ -24069,7 +24069,7 @@ DELIMITER ; -- Current Database: `tmp` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `tmp`; @@ -24147,7 +24147,7 @@ DELIMITER ; -- Current Database: `util` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `util`; @@ -26252,7 +26252,7 @@ DELIMITER ; -- Current Database: `vn` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn`; @@ -63220,7 +63220,7 @@ BEGIN * @param vDate -> Date of the purchase operation. * @param vWarehouseFk -> Identifier of the warehouse (warehouseId). */ - ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT; + ALTER TABLE tmp.itemInventory ADD buy_id INT; CALL buyUltimate(vWarehouseFk, vDate); @@ -68883,7 +68883,7 @@ proc: BEGIN CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN + (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk)); END IF; @@ -77852,11 +77852,11 @@ BEGIN IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE tmp.`user` SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk FROM worker w; END IF; @@ -81544,7 +81544,7 @@ DELIMITER ; -- Current Database: `vn2008` -- -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 */ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn2008`; diff --git a/db/versions/11134-silverRaphis/00-firstScript.sql b/db/versions/11134-silverRaphis/00-firstScript.sql new file mode 100644 index 000000000..0836abe4e --- /dev/null +++ b/db/versions/11134-silverRaphis/00-firstScript.sql @@ -0,0 +1,42 @@ +USE `vn`; + +CREATE TABLE IF NOT EXISTS vn.`tillSerial` ( + `code` varchar(2) COLLATE utf8mb3_unicode_ci NOT NULL, + `description` varchar(30) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `account` varchar(10) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES(' S', 'Saldos final / inicial', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('A', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('B', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('C', 'Facturas Contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CC', 'Cuadre caja', '6780000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CD', 'Cuenta Director Comercial', '5510000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CH', 'Cheques', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CM', 'Cambio', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CR', 'Ingreso/Reintegro Caja Rural', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CT', 'Correos y telégrafos', '6290000005'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DC', 'Dietas conductores', '6290000010'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DH', 'Deudas Holland', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DT', 'Dietas', '6290000011'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('E', 'Entrada mercancia', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('EN', 'Enric Martinez', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GC', 'Cuenta con dto. Comercial', '5510000003'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GP', 'Gastos de personal', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GR', 'Gastos RRPP dpto comercial', '6290001002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GS', 'Gasoil', '6280000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GV', 'Gastos viaje', '6290001000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('JV', 'Juanvi', '6290000553'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MB', 'Movimiento bancario', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MP', 'Materias Primas', '6000000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('OG', 'Otros gastos', '6290000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('PM', 'Pequeño material', '6290000007'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('R', 'Factura proveedor', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RC', 'Ingreso/Reintegro Ruralcaja', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RN', 'Reparación nave', '6220000004'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('SS', 'Gastos Silla', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('T', 'Ticket', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TA', 'Factura rapida', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TC', 'Ticket contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TR', 'Traspaso', NULL); \ No newline at end of file -- 2.40.1 From 27a4b747b5595a50087b34ae0fa866612bd09d0b Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 5 Jul 2024 09:05:39 +0200 Subject: [PATCH 374/413] fix: refs #6371 restore table Series --- .../11134-silverRaphis/00-firstScript.sql | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 db/versions/11134-silverRaphis/00-firstScript.sql diff --git a/db/versions/11134-silverRaphis/00-firstScript.sql b/db/versions/11134-silverRaphis/00-firstScript.sql new file mode 100644 index 000000000..0836abe4e --- /dev/null +++ b/db/versions/11134-silverRaphis/00-firstScript.sql @@ -0,0 +1,42 @@ +USE `vn`; + +CREATE TABLE IF NOT EXISTS vn.`tillSerial` ( + `code` varchar(2) COLLATE utf8mb3_unicode_ci NOT NULL, + `description` varchar(30) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `account` varchar(10) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES(' S', 'Saldos final / inicial', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('A', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('B', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('C', 'Facturas Contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CC', 'Cuadre caja', '6780000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CD', 'Cuenta Director Comercial', '5510000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CH', 'Cheques', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CM', 'Cambio', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CR', 'Ingreso/Reintegro Caja Rural', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CT', 'Correos y telégrafos', '6290000005'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DC', 'Dietas conductores', '6290000010'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DH', 'Deudas Holland', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DT', 'Dietas', '6290000011'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('E', 'Entrada mercancia', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('EN', 'Enric Martinez', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GC', 'Cuenta con dto. Comercial', '5510000003'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GP', 'Gastos de personal', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GR', 'Gastos RRPP dpto comercial', '6290001002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GS', 'Gasoil', '6280000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GV', 'Gastos viaje', '6290001000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('JV', 'Juanvi', '6290000553'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MB', 'Movimiento bancario', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MP', 'Materias Primas', '6000000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('OG', 'Otros gastos', '6290000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('PM', 'Pequeño material', '6290000007'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('R', 'Factura proveedor', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RC', 'Ingreso/Reintegro Ruralcaja', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RN', 'Reparación nave', '6220000004'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('SS', 'Gastos Silla', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('T', 'Ticket', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TA', 'Factura rapida', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TC', 'Ticket contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TR', 'Traspaso', NULL); \ No newline at end of file -- 2.40.1 From 182273d3b387c35cd40d296eceee468381d4ca4a Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 09:59:15 +0200 Subject: [PATCH 375/413] refs #7450 Modified msg throw --- db/routines/vn/procedures/entry_isEditable.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql index a05a1fd92..c279fac65 100644 --- a/db/routines/vn/procedures/entry_isEditable.sql +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -18,7 +18,7 @@ BEGIN AND e.id = vSelf; IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN - CALL util.throw('Entry is not editable'); + CALL util.throw(CONCAT('Entry ', vSelf, ' is not editable')); END IF; END$$ DELIMITER ; -- 2.40.1 From 3051e4ed251a7dc25a96efdee607769b79c4f2d7 Mon Sep 17 00:00:00 2001 From: robert Date: Fri, 5 Jul 2024 10:35:32 +0200 Subject: [PATCH 376/413] Merge branch '6371-restoreSeries' of https://gitea.verdnatura.es/verdnatura/salix into 6371-restoreSeries --- db/dump/.dump/structure.sql | 44 ++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 5755ce085..6797c01a5 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -19,7 +19,7 @@ -- Current Database: `account` -- -CREATE DATABASE /*!32312 */ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `account` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `account`; @@ -2230,7 +2230,7 @@ DELIMITER ; -- Current Database: `bi` -- -CREATE DATABASE /*!32312 */ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bi`; @@ -4000,7 +4000,7 @@ DELIMITER ; -- Current Database: `bs` -- -CREATE DATABASE /*!32312 */ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `bs`; @@ -6967,7 +6967,7 @@ DELIMITER ; -- Current Database: `cache` -- -CREATE DATABASE /*!32312 */ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cache` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `cache`; @@ -8087,7 +8087,7 @@ DELIMITER ; -- Current Database: `dipole` -- -CREATE DATABASE /*!32312 */ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `dipole` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `dipole`; @@ -8316,7 +8316,7 @@ DELIMITER ; -- Current Database: `edi` -- -CREATE DATABASE /*!32312 */ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `edi` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `edi`; @@ -11054,7 +11054,7 @@ DELIMITER ; -- Current Database: `floranet` -- -CREATE DATABASE /*!32312 */ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `floranet` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `floranet`; @@ -11638,7 +11638,7 @@ DELIMITER ; -- Current Database: `hedera` -- -CREATE DATABASE /*!32312 */ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `hedera`; @@ -15833,7 +15833,7 @@ DELIMITER ; -- Current Database: `pbx` -- -CREATE DATABASE /*!32312 */ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `pbx`; @@ -16499,7 +16499,7 @@ DELIMITER ; -- Current Database: `psico` -- -CREATE DATABASE /*!32312 */ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `psico` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `psico`; @@ -16834,7 +16834,7 @@ DELIMITER ; -- Current Database: `sage` -- -CREATE DATABASE /*!32312 */ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `sage` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `sage`; @@ -19146,7 +19146,7 @@ DELIMITER ; -- Current Database: `salix` -- -CREATE DATABASE /*!32312 */ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `salix`; @@ -19440,7 +19440,7 @@ DELIMITER ; -- Current Database: `srt` -- -CREATE DATABASE /*!32312 */ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `srt` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `srt`; @@ -22991,7 +22991,7 @@ DELIMITER ; -- Current Database: `stock` -- -CREATE DATABASE /*!32312 */ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `stock` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci */; USE `stock`; @@ -24069,7 +24069,7 @@ DELIMITER ; -- Current Database: `tmp` -- -CREATE DATABASE /*!32312 */ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `tmp` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `tmp`; @@ -24147,7 +24147,7 @@ DELIMITER ; -- Current Database: `util` -- -CREATE DATABASE /*!32312 */ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `util` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `util`; @@ -26252,7 +26252,7 @@ DELIMITER ; -- Current Database: `vn` -- -CREATE DATABASE /*!32312 */ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn`; @@ -63220,7 +63220,7 @@ BEGIN * @param vDate -> Date of the purchase operation. * @param vWarehouseFk -> Identifier of the warehouse (warehouseId). */ - ALTER TABLE tmp.itemInventory ADD buy_id INT; + ALTER TABLE tmp.itemInventory ADD IF NOT EXISTS buy_id INT; CALL buyUltimate(vWarehouseFk, vDate); @@ -68883,7 +68883,7 @@ proc: BEGIN CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN + IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk)); END IF; @@ -77852,11 +77852,11 @@ BEGIN IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT id userFk FROM worker w; END IF; @@ -81544,7 +81544,7 @@ DELIMITER ; -- Current Database: `vn2008` -- -CREATE DATABASE /*!32312 */ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vn2008` /*!40100 DEFAULT CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci */; USE `vn2008`; -- 2.40.1 From f3f450463b628ac57cb811985e3659519bf0fe70 Mon Sep 17 00:00:00 2001 From: sergiodt Date: Fri, 5 Jul 2024 10:47:26 +0200 Subject: [PATCH 377/413] warmFix getSales refs #6861 --- back/methods/collection/getSales.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index 8f5bfaeef..a9e5f2e60 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -60,15 +60,17 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); for (let ticket of tickets) { - let observations = ticket.observaciones.split(' '); + if (ticket.observaciones) { + let observations = ticket.observaciones.split(' '); - for (let observation of observations) { - const salesPerson = ticket.salesPersonFk; - if (observation.startsWith('#') || observation.startsWith('@')) { - await models.Chat.send(ctx, - observation, - $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) - ); + for (let observation of observations) { + const salesPerson = ticket.salesPersonFk; + if (observation.startsWith('#') || observation.startsWith('@')) { + await models.Chat.send(ctx, + observation, + $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) + ); + } } } } -- 2.40.1 From 1799b52f8b8fc0ac5188c38876aacb3aeb2f5a8d Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 12:37:59 +0200 Subject: [PATCH 378/413] feat: refs #7622 Added type column addressWaste --- db/routines/vn/procedures/item_setVisibleDiscard.sql | 3 ++- db/versions/11136-maroonMedeola/00-firstScript.sql | 6 ++++++ .../models/{addressShortage.json => address-waste.json} | 8 ++++++-- 3 files changed, 14 insertions(+), 3 deletions(-) create mode 100644 db/versions/11136-maroonMedeola/00-firstScript.sql rename modules/client/back/models/{addressShortage.json => address-waste.json} (70%) diff --git a/db/routines/vn/procedures/item_setVisibleDiscard.sql b/db/routines/vn/procedures/item_setVisibleDiscard.sql index 0a6c54971..a44d87333 100644 --- a/db/routines/vn/procedures/item_setVisibleDiscard.sql +++ b/db/routines/vn/procedures/item_setVisibleDiscard.sql @@ -6,7 +6,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDisc vAddressFk INT) BEGIN /** - * Procedimiento para dar dar de baja/alta un item, si vAddressFk es NULL se entiende que se da de alta y se toma el addressFk de la configuración + * Procedimiento para dar dar de baja/alta un item, si vAdressFk es NULL + * se entiende que se da de alta y se toma el addressFk de la configuración * * @param vItemFk Identificador del ítem * @param vWarehouseFk id del warehouse diff --git a/db/versions/11136-maroonMedeola/00-firstScript.sql b/db/versions/11136-maroonMedeola/00-firstScript.sql new file mode 100644 index 000000000..09abfe391 --- /dev/null +++ b/db/versions/11136-maroonMedeola/00-firstScript.sql @@ -0,0 +1,6 @@ +RENAME TABLE vn.addressShortage TO vn.addressWaste; +ALTER TABLE vn.addressWaste ADD `type` ENUM('internal', 'external') NOT NULL; +INSERT INTO IGNORE vn.addressWaste (addressFk,`type`) VALUES + (2230,'external'), + (5986,'external'), + (7475,'external'); diff --git a/modules/client/back/models/addressShortage.json b/modules/client/back/models/address-waste.json similarity index 70% rename from modules/client/back/models/addressShortage.json rename to modules/client/back/models/address-waste.json index 1ae8d986c..2d7126eae 100644 --- a/modules/client/back/models/addressShortage.json +++ b/modules/client/back/models/address-waste.json @@ -1,15 +1,19 @@ { - "name": "AddressShortage", + "name": "AddressWaste", "base": "VnModel", "options": { "mysql": { - "table": "addressShortage" + "table": "addressWaste" } }, "properties": { "addressFk": { "type": "number", "id": true + }, + "type": { + "type": "string", + "id": true } }, "relations": { -- 2.40.1 From b9e986c9627c26921e880245e4b7c8c264e55a64 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 12:39:54 +0200 Subject: [PATCH 379/413] feat: refs #7622 Fix --- db/versions/11136-maroonMedeola/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/11136-maroonMedeola/00-firstScript.sql b/db/versions/11136-maroonMedeola/00-firstScript.sql index 09abfe391..b0b92c7e9 100644 --- a/db/versions/11136-maroonMedeola/00-firstScript.sql +++ b/db/versions/11136-maroonMedeola/00-firstScript.sql @@ -1,6 +1,6 @@ RENAME TABLE vn.addressShortage TO vn.addressWaste; ALTER TABLE vn.addressWaste ADD `type` ENUM('internal', 'external') NOT NULL; -INSERT INTO IGNORE vn.addressWaste (addressFk,`type`) VALUES +INSERT IGNORE INTO vn.addressWaste (addressFk,`type`) VALUES (2230,'external'), (5986,'external'), (7475,'external'); -- 2.40.1 From 8ac26c7281ca26fa9110389783c7128ee90d0967 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 12:50:31 +0200 Subject: [PATCH 380/413] refactor: refs #7640 Refactor multipleInventory --- .../vn/procedures/multipleInventory.sql | 85 ++++++++++--------- 1 file changed, 43 insertions(+), 42 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index ece57727d..704a93152 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -76,52 +76,52 @@ proc: BEGIN GROUP BY itemFk; -- Cálculo del visible - UPDATE tItemInventoryCalc iic - JOIN ( - SELECT itemFk, SUM(quantity) visible - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON sub.itemFk = iic.itemFk - SET iic.visible = iic.visible + sub.visible; + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) visible + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk; UPDATE tmp.itemInventory ai JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id SET ai.inventory = iic.quantity, - ai.visible = iic.visible, + ai.visible = iic.quantity + ivc.visible, ai.avalaible = iic.quantity, ai.sd = iic.quantity; @@ -195,6 +195,7 @@ proc: BEGIN tmp.itemTravel, tmp.itemCalc, tItemInventoryCalc, + tItemVisibleCalc, tmp.itemAtp; END$$ DELIMITER ; -- 2.40.1 From 1d59883d19f96020ec7d377cc965c975821b60e0 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:14:16 +0200 Subject: [PATCH 381/413] feat: refs #7644 Minor change --- print/templates/reports/buy-label/buy-label.html | 2 +- print/templates/reports/buy-label/sql/buys.sql | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/print/templates/reports/buy-label/buy-label.html b/print/templates/reports/buy-label/buy-label.html index 494cdcbc5..b14e54759 100644 --- a/print/templates/reports/buy-label/buy-label.html +++ b/print/templates/reports/buy-label/buy-label.html @@ -59,7 +59,7 @@
- {{buy.id}} + {{buy.itemFk}} diff --git a/print/templates/reports/buy-label/sql/buys.sql b/print/templates/reports/buy-label/sql/buys.sql index 50b34bd03..41fd3556b 100644 --- a/print/templates/reports/buy-label/sql/buys.sql +++ b/print/templates/reports/buy-label/sql/buys.sql @@ -8,6 +8,7 @@ SELECT ROW_NUMBER() OVER(ORDER BY b.id) labelNum, b.`grouping`, i.stems, b.id, + b.itemFk, p.name producer FROM buy b JOIN item i ON i.id = b.itemFk -- 2.40.1 From 3ddf49da0afdbd00b7f4c8466668149b439cacc1 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:21:07 +0200 Subject: [PATCH 382/413] feat: refs #7640 Fix --- db/routines/vn/procedures/multipleInventory.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 704a93152..8eb4dae71 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -119,9 +119,9 @@ proc: BEGIN UPDATE tmp.itemInventory ai JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id - JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id + LEFT JOIN tItemVisibleCalc ivc ON ivc.itemFk = iic.itemFk SET ai.inventory = iic.quantity, - ai.visible = iic.quantity + ivc.visible, + ai.visible = iic.visible + IFNULL(ivc.visible, 0), ai.avalaible = iic.quantity, ai.sd = iic.quantity; -- 2.40.1 From 55f0e907711b4090fa7c97caf4f54817414d882f Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:36:38 +0200 Subject: [PATCH 383/413] feat: refs #7640 Minor change --- db/routines/vn/procedures/multipleInventory.sql | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 8eb4dae71..662aa2d63 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -75,6 +75,13 @@ proc: BEGIN ) sub GROUP BY itemFk; + UPDATE tmp.itemInventory ai + JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + SET ai.inventory = iic.quantity, + ai.visible = iic.visible, + ai.avalaible = iic.quantity, + ai.sd = iic.quantity; + -- Cálculo del visible CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc (PRIMARY KEY (itemFk)) @@ -118,12 +125,8 @@ proc: BEGIN GROUP BY itemFk; UPDATE tmp.itemInventory ai - JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id - LEFT JOIN tItemVisibleCalc ivc ON ivc.itemFk = iic.itemFk - SET ai.inventory = iic.quantity, - ai.visible = iic.visible + IFNULL(ivc.visible, 0), - ai.avalaible = iic.quantity, - ai.sd = iic.quantity; + JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id + SET ai.visible = ai.visible + ivc.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc -- 2.40.1 From 592738c7a0c3d39da8c75c6f7fc365023c5402f7 Mon Sep 17 00:00:00 2001 From: guillermo Date: Fri, 5 Jul 2024 13:48:03 +0200 Subject: [PATCH 384/413] refs #7024 & ticket 198125 Hotfix --- db/routines/vn/triggers/entry_beforeUpdate.sql | 2 -- 1 file changed, 2 deletions(-) diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 31c6f9bd6..0a161853b 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -11,11 +11,9 @@ BEGIN IF NEW.isBooked = OLD.isBooked AND ( NOT (NEW.supplierFk <=> OLD.supplierFk) OR NOT (NEW.dated <=> OLD.dated) OR - NOT (NEW.invoiceNumber <=> OLD.invoiceNumber) OR NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.companyFk <=> OLD.companyFk) OR NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) OR - NOT (NEW.invoiceAmount <=> OLD.invoiceAmount) OR NOT (NEW.typeFk <=> OLD.typeFk) ) THEN -- 2.40.1 From 3508cf3a9eea30366065b002e4135fce13590a17 Mon Sep 17 00:00:00 2001 From: ivanm Date: Fri, 5 Jul 2024 14:01:09 +0200 Subject: [PATCH 385/413] refs #7561 add fk en userFk --- db/versions/11137-salmonRoebelini/00-firstScript.sql | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 db/versions/11137-salmonRoebelini/00-firstScript.sql diff --git a/db/versions/11137-salmonRoebelini/00-firstScript.sql b/db/versions/11137-salmonRoebelini/00-firstScript.sql new file mode 100644 index 000000000..69d20ac6d --- /dev/null +++ b/db/versions/11137-salmonRoebelini/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.expeditionState + MODIFY COLUMN userFk INT(10) UNSIGNED, + ADD CONSTRAINT expeditionState_userFk FOREIGN KEY (userFk) + REFERENCES account.`user`(id); \ No newline at end of file -- 2.40.1 From 5192bfd8ead52327c2b474465f231b8e596466c8 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Fri, 5 Jul 2024 14:58:34 +0200 Subject: [PATCH 386/413] fix(salix): refs #7648 #7648 entryFilter and getBuys by fi --- modules/entry/back/methods/entry/filter.js | 7 ++++--- modules/entry/back/methods/entry/getBuys.js | 7 ++++--- modules/entry/back/methods/entry/specs/filter.spec.js | 4 ++-- modules/entry/back/methods/entry/specs/getBuys.spec.js | 2 +- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 5989494a4..f21d9dbc4 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -146,10 +146,11 @@ module.exports = Self => { }); filter = mergeFilters(ctx.args.filter, {where}); const userId = ctx.req.accessToken.userId; - const isSupplier = await Self.app.models.Supplier.findById(userId, myOptions); - if (isSupplier) { + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { if (!filter.where) filter.where = {}; - filter.where[`e.supplierFk`] = ctx.req.accessToken.userId; + filter.where[`e.supplierFk`] = supplier.id; } const stmts = []; let stmt; diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index 444e6cb14..0cb71653e 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -36,9 +36,10 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const isSupplier = await Self.app.models.Supplier.findById(userId, myOptions); - if (isSupplier) { - const isEntryOwner = (await Self.findById(id)).supplierFk === userId; + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { + const isEntryOwner = (await Self.findById(id)).supplierFk === supplier.id; if (!isEntryOwner) throw new UserError('Access Denied'); } diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index 9d954cdc4..c8a5bd94f 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -56,7 +56,7 @@ describe('Entry filter()', () => { try { const ctx = { args: {}, - req: {accessToken: {userId: 2}} + req: {accessToken: {userId: 1102}} }; const result = await models.Entry.filter(ctx, options); @@ -79,7 +79,7 @@ describe('Entry filter()', () => { args: { supplierFk: 1 }, - req: {accessToken: {userId: 2}} + req: {accessToken: {userId: 1102}} }; const result = await models.Entry.filter(ctx, options); diff --git a/modules/entry/back/methods/entry/specs/getBuys.spec.js b/modules/entry/back/methods/entry/specs/getBuys.spec.js index cb7f7cb80..2d3531249 100644 --- a/modules/entry/back/methods/entry/specs/getBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/getBuys.spec.js @@ -40,7 +40,7 @@ describe('entry getBuys()', () => { args: { search: 1 }, - req: {accessToken: {userId: 2}} + req: {accessToken: {userId: 1102}} }; const result = await models.Entry.getBuys(ctx, entryId, options); -- 2.40.1 From 2f10066290c1c064c49a68167dd775698b0fe908 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sun, 7 Jul 2024 23:23:30 +0200 Subject: [PATCH 387/413] feat(salix): refs #7380 #7380 remove new field --- db/versions/11132-aquaDracena/00-firstScript.sql | 2 -- modules/client/back/models/client.json | 3 --- 2 files changed, 5 deletions(-) diff --git a/db/versions/11132-aquaDracena/00-firstScript.sql b/db/versions/11132-aquaDracena/00-firstScript.sql index 1b304c1d0..a8baa8051 100644 --- a/db/versions/11132-aquaDracena/00-firstScript.sql +++ b/db/versions/11132-aquaDracena/00-firstScript.sql @@ -1,4 +1,2 @@ INSERT IGNORE INTO vn.observationType (`description`,code,hasNewBornMessage) VALUES ('Sustitución','substitution',0); - -ALTER TABLE vn.client ADD substitutionAllowed BOOL DEFAULT false NULL; diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index 97c2a3624..f3eb9919b 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -53,9 +53,6 @@ "isActive": { "type": "boolean" }, - "substitutionAllowed": { - "type": "boolean" - }, "credit": { "type": "number" }, -- 2.40.1 From 3c2a44eb53334a31de7646f93a7f68c4a2fa1cc6 Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Sun, 7 Jul 2024 23:47:00 +0200 Subject: [PATCH 388/413] feat(salix): refs #7380 #7380 add value to fixtures --- db/dump/fixtures.before.sql | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 783feaca0..ebf0c3401 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -528,7 +528,8 @@ INSERT INTO `vn`.`observationType`(`id`,`description`, `code`) (5, 'Administrative', 'administrative'), (6, 'Weight', 'weight'), (7, 'InvoiceOut', 'invoiceOut'), - (8, 'DropOff', 'dropOff'); + (8, 'DropOff', 'dropOff'), + (9, 'Sustitución', 'substitution',0); INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) VALUES -- 2.40.1 From 3a2acfb7f8e5e012704c9e3496375521416d06c8 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 07:21:53 +0200 Subject: [PATCH 389/413] feat: refs #7640 Optimization --- db/routines/vn/procedures/multipleInventory.sql | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 662aa2d63..941ac6c3d 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -40,8 +40,7 @@ proc: BEGIN (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT itemFk, - SUM(quantity) quantity, - SUM(quantity) visible + SUM(quantity) quantity FROM ( SELECT s.itemFk, - s.quantity quantity FROM sale s @@ -78,7 +77,7 @@ proc: BEGIN UPDATE tmp.itemInventory ai JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id SET ai.inventory = iic.quantity, - ai.visible = iic.visible, + ai.visible = iic.quantity, ai.avalaible = iic.quantity, ai.sd = iic.quantity; -- 2.40.1 From 816b111f79206e35486d1b7491a5aecd86353881 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 8 Jul 2024 09:20:39 +0200 Subject: [PATCH 390/413] feat: refs #6403 add dynamic clientType --- back/methods/mrw-config/createShipment.ejs | 2 +- back/methods/mrw-config/createShipment.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/back/methods/mrw-config/createShipment.ejs b/back/methods/mrw-config/createShipment.ejs index 7468218f2..8e123ddd9 100644 --- a/back/methods/mrw-config/createShipment.ejs +++ b/back/methods/mrw-config/createShipment.ejs @@ -3,7 +3,7 @@ <%= mrw.franchiseCode %> - <%= mrw.subscriberCode %> + <%= expeditionData.clientType %> <%= mrw.user %> <%= mrw.password %> diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index a2fccb95b..13d3a591f 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -52,7 +52,8 @@ module.exports = Self => { CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference, LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth,'0') serviceType, IF(mw.weekdays, 'S', 'N') weekDays, - oa.description deliveryObservation + oa.description deliveryObservation, + ms.clientType FROM expedition e JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk -- 2.40.1 From e9d2ff14764bfc5eddcc1e0121de93d183c71546 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 09:43:59 +0200 Subject: [PATCH 391/413] feat: refs #7582 claimDestination addColumn code --- db/versions/11138-aquaGalax/00-firstScript.sql | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 db/versions/11138-aquaGalax/00-firstScript.sql diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql new file mode 100644 index 000000000..44fdd468f --- /dev/null +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -0,0 +1,9 @@ +USE `vn`; +ALTER TABLE `vn`.`claimDestination` +ADD COLUMN `code` varchar(45) DEFAULT NULL; + +UPDATE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; +UPDATE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; +UPDATE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; +UPDATE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; +UPDATE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file -- 2.40.1 From 9f57e50f8964f7617dd0e4999050d0dd901dcf1a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 8 Jul 2024 09:54:40 +0200 Subject: [PATCH 392/413] feat(salix): refs #7380 #7380 add value to fixtures --- db/dump/fixtures.before.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index ebf0c3401..8bc70fbba 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -529,7 +529,7 @@ INSERT INTO `vn`.`observationType`(`id`,`description`, `code`) (6, 'Weight', 'weight'), (7, 'InvoiceOut', 'invoiceOut'), (8, 'DropOff', 'dropOff'), - (9, 'Sustitución', 'substitution',0); + (9, 'Sustitución', 'substitution'); INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) VALUES -- 2.40.1 From 9f4680325bfb580147fdb1d9ead048a62689851a Mon Sep 17 00:00:00 2001 From: Javier Segarra Date: Mon, 8 Jul 2024 09:54:52 +0200 Subject: [PATCH 393/413] feat(salix): refs #7380 #7380 rename extension file --- db/versions/11132-aquaDracena/00-firstScript.sql | 2 -- db/versions/11132-aquaDracena/00-firstScript.vn.sql | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) delete mode 100644 db/versions/11132-aquaDracena/00-firstScript.sql create mode 100644 db/versions/11132-aquaDracena/00-firstScript.vn.sql diff --git a/db/versions/11132-aquaDracena/00-firstScript.sql b/db/versions/11132-aquaDracena/00-firstScript.sql deleted file mode 100644 index a8baa8051..000000000 --- a/db/versions/11132-aquaDracena/00-firstScript.sql +++ /dev/null @@ -1,2 +0,0 @@ -INSERT IGNORE INTO vn.observationType (`description`,code,hasNewBornMessage) - VALUES ('Sustitución','substitution',0); diff --git a/db/versions/11132-aquaDracena/00-firstScript.vn.sql b/db/versions/11132-aquaDracena/00-firstScript.vn.sql new file mode 100644 index 000000000..64f8442b4 --- /dev/null +++ b/db/versions/11132-aquaDracena/00-firstScript.vn.sql @@ -0,0 +1,2 @@ +INSERT IGNORE INTO vn.observationType (`description`,code) + VALUES ('Sustitución','substitution'); -- 2.40.1 From 62045756e6717d759408b2e883ce0bde25a6baa3 Mon Sep 17 00:00:00 2001 From: pablone Date: Mon, 8 Jul 2024 10:50:15 +0200 Subject: [PATCH 394/413] fix: refs #6403 extend length to 6 digits for mrw clientType --- back/methods/mrw-config/createShipment.js | 4 ++-- db/versions/11139-bronzeCataractarum/00-firstScript.sql | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) create mode 100644 db/versions/11139-bronzeCataractarum/00-firstScript.sql diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index 13d3a591f..9b23cc370 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -50,10 +50,10 @@ module.exports = Self => { DATE_FORMAT(t.shipped, '%d/%m/%Y') created, t.shipped, CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference, - LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth,'0') serviceType, + LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth, '0') serviceType, IF(mw.weekdays, 'S', 'N') weekDays, oa.description deliveryObservation, - ms.clientType + LPAD(ms.clientType, mc.clientTypeWidth, '0') clientType FROM expedition e JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk diff --git a/db/versions/11139-bronzeCataractarum/00-firstScript.sql b/db/versions/11139-bronzeCataractarum/00-firstScript.sql new file mode 100644 index 000000000..2816fab86 --- /dev/null +++ b/db/versions/11139-bronzeCataractarum/00-firstScript.sql @@ -0,0 +1,6 @@ +-- Place your SQL code here +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS clientTypeWidth int(10) unsigned NULL + COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.'; + +UPDATE vn.mrwConfig + SET clientTypeWidth = 6; \ No newline at end of file -- 2.40.1 From 3fa0823d931bc8a817772f0ed855172151e537c5 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 11:01:35 +0200 Subject: [PATCH 395/413] feat: refs #7582 quitar vn --- db/versions/11138-aquaGalax/00-firstScript.sql | 1 - 1 file changed, 1 deletion(-) diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql index 44fdd468f..1e759db61 100644 --- a/db/versions/11138-aquaGalax/00-firstScript.sql +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -1,4 +1,3 @@ -USE `vn`; ALTER TABLE `vn`.`claimDestination` ADD COLUMN `code` varchar(45) DEFAULT NULL; -- 2.40.1 From a796787cb5eb3da34a893f25c79c7d52ff939aa0 Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 11:04:35 +0200 Subject: [PATCH 396/413] feat: refs #7582 --- db/versions/11138-aquaGalax/00-firstScript.sql | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql index 1e759db61..0c6547260 100644 --- a/db/versions/11138-aquaGalax/00-firstScript.sql +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -1,8 +1,8 @@ ALTER TABLE `vn`.`claimDestination` ADD COLUMN `code` varchar(45) DEFAULT NULL; -UPDATE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; -UPDATE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; -UPDATE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; -UPDATE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; -UPDATE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file +UPDATE IGNORE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; +UPDATE IGNORE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; +UPDATE IGNORE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; +UPDATE IGNORE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; +UPDATE IGNORE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file -- 2.40.1 From 0722a97c6000bd9ebc36b9349589bd660ee5e31a Mon Sep 17 00:00:00 2001 From: robert Date: Mon, 8 Jul 2024 11:28:33 +0200 Subject: [PATCH 397/413] feat: refs #7582 --- db/versions/11138-aquaGalax/00-firstScript.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql index 0c6547260..d492e6470 100644 --- a/db/versions/11138-aquaGalax/00-firstScript.sql +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -3,6 +3,6 @@ ADD COLUMN `code` varchar(45) DEFAULT NULL; UPDATE IGNORE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; UPDATE IGNORE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; -UPDATE IGNORE vn.claimDestination SET code='Manufacturing'WHERE description = 'Confeccion'; +UPDATE IGNORE vn.claimDestination SET code='Manufacturing' WHERE description = 'Confeccion'; UPDATE IGNORE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; UPDATE IGNORE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file -- 2.40.1 From 03b95eb9f6d7e1a9993b6d4e25bb7a4cb6bccfdd Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 8 Jul 2024 13:43:08 +0200 Subject: [PATCH 398/413] refs #5525 fix accountDetailValue --- print/templates/reports/sepa-core/sql/supplier.sql | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index a32d311de..e0ad69257 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -7,7 +7,6 @@ SELECT s.city, sp.name province, s.nif, - sa.iban, sa.supplierFk, be.name bankName, ad.value accountDetailValue @@ -21,9 +20,11 @@ FROM LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id LEFT JOIN bankEntity be ON sa.bankEntityFk = be.id LEFT JOIN accountDetail ad ON ad.supplierAccountFk = sa.id - LEFT JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 + JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk WHERE (m.companyFk = ? OR m.companyFk IS NULL) AND (c.id = ? OR (c.id IS NULL AND c.countryFk = sa.countryFk)) + AND adt.id = 3 +GROUP BY ad.value ORDER BY - m.created DESC; +m.created DESC; -- 2.40.1 From 06ae86d78faf3dae812f18045091a41fbe717319 Mon Sep 17 00:00:00 2001 From: carlossa Date: Mon, 8 Jul 2024 13:45:16 +0200 Subject: [PATCH 399/413] refs #5525 fix adt --- print/templates/reports/sepa-core/sql/supplier.sql | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/print/templates/reports/sepa-core/sql/supplier.sql b/print/templates/reports/sepa-core/sql/supplier.sql index e0ad69257..1276f2437 100644 --- a/print/templates/reports/sepa-core/sql/supplier.sql +++ b/print/templates/reports/sepa-core/sql/supplier.sql @@ -20,11 +20,10 @@ FROM LEFT JOIN supplierAccount sa ON sa.supplierFk = s.id LEFT JOIN bankEntity be ON sa.bankEntityFk = be.id LEFT JOIN accountDetail ad ON ad.supplierAccountFk = sa.id - JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk + JOIN accountDetailType adt ON adt.id = ad.accountDetailTypeFk AND adt.id = 3 WHERE (m.companyFk = ? OR m.companyFk IS NULL) AND (c.id = ? OR (c.id IS NULL AND c.countryFk = sa.countryFk)) - AND adt.id = 3 GROUP BY ad.value ORDER BY m.created DESC; -- 2.40.1 From 86859c98e37d50bac8fb40f22d0fbba2a7861388 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 13:57:17 +0200 Subject: [PATCH 400/413] refactor: refs #7662 Added transaction --- .../ticket_splitItemPackingType.sql | 97 +++++++++++-------- 1 file changed, 57 insertions(+), 40 deletions(-) diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index d6e8e8a53..bc4c94d46 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -1,59 +1,67 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitItemPackingType`( - vTicketFk INT, - vOriginalItemPackingTypeFk VARCHAR(1) + vSelf INT, + vItemPackingTypeFk VARCHAR(1) ) BEGIN /** * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. * Respeta el id inicial para el tipo propuesto. * - * @param vTicketFk Identificador de vn.ticket - * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original + * @param vSelf Id ticket + * @param vItemPackingTypeFk Tipo para el que se reserva el número de ticket original * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; DECLARE vNewTicketFk INT; DECLARE vPackingTypesToSplit INT; DECLARE vDone INT DEFAULT FALSE; - - DECLARE cur1 CURSOR FOR + DECLARE vSaleGroup CURSOR FOR SELECT itemPackingTypeFk - FROM tmp.saleGroup + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL - ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC; + ORDER BY (itemPackingTypeFk = vItemPackingTypeFk) DESC; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + ROLLBACK; RESIGNAL; END; - DELETE FROM vn.sale - WHERE quantity = 0 - AND ticketFk = vTicketFk; + START TRANSACTION; - CREATE OR REPLACE TEMPORARY TABLE tmp.sale + SELECT id + FROM sale + WHERE ticketFk = vSelf + AND NOT quantity + FOR UPDATE; + + DELETE FROM sale + WHERE NOT quantity + AND ticketFk = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tSale (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id - WHERE s.ticketFk = vTicketFk; + SELECT s.id, i.itemPackingTypeFk, IFNULL(sv.litros, 0) litros + FROM sale s + JOIN item i ON i.id = s.itemFk + LEFT JOIN saleVolume sv ON sv.saleFk = s.id + WHERE s.ticketFk = vSelf; - CREATE OR REPLACE TEMPORARY TABLE tmp.saleGroup + CREATE OR REPLACE TEMPORARY TABLE tSaleGroup ENGINE = MEMORY SELECT itemPackingTypeFk, SUM(litros) totalLitros - FROM tmp.sale + FROM tSale GROUP BY itemPackingTypeFk; SELECT COUNT(*) INTO vPackingTypesToSplit - FROM tmp.saleGroup + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT ( + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( ticketFk INT, itemPackingTypeFk VARCHAR(1) ) ENGINE = MEMORY; @@ -61,55 +69,64 @@ BEGIN CASE vPackingTypesToSplit WHEN 0 THEN INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, vItemPackingTypeFk); + VALUES(vSelf, vItemPackingTypeFk); WHEN 1 THEN INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - SELECT vTicketFk, itemPackingTypeFk - FROM tmp.saleGroup + SELECT vSelf, itemPackingTypeFk + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; ELSE - OPEN cur1; - - FETCH cur1 INTO vItemPackingTypeFk; + OPEN vSaleGroup; + FETCH vSaleGroup INTO vItemPackingTypeFk; INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, vItemPackingTypeFk); + VALUES(vSelf, vItemPackingTypeFk); - read_loop: LOOP - FETCH cur1 INTO vItemPackingTypeFk; + l: LOOP + SET vDone = FALSE; + FETCH vSaleGroup INTO vItemPackingTypeFk; IF vDone THEN - LEAVE read_loop; + LEAVE l; END IF; - CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); + CALL ticket_Clone(vSelf, vNewTicketFk); INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vNewTicketFk, vItemPackingTypeFk); END LOOP; - CLOSE cur1; + CLOSE vSaleGroup; - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id + SELECT s.id + FROM sale s + JOIN tSale ts ON ts.id = s.id + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + WHERE s.ticketFk = vSelf + FOR UPDATE; + + UPDATE sale s + JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk SET s.ticketFk = t.ticketFk; SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM tmp.saleGroup sg + FROM tSaleGroup sg WHERE sg.itemPackingTypeFk IS NOT NULL ORDER BY sg.itemPackingTypeFk LIMIT 1; - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id + UPDATE sale s + JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk SET s.ticketFk = t.ticketFk WHERE ts.itemPackingTypeFk IS NULL; END CASE; + COMMIT; + DROP TEMPORARY TABLE - tmp.sale, - tmp.saleGroup; + tSale, + tSaleGroup; END$$ DELIMITER ; -- 2.40.1 From 32793990ec6d86b0ab24181db3416f305c5a3d90 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 14:01:18 +0200 Subject: [PATCH 401/413] refactor: refs #7662 Minor change --- db/routines/vn/procedures/collection_new.sql | 1 - .../ticket_splitItemPackingType.sql | 20 +++++++++---------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index 029427306..cd4b1b47f 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -229,7 +229,6 @@ BEGIN AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk); - DROP TEMPORARY TABLE tmp.ticketIPT; UPDATE tmp.productionBuffer pb JOIN ( diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index bc4c94d46..2a84948c9 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -10,7 +10,6 @@ BEGIN * * @param vSelf Id ticket * @param vItemPackingTypeFk Tipo para el que se reserva el número de ticket original - * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; DECLARE vNewTicketFk INT; @@ -61,17 +60,17 @@ BEGIN FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( + CREATE OR REPLACE TEMPORARY TABLE tTicketIPT( ticketFk INT, itemPackingTypeFk VARCHAR(1) ) ENGINE = MEMORY; CASE vPackingTypesToSplit WHEN 0 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) VALUES(vSelf, vItemPackingTypeFk); WHEN 1 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) SELECT vSelf, itemPackingTypeFk FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; @@ -79,7 +78,7 @@ BEGIN OPEN vSaleGroup; FETCH vSaleGroup INTO vItemPackingTypeFk; - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) VALUES(vSelf, vItemPackingTypeFk); l: LOOP @@ -92,7 +91,7 @@ BEGIN CALL ticket_Clone(vSelf, vNewTicketFk); - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) VALUES(vNewTicketFk, vItemPackingTypeFk); END LOOP; @@ -101,13 +100,13 @@ BEGIN SELECT s.id FROM sale s JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + JOIN tTicketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk WHERE s.ticketFk = vSelf FOR UPDATE; UPDATE sale s JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + JOIN tTicketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk SET s.ticketFk = t.ticketFk; SELECT itemPackingTypeFk INTO vItemPackingTypeFk @@ -118,7 +117,7 @@ BEGIN UPDATE sale s JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk + JOIN tTicketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk SET s.ticketFk = t.ticketFk WHERE ts.itemPackingTypeFk IS NULL; END CASE; @@ -127,6 +126,7 @@ BEGIN DROP TEMPORARY TABLE tSale, - tSaleGroup; + tSaleGroup, + tTicketIPT; END$$ DELIMITER ; -- 2.40.1 From eaca3427772d8c02d6ccc5ad600b2fb075d67dd4 Mon Sep 17 00:00:00 2001 From: guillermo Date: Mon, 8 Jul 2024 14:11:55 +0200 Subject: [PATCH 402/413] refactor: refs #7662 Minor change --- db/routines/vn/procedures/collection_new.sql | 1 + .../ticket_splitItemPackingType.sql | 19 +++++++++---------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index cd4b1b47f..029427306 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -229,6 +229,7 @@ BEGIN AND ((vTicketVolume + @volume) <= vVolumeLimit OR vVolumeLimit IS NULL) THEN CALL ticket_splitItemPackingType(vTicketFk, vItemPackingTypeFk); + DROP TEMPORARY TABLE tmp.ticketIPT; UPDATE tmp.productionBuffer pb JOIN ( diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index 2a84948c9..87fbafe13 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -60,17 +60,17 @@ BEGIN FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; - CREATE OR REPLACE TEMPORARY TABLE tTicketIPT( + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( ticketFk INT, itemPackingTypeFk VARCHAR(1) ) ENGINE = MEMORY; CASE vPackingTypesToSplit WHEN 0 THEN - INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vSelf, vItemPackingTypeFk); WHEN 1 THEN - INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) SELECT vSelf, itemPackingTypeFk FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; @@ -78,7 +78,7 @@ BEGIN OPEN vSaleGroup; FETCH vSaleGroup INTO vItemPackingTypeFk; - INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vSelf, vItemPackingTypeFk); l: LOOP @@ -91,7 +91,7 @@ BEGIN CALL ticket_Clone(vSelf, vNewTicketFk); - INSERT INTO tTicketIPT(ticketFk, itemPackingTypeFk) + INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vNewTicketFk, vItemPackingTypeFk); END LOOP; @@ -100,13 +100,13 @@ BEGIN SELECT s.id FROM sale s JOIN tSale ts ON ts.id = s.id - JOIN tTicketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk WHERE s.ticketFk = vSelf FOR UPDATE; UPDATE sale s JOIN tSale ts ON ts.id = s.id - JOIN tTicketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk SET s.ticketFk = t.ticketFk; SELECT itemPackingTypeFk INTO vItemPackingTypeFk @@ -117,7 +117,7 @@ BEGIN UPDATE sale s JOIN tSale ts ON ts.id = s.id - JOIN tTicketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk SET s.ticketFk = t.ticketFk WHERE ts.itemPackingTypeFk IS NULL; END CASE; @@ -126,7 +126,6 @@ BEGIN DROP TEMPORARY TABLE tSale, - tSaleGroup, - tTicketIPT; + tSaleGroup; END$$ DELIMITER ; -- 2.40.1 From f1276d6f560bf59baaaf01a7721957352bf0ef20 Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 8 Jul 2024 14:51:50 +0200 Subject: [PATCH 403/413] changelog --- CHANGELOG.md | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b322f9f25..4572b137a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,83 @@ +# Version 24.28 - 2024-07-09 + +### Added 🆕 + +- feat boxPicking refs #7357 by:sergiodt +- feat boxPicking refs #7357 (origin/7357_dipole_review) by:sergiodt +- feat:concurrency issue refs #6861 by:Carlos Andrés +- feat expeditionPalletPrint refs #5210 by:sergiodt +- feat front-reservas refs #6861 (origin/6861-Reservas-front) by:sergiodt +- feat itemShelving_filterBuyer refs #7023 by:sergiodt +- feat itemShelvingLog refs #7168 by:sergiodt +- feat itemShelvingSale refs #6861 by:sergiodt +- feat: previas con reserva refs #6861 by:Carlos Andrés +- feat: previas con sitema de reservas refs #6861 by:Carlos Andrés +- feat: previas con sitema de reservas refs #6861 (origin/6861-Pasar-modo-trabajo-de-previa-a-reservas) by:Carlos Andrés +- feat refactor setParking REGEXP refs #7575 (origin/7575_setParking_regExp) by:sergiodt +- feat: refs #6238 add travelKgPercentage table and model (origin/6238-addPercentage) by:jorgep +- feat: refs #6286 check if is teamBoss (origin/6286-setRightWorkerTimeControlAcls) by:jorgep +- feat: refs #6701 Fix error by:guillermo +- feat: refs #6861 trigger by:sergiodt +- feat: refs #7027 mailError managed by:jgallego +- feat: refs #7168 Added vRecords param in proc by:guillermo +- feat: refs #7168 Minor change by:guillermo +- feat: refs #7216 logUnpaid (origin/7216-clientUnpaid) by:jgallego +- feat: refs #7216 triggers by:jgallego +- feat: refs #7296 by:robert +- feat: refs #7296 drop column expeditionTruckFk by:robert +- feat: refs #7490 Changes (origin/7490-duaInvoiceInBooking) by:guillermo +- feat: refs #7545 Deleted hasIncoterms client column (origin/7545-hasIncoterms) by:guillermo +- feat: refs #7555 remove account.password__ by:alexm +- feat: return sql check error by:alexm +- feat roadmap refs #7195 by:sergiodt +- #refs 5890 feat:add assignCollection by:sergiodt +- refs#5890 feat: delete trigger and modify getTickets by:sergiodt +- refs #5890 feat:itemShelving_add by:sergiodt +- refs #5890 feat:reserves by:sergiodt +- refs #5890 feat:trigger by:sergiodt +- refs #5890 feat: triggers by:sergiodt +- refs #6861 feat: getLock by:sergiodt +- refs #6861 feat: obsrevation by:sergiodt +- refs #6861 feat: previas a reservas by:sergiodt +- refs #6861 feat:reserve previos by:sergiodt +- refs #6861 feat: reservePrevious by:sergiodt +- refs #6861 feat:reserveWithReservation by:sergiodt +- refs #6861 feat:sectoCollection reserve by:sergiodt +- refs #6861 feat: skipTest by:sergiodt +- refs #6861 feat: trigger by:sergiodt + +### Changed 📦 + +- feat refactor setParking REGEXP refs #7575 (origin/7575_setParking_regExp) by:sergiodt +- refactor: refs #5447 changed models by:Jon +- refactor: refs #6238 drop useless round by:jorgep +- refactor: refs #6286 replace name by:jorgep +- refactor: refs #6701 Refactor claim_ratio_routine by:guillermo +- refactor: refs #7490 Added final update by:guillermo +- refactor: refs #7490 Deleted update duaInvoiceInBooking by:guillermo +- refactor: refs #7490 Minor changes by:guillermo +- refactor: refs #7519 Minor change by:guillermo + +### Fixed 🛠️ + +- acls, fixtures, models by:carlossa +- fix: refs #6238 delete unused SQL script by:jorgep +- fix: refs #6238 insert ignore by:jorgep +- fix: refs #6238 use scheme by:jorgep +- fix: refs #6286 replace id for reason by:jorgep +- fix: refs #6286 update WorkerTimeControl permissions by:jorgep +- fix(WorkerIncome): refs #7409 fix models by:alexm +- refs #5890 fix: dev by:sergiodt +- refs #6897 fix entry Salix by:carlossa +- refs #6897 fix es.yml by:carlossa +- refs #6897 fix redirection by:carlossa +- refs #6897 fix remove by:carlossa +- refs #7406 fix back by:carlossa +- refs #7406 fix pr by:carlossa +- refs #7409 fix acls by:carlossa +- refs #7409 fix back (origin/7409-workerIncome) by:carlossa +- refs #7409 fix pr by:carlossa + # Version 24.24 - 2024-06-11 ### Added 🆕 -- 2.40.1 From 213524edb598e989e665f21c54982aed3a972079 Mon Sep 17 00:00:00 2001 From: alexm Date: Tue, 9 Jul 2024 07:52:18 +0200 Subject: [PATCH 404/413] deploy: dump db --- db/dump/.dump/data.sql | 53 +- db/dump/.dump/privileges.sql | 54 +- db/dump/.dump/structure.sql | 5799 +++++++++++++++++++--------------- db/dump/.dump/triggers.sql | 105 +- 4 files changed, 3415 insertions(+), 2596 deletions(-) diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index c979ea1a2..43f686022 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -3,7 +3,7 @@ USE `util`; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -INSERT INTO `version` VALUES ('vn-database','11114','cf0f80142fed798c3307565a69158d7dba9276c4','2024-06-25 09:25:54','11115'); +INSERT INTO `version` VALUES ('vn-database','11117','5558e69e648c3819d4a1edf86f8df4b94d36e71a','2024-07-09 07:39:39','11141'); INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL); @@ -644,6 +644,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','10849','15-invoiceInLog.sql','je INSERT INTO `versionLog` VALUES ('vn-database','10849','16-travelLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10849','17-packingSiteDeviceLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10851','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-01-30 13:31:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','10852','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:37',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10853','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:05',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10853','00-secondScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:06',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10854','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-30 16:20:34',NULL,NULL); @@ -776,6 +777,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','10975','01-expeditionFk.sql','je INSERT INTO `versionLog` VALUES ('vn-database','10976','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-18 07:40:57',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10977','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-18 07:40:57',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10978','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:33',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','10983','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:37',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10984','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10988','00-pbx_prefix.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-04-11 17:00:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10990','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); @@ -844,24 +846,39 @@ INSERT INTO `versionLog` VALUES ('vn-database','11068','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11069','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11070','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11071','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11073','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11074','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11075','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-28 12:54:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11078','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11079','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 08:22:10',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11080','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 12:01:58',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11081','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11082','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11083','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-03 10:46:36',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11084','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11086','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-27 10:02:02',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11087','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11089','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11090','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11092','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-07 08:21:23',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11093','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11096','00-addBuyerAcl.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 12:48:51',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11099','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11100','00-modifyTimeControlAcls.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11101','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11102','00-createTravelKgPercentage.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11103','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11104','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11105','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-20 15:36:07',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11106','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11109','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-18 19:09:56',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11110','00-clientUnpaid.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11111','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11114','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11116','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11117','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11134','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-05 11:02:07',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11139','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-08 10:58:01',NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; @@ -958,6 +975,7 @@ INSERT INTO `role` VALUES (126,'greenhouseBoss','Jefe de invernadero',1,'2023-11 INSERT INTO `role` VALUES (127,'timeControl','Tablet para fichar',1,'2024-01-09 16:36:56','2024-01-09 16:36:56',NULL); INSERT INTO `role` VALUES (129,'buyerAssistant','Comprador que tienes mas permisos para ayudar al buyerBoss en algunas tareas',1,'2024-02-06 06:59:12','2024-02-06 06:59:12',783); INSERT INTO `role` VALUES (130,'reviewer','Revisor de producción',1,'2024-06-11 00:00:00','2024-06-11 00:00:00',10578); +INSERT INTO `role` VALUES (131,'supplier','Privilegios básicos de un proveedor',1,'2024-07-05 10:18:58','2024-07-05 10:18:58',19295); INSERT INTO `roleInherit` VALUES (1,1,2,NULL); INSERT INTO `roleInherit` VALUES (2,1,3,NULL); @@ -1228,6 +1246,8 @@ INSERT INTO `roleInherit` VALUES (368,130,49,10578); INSERT INTO `roleInherit` VALUES (369,50,130,10578); INSERT INTO `roleInherit` VALUES (370,72,130,10578); INSERT INTO `roleInherit` VALUES (371,36,35,NULL); +INSERT INTO `roleInherit` VALUES (372,126,13,19295); +INSERT INTO `roleInherit` VALUES (373,131,2,19295); INSERT INTO `userPassword` VALUES (1,7,1,0,2,1); @@ -1886,12 +1906,12 @@ INSERT INTO `ACL` VALUES (772,'Route','getExpeditionSummary','READ','ALLOW','ROL INSERT INTO `ACL` VALUES (773,'WorkerTimeControl','login','READ','ALLOW','ROLE','timeControl'); INSERT INTO `ACL` VALUES (774,'WorkerTimeControl','getClockIn','READ','ALLOW','ROLE','timeControl'); INSERT INTO `ACL` VALUES (775,'WorkerTimeControl','clockIn','WRITE','ALLOW','ROLE','timeControl'); -INSERT INTO `ACL` VALUES (776,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (777,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (778,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (779,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (780,'WorkerTimeControl','updateWorkerTimeControlMail','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (781,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (776,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','teamBoss'); +INSERT INTO `ACL` VALUES (777,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','teamBoss'); +INSERT INTO `ACL` VALUES (778,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','teamBoss'); +INSERT INTO `ACL` VALUES (779,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','developer'); +INSERT INTO `ACL` VALUES (780,'WorkerTimeControl','updateMailState','WRITE','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (781,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','teamBoss'); INSERT INTO `ACL` VALUES (782,'WorkerTimeControl','getMailStates','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (783,'WorkerTimeControl','resendWeeklyHourEmail','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (784,'VnRole','*','READ','ALLOW','ROLE','employee'); @@ -1941,7 +1961,6 @@ INSERT INTO `ACL` VALUES (830,'InvoiceIn','*','READ','ALLOW','ROLE','deliveryBos INSERT INTO `ACL` VALUES (831,'InvoiceIn','exchangeRateUpdate','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (832,'AgencyLog','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (833,'AgencyWorkCenter','*','READ','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (834,'AgencyMode','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (835,'Agency','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (836,'Agency','*','WRITE','ALLOW','ROLE','deliveryAssistant'); INSERT INTO `ACL` VALUES (837,'AgencyWorkCenter','*','WRITE','ALLOW','ROLE','deliveryAssistant'); @@ -1983,6 +2002,24 @@ INSERT INTO `ACL` VALUES (874,'Roadmap','*','READ','ALLOW','ROLE','production'); INSERT INTO `ACL` VALUES (875,'RoadmapStop','*','WRITE','ALLOW','ROLE','palletizerBoss'); INSERT INTO `ACL` VALUES (876,'RoadmapStop','*','READ','ALLOW','ROLE','production'); INSERT INTO `ACL` VALUES (877,'TravelKgPercentage','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (878,'MrwConfig','getLabel','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (879,'AgencyMode','*','*','ALLOW','ROLE','deliveryAssistant'); +INSERT INTO `ACL` VALUES (880,'Collection','assignCollection','WRITE','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (881,'TrainingCourse','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (882,'TrainingCourseType','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (883,'TrainingCenter','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (884,'Worker','__get__trainingCourse','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (885,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (886,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (887,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (888,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (889,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (890,'WorkerTimeControl','updateMailState','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (891,'TravelKgPercentage','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (892,'WorkerIncome','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (893,'PayrollComponent','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (894,'Worker','__get__incomes','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (895,'ItemShelvingLog','*','READ','ALLOW','ROLE','production'); INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee'); INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee'); diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql index b99a60395..c063df7ae 100644 --- a/db/dump/.dump/privileges.sql +++ b/db/dump/.dump/privileges.sql @@ -259,7 +259,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran' INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','salesPerson','inter','alexm@%','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_state','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Articles','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Articles','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','awb','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_component','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -281,8 +281,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','employee','inter','ale INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb','alexm@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','agency','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','buySource','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','buy_edi','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','buy_edi_k04','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k03','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k04','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -313,7 +311,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Cajas',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','cmrConfig','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','awb_recibida','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','awb','juan@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Compres','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','buy_edi','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','ACL','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Vehiculos_consumo','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -348,7 +345,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','empresa','alex INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','sectorType','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Tintas','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','Movimientos','juan@%','0000-00-00 00:00:00','Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Compres','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','ticket_observation','juan@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas_dits','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','sale','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -364,7 +361,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','tickets_ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Tickets','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Entradas','alexm@%','0000-00-00 00:00:00','Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Entradas','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','Tintas','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','filtros','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_kop','alexm@%','0000-00-00 00:00:00','Select',''); @@ -372,9 +369,9 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','flight','jenki INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','zones','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','businessReasonEnd','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','businessCalendar','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','alexm@%','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Entradas','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','buy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','buySource','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','budgetNotes','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','specialLabels','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetDms','alexm@%','0000-00-00 00:00:00','Select,Insert',''); @@ -383,7 +380,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','offerList','juan@d INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','bookingPlanner','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetInvoiceIn','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','beach','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','business','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','business','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Movimientos_revisar','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Movimientos_mark','alexm@%','0000-00-00 00:00:00','Select,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Movimientos_componentes','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -414,7 +411,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Movimientos INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','handmadeBoss','Reservas','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerBoss','bankEntity','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Ordenes','alexm@%','0000-00-00 00:00:00','Select,Update',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','awb','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Origen','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','pago','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','awb','alexm@%','0000-00-00 00:00:00','Update',''); @@ -485,7 +481,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','absenceType','alexm@%',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','artificialBoss','Entradas_Auto','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','Vehiculos_consumo','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','tblContadores','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','buyMark','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','calendar','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','calendarHolidays','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claim','alexm@%','0000-00-00 00:00:00','Select',''); @@ -638,7 +633,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeGroup','a INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','floramondoNotOfferDay__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','fuelType','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeDMS','alexm@%','0000-00-00 00:00:00','Select,Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','genericAllocation','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeComponent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppe','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','glsExpedition__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -744,7 +738,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','mrw','guille INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','mrwService','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppePlan','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','accountingConfig','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','buy','alexm@%','0000-00-00 00:00:00','Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','buy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','buy','alexm@%','0000-00-00 00:00:00','Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleGoal','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','packingSiteLog','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert',''); @@ -759,9 +753,8 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','moving','guill INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machineDetail','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machineDms','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','vehicle','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','awb','alexm@%','0000-00-00 00:00:00','Insert,Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','awb','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machine','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','buy','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_dits','alexm@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerTimeControlMail','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','bi','coolerBoss','rotacion','alexm@%','0000-00-00 00:00:00','Select',''); @@ -909,7 +902,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','ticketService','a INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','ticketServiceType','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketState','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketStateToday','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','bi','employee','claims_ratio','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','greugeType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','time','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketWeekly','alexm@%','0000-00-00 00:00:00','Select',''); @@ -1404,6 +1396,12 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','roadmapStop','guill INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','roadmapStop','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','agencyWorkCenter','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','roadmapStop','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','greenhouseBoss','business','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','teamBoss','business','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketServiceType','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierAgencyTerm','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientRate','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','entryEditor','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientInforma','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','solunionCAP','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -1422,6 +1420,17 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','expedition INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','failureLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','movingLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','sorterLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','genericAllocation','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','businessReasonEnd','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buySource','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','claims_ratio','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_gestdoc','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_state','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','deliveryNote','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','deliveryNoteDms','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','deliveryNoteState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); /*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */; @@ -1481,6 +1490,10 @@ INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','user_id','0 INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','extension','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','name','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','active','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','workerFk','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','id','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','departmentFk','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','companyCodeFk','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','routeFk','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','name','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','beachFk','0000-00-00 00:00:00','Update'); @@ -2018,7 +2031,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','account','developer','user_hasrouti INSERT IGNORE INTO `procs_priv` VALUES ('','account','grafana','user_hasRole','FUNCTION','jgallego@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','time_generate','PROCEDURE','jenkins@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addbyclaim','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelvingtransfer','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addlist','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_selfconsumption','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','item_getsimilar','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2070,7 +2082,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_add',' INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_getsaledate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_filterbuyer','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addbyclaim','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelvingtransfer','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addlist','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_selfconsumption','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','item_getsimilar','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2185,7 +2196,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','financial','{\"access\": 0, \"vers INSERT IGNORE INTO `global_priv` VALUES ('','financialBoss','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}'); INSERT IGNORE INTO `global_priv` VALUES ('','floranet','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','grafana','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','greenhouseBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','greenhouseBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','guest','{\"access\": 0, \"max_questions\": 40000, \"max_updates\": 1000, \"max_connections\": 150000, \"max_user_connections\": 200, \"max_statement_time\": 0.000000, \"is_role\": true, \"version_id\": 101106}'); INSERT IGNORE INTO `global_priv` VALUES ('','handmadeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','hedera-web','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); @@ -2201,7 +2212,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','logisticBoss','{\"access\":0,\"ver INSERT IGNORE INTO `global_priv` VALUES ('','maintenance','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBos','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','manager','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','manager','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','marketing','{\"access\": 0, \"is_role\": true,\"version_id\":101106}'); INSERT IGNORE INTO `global_priv` VALUES ('','marketingBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','officeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); @@ -2220,6 +2231,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','salesPerson','{\"access\": 0, \"is INSERT IGNORE INTO `global_priv` VALUES ('','salesTeamBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','salix','{\"access\":33555456,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','sysadmin','{\"access\": 201326592, \"is_role\": true, \"version_id\": 100707}'); +INSERT IGNORE INTO `global_priv` VALUES ('','teamBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); /*!40000 ALTER TABLE `global_priv` ENABLE KEYS */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index 6797c01a5..9b5e9e4a7 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -449,7 +449,6 @@ CREATE TABLE `user` ( `created` timestamp NOT NULL DEFAULT current_timestamp(), `updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `image` varchar(255) DEFAULT NULL, - `password__` char(64) NOT NULL COMMENT 'Deprecated', `recoverPass` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT 'Deprecated', `sync` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Deprecated', `hasGrant` tinyint(1) NOT NULL, @@ -3109,235 +3108,55 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); - - DELETE FROM analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO analisis_ventas ( - Familia, - Reino, - Comercial, - Comprador, - Provincia, - almacen, - Año, - Mes, - Semana, - Vista, - Importe - ) - SELECT - it.name, - ic.name, - w.code, - w2.code, - p.name, - wa.name, - tm.year, - tm.month, - tm.week, - dm.description, - bt.importe - FROM bs.ventas bt - LEFT JOIN vn.itemType it ON it.id = bt.tipo_id - LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN vn.client c on c.id = bt.Id_Cliente - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.worker w2 ON w2.id = it.workerFk - JOIN vn.time tm ON tm.dated = bt.fecha - JOIN vn.sale s ON s.id = bt.Id_Movimiento - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - LEFT JOIN vn.address a ON a.id = t.addressFk - LEFT JOIN vn.province p ON p.id = a.provinceFk - LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk - WHERE bt.fecha >= vLastMonth AND ic.merchandise; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `claim_ratio_routine` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `claim_ratio_routine`() -BEGIN - DECLARE vMonthToRefund INT DEFAULT 4; - - /* - * PAK 2015-11-20 - * Se trata de añadir a la tabla Greuges todos los - * cargos que luego vamos a utilizar para calcular el recobro - */ - - -- Reclamaciones demasiado sensibles - - INSERT INTO vn.greuge(shipped, clientFk, description, - amount, greugeTypeFk, ticketFk) - SELECT c.ticketCreated - , c.clientFk - , concat('Claim ', c.id,' : ', s.concept) - ,round( -1 * ((c.responsibility -1)/4) * s.quantity * - s.price * (100 - s.discount) / 100, 2) - , 4 - , s.ticketFk - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3; - - -- Reclamaciones que pasan a Maná - - INSERT INTO vn.greuge(shipped, clientFk, description, - amount, greugeTypeFk, ticketFk) - SELECT c.ticketCreated - , c.clientFk - , concat('Claim_mana ',c.id,' : ', s.concept) - ,round( ((c.responsibility -1)/4) * s.quantity * s.price * (100 - s.discount) / 100, 2) - ,3 - ,s.ticketFk - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3 - AND c.isChargedToMana; - - -- Marcamos para no repetir - UPDATE vn.claimEnd ce - JOIN vn.claim c ON c.id = ce.claimFk - SET ce.isGreuge = TRUE - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3; - - -- Recobros - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT DISTINCT t.id Id_Ticket - FROM vn.saleComponent sc - JOIN vn.sale s ON sc.saleFk = s.id - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.ticketLastState ts ON ts.ticketFk = t.id - JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk - JOIN vn.state st ON st.id = tt.stateFk - JOIN vn.alertLevel al ON al.code = 'DELIVERED' - WHERE sc.componentFk = 17 - AND sc.isGreuge = 0 - AND t.shipped >= '2016-10-01' - AND t.shipped < util.VN_CURDATE() - AND st.alertLevel >= al.id; - - DELETE g.* - FROM vn.greuge g - JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket - WHERE g.greugeTypeFk = 2; - - INSERT INTO vn.greuge(clientFk, description, amount,shipped, - greugeTypeFk, ticketFk) - SELECT t.clientFk - ,concat('recobro ', s.ticketFk), - round(SUM(sc.value*s.quantity),2) - AS dif, - date(t.shipped) - , 2 - ,tt.Id_Ticket - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.id - JOIN vn.saleComponent sc - ON sc.saleFk = s.id AND sc.componentFk = 17 - GROUP BY t.id - HAVING ABS(dif) > 1; - - UPDATE vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = s.ticketFk - SET sc.isGreuge = 1 - WHERE sc.componentFk = 17; - - /* - * Recalculamos la ratio de las reclamaciones, que luego - * se va a utilizar en el recobro - */ - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT id, 0,0,0,0 - FROM vn.client; - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, - round(Reclamaciones / (12*fm.Consumo),4), 0 - FROM bi.facturacion_media_anual fm - LEFT JOIN( - SELECT c.clientFk, round(sum(-1 * ((c.responsibility -1)/4) * - s.quantity * s.price * (100 - s.discount) / 100)) - AS Reclamaciones - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND c.claimStateFk = 3 - AND c.ticketCreated >= TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) - GROUP BY c.clientFk - ) claims ON claims.clientFk = fm.Id_Cliente; - - - -- Calculamos el porcentaje del recobro para añadirlo al precio de venta - UPDATE bi.claims_ratio cr - JOIN ( - SELECT clientFk Id_Cliente, IFNULL(SUM(amount), 0) AS Greuge - FROM vn.greuge - WHERE shipped <= util.VN_CURDATE() - GROUP BY clientFk - ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(IFNULL(Greuge, 0) / - (IFNULL(Consumo, 0) * vMonthToRefund / 12 ) ,3)); - - -- Protección neonatos - UPDATE bi.claims_ratio cr - JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente - SET recobro = 0, Ratio = 0 - WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); - - -- CLIENTE 7983, JULIAN SUAU - UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; - - -- CLIENTE 4358 - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; - - -- CLIENTE 5523, VERDECORA - UPDATE bi.claims_ratio SET recobro = GREATEST(0.12, recobro) WHERE Id_Cliente = 5523; - - -- CLIENTE 15979, SERVEIS VETERINARIS - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979; - - -- CLIENTE 5189 i 8942, son de CSR i son el mateix client - UPDATE bi.claims_ratio cr - JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro - FROM bi.claims_ratio - WHERE Id_Cliente IN ( 5189,8942) - ) sub - SET cr.recobro = sub.recobro - WHERE Id_Cliente IN ( 5189,8942); +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, util.VN_CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + it.name, + ic.name, + w.code, + w2.code, + p.name, + wa.name, + tm.year, + tm.month, + tm.week, + dm.description, + bt.importe + FROM bs.ventas bt + LEFT JOIN vn.itemType it ON it.id = bt.tipo_id + LEFT JOIN vn.itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN vn.client c on c.id = bt.Id_Cliente + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN vn.worker w2 ON w2.id = it.workerFk + JOIN vn.time tm ON tm.dated = bt.fecha + JOIN vn.sale s ON s.id = bt.Id_Movimiento + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk + LEFT JOIN vn.address a ON a.id = t.addressFk + LEFT JOIN vn.province p ON p.id = a.provinceFk + LEFT JOIN vn.warehouse wa ON wa.id = t.warehouseFk + WHERE bt.fecha >= vLastMonth AND ic.merchandise; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3355,21 +3174,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); - - DELETE FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - - DELETE FROM bi.defaulters WHERE `date` < vDateLong; - DELETE FROM bi.defaulting WHERE `date` < vDateLong; +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,util.VN_CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,util.VN_CURDATE()); + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3558,18 +3377,18 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bs.clientAnnualConsumption; - - REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) - SELECT clientFk, avg(Facturacion) - FROM ( - SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion - FROM vn.invoiceOut - WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bs.clientAnnualConsumption; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,util.VN_CURDATE()) AND TIMESTAMPADD(DAY, - DAY(util.VN_CURDATE()),util.VN_CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4934,29 +4753,29 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en la tabla @bs.carteras las ventas desde el año pasado - * agrupadas por trabajador, año y mes - */ - DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; - - DELETE FROM bs.carteras WHERE Año >= vYear; - - CALL util.time_generate( - MAKEDATE(vYear, 1), - (SELECT MAX(fecha) FROM ventas) - ); - - INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) - SELECT t.`year`, t.`month`, w.code, SUM(v.importe) - FROM tmp.time t - JOIN ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - GROUP BY w.code, t.`year`, t.`month`; - - DROP TEMPORARY TABLE tmp.time; +BEGIN +/** + * Inserta en la tabla @bs.carteras las ventas desde el año pasado + * agrupadas por trabajador, año y mes + */ + DECLARE vYear INT DEFAULT YEAR(util.VN_CURDATE()) - 1; + + DELETE FROM bs.carteras WHERE Año >= vYear; + + CALL util.time_generate( + MAKEDATE(vYear, 1), + (SELECT MAX(fecha) FROM ventas) + ); + + INSERT INTO carteras(Año, Mes , CodigoTrabajador, Peso) + SELECT t.`year`, t.`month`, w.code, SUM(v.importe) + FROM tmp.time t + JOIN ventas v on t.dated = v.fecha + JOIN vn.client c on c.id = v.Id_Cliente + JOIN vn.worker w ON w.id = c.salesPersonFk + GROUP BY w.code, t.`year`, t.`month`; + + DROP TEMPORARY TABLE tmp.time; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5881,82 +5700,82 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `nightTask_launchAll`() -BEGIN -/** - * Runs all nightly tasks. - */ - DECLARE vDone BOOL; - DECLARE vError VARCHAR(255); - DECLARE vErrorCode VARCHAR(255); - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vLogMail VARCHAR(255); - DECLARE vNightTaskFk INT; - - DECLARE vQueue CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask - WHERE finished <= util.VN_CURDATE() - OR finished IS NULL - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SET max_sp_recursion_depth = 3; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - OPEN vQueue; - l: LOOP - SET vDone = FALSE; - FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; - - IF vDone THEN - LEAVE l; - END IF; - - UPDATE nightTask - SET `started` = util.VN_NOW(), - `finished` = NULL, - `error` = NULL, - `errorCode` = NULL - WHERE id = vNightTaskFk; - - SET vError = NULL; - CALL nightTask_launchTask( - vSchema, - vProcedure, - vError, - vErrorCode - ); - - IF vError IS NOT NULL THEN - IF vLogMail IS NOT NULL THEN - CALL vn.mail_insert( - vLogMail, - NULL, - CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), - CONCAT( - '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break - 'See ', SCHEMA(), '.nightTask table for more info.' - ) - ); - END IF; - - UPDATE nightTask - SET `error` = vError, - `errorCode` = vErrorCode - WHERE id = vNightTaskFk; - ELSE - UPDATE nightTask - SET finished = util.VN_NOW(), - lastFinished = util.VN_NOW() - WHERE id = vNightTaskFk; - END IF; - END LOOP; - CLOSE vQueue; +BEGIN +/** + * Runs all nightly tasks. + */ + DECLARE vDone BOOL; + DECLARE vError VARCHAR(255); + DECLARE vErrorCode VARCHAR(255); + DECLARE vSchema VARCHAR(255); + DECLARE vProcedure VARCHAR(255); + DECLARE vLogMail VARCHAR(255); + DECLARE vNightTaskFk INT; + + DECLARE vQueue CURSOR FOR + SELECT id, `schema`, `procedure` + FROM nightTask + WHERE finished <= util.VN_CURDATE() + OR finished IS NULL + ORDER BY `order`; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET max_sp_recursion_depth = 3; + + SELECT logMail INTO vLogMail + FROM nightTaskConfig LIMIT 1; + + OPEN vQueue; + l: LOOP + SET vDone = FALSE; + FETCH vQueue INTO vNightTaskFk, vSchema, vProcedure; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE nightTask + SET `started` = util.VN_NOW(), + `finished` = NULL, + `error` = NULL, + `errorCode` = NULL + WHERE id = vNightTaskFk; + + SET vError = NULL; + CALL nightTask_launchTask( + vSchema, + vProcedure, + vError, + vErrorCode + ); + + IF vError IS NOT NULL THEN + IF vLogMail IS NOT NULL THEN + CALL vn.mail_insert( + vLogMail, + NULL, + CONCAT('Nightly task failed (', vSchema, '.', vProcedure, ')'), + CONCAT( + '[', vErrorCode, '] ', vError, CHAR(13, 10), -- Line break + 'See ', SCHEMA(), '.nightTask table for more info.' + ) + ); + END IF; + + UPDATE nightTask + SET `error` = vError, + `errorCode` = vErrorCode + WHERE id = vNightTaskFk; + ELSE + UPDATE nightTask + SET finished = util.VN_NOW(), + lastFinished = util.VN_NOW() + WHERE id = vNightTaskFk; + END IF; + END LOOP; + CLOSE vQueue; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6336,8 +6155,8 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`() -BEGIN - CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); +BEGIN + CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7589,27 +7408,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7627,89 +7446,89 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - DECLARE vLastRefresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires, ca.last_refresh - INTO v_cache_id, v_calc, v_expires, vLastRefresh - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + DECLARE vLastRefresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires, ca.last_refresh + INTO v_cache_id, v_calc, v_expires, vLastRefresh + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10228,524 +10047,524 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`() -proc: BEGIN - DECLARE vLanded DATETIME; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vFreeId INT; - DECLARE vSupplyResponseFk INT; - DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; - DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; - DECLARE vDayRange INT; - - DECLARE cur1 CURSOR FOR - SELECT id - FROM edi.item_free; - - DECLARE cur2 CURSOR FOR - SELECT srId - FROM itemToInsert; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); - SET @isTriggerDisabled = FALSE; - RESIGNAL; - END; - - IF 'test' = (SELECT environment FROM util.config) THEN - LEAVE proc; - END IF; - - IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN - LEAVE proc; - END IF; - - SELECT dayRange INTO vDayRange - FROM offerRefreshConfig; - - IF vDayRange IS NULL THEN - CALL util.throw("Variable vDayRange not declared"); - END IF; - - SET vStartingTime = util.VN_NOW(); - - TRUNCATE edi.offerList; - - INSERT INTO edi.offerList(supplier, total) - SELECT v.name, COUNT(DISTINCT sr.ID) total - FROM edi.supplyResponse sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE sr.NumberOfUnits > 0 - AND sr.EmbalageCode != 999 - GROUP BY sr.vmpID; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(*) total - FROM edi.supplyOffer sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.`filter` = sub.total; - - -- Elimina de la lista de items libres aquellos que ya existen - DELETE itf.* - FROM edi.item_free itf - JOIN vn.item i ON i.id = itf.id; - - CREATE OR REPLACE TEMPORARY TABLE tmp - (INDEX (`Item_ArticleCode`)) - ENGINE = MEMORY - SELECT t.* - FROM ( - SELECT * - FROM edi.supplyOffer - ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, - NumberOfUnits DESC LIMIT 10000000000000000000) t - GROUP BY t.srId; - - CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), - INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), - INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) - ENGINE = MEMORY - SELECT so.*, - ev1.type_description s1Value, - ev2.type_description s2Value, - ev3.type_description s3Value, - ev4.type_description s4Value, - ev5.type_description s5Value, - ev6.type_description s6Value, - eif1.feature ef1, - eif2.feature ef2, - eif3.feature ef3, - eif4.feature ef4, - eif5.feature ef5, - eif6.feature ef6 - FROM tmp so - LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode - AND eif1.presentation_order = 1 - AND eif1.expiry_date IS NULL - LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode - AND eif2.presentation_order = 2 - AND eif2.expiry_date IS NULL - LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode - AND eif3.presentation_order = 3 - AND eif3.expiry_date IS NULL - LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode - AND eif4.presentation_order = 4 - AND eif4.expiry_date IS NULL - LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode - AND eif5.presentation_order = 5 - AND eif5.expiry_date IS NULL - LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode - AND eif6.presentation_order = 6 - AND eif6.expiry_date IS NULL - LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature - AND so.s1 = ev1.type_value - LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature - AND so.s2 = ev2.type_value - LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature - AND so.s3 = ev3.type_value - LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature - AND so.s4 = ev4.type_value - LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature - AND so.s5 = ev5.type_value - LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature - AND so.s6 = ev6.type_value - ORDER BY Price; - - DROP TEMPORARY TABLE tmp; - - DELETE o - FROM edi.offer o - LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' - LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' - LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' - LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' - LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' - LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' - JOIN vn.floramondoConfig fc ON TRUE - WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) - OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) - OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) - OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) - OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) - OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); - - START TRANSACTION; - - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos - UPDATE IGNORE edi.offer o - JOIN vn.item i - ON i.name = o.product_name - AND i.subname <=> o.company_name - AND i.value5 <=> o.s1Value - AND i.value6 <=> o.s2Value - AND i.value7 <=> o.s3Value - AND i.value8 <=> o.s4Value - AND i.value9 <=> o.s5Value - AND i.value10 <=> o.s6Value - AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask - AND i.EmbalageCode <=> o.EmbalageCode - AND i.quality <=> o.Quality - JOIN vn.itemType it ON it.id = i.typeFk - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) - LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk - AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) - SET i.supplyResponseFk = o.srID - WHERE (sr.ID IS NULL - OR sr.NumberOfUnits = 0 - OR di.LatestOrderDateTime < util.VN_NOW() - OR di.ID IS NULL) - AND it.isInventory - AND t.id IS NULL - AND po.id IS NULL; - - CREATE OR REPLACE TEMPORARY TABLE itemToInsert - ENGINE = MEMORY - SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk - FROM edi.offer o - LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId - WHERE i.id IS NULL - LIMIT vMaxNewItems; - - -- Reciclado de nº de item - OPEN cur1; - OPEN cur2; - - read_loop: LOOP - - FETCH cur2 INTO vSupplyResponseFk; - FETCH cur1 INTO vFreeId; - - IF vDone THEN - LEAVE read_loop; - END IF; - - UPDATE itemToInsert - SET itemFk = vFreeId - WHERE srId = vSupplyResponseFk; - - END LOOP; - - CLOSE cur1; - CLOSE cur2; - - -- Insertamos todos los items en Articles de la oferta - INSERT INTO vn.item(id, - `name`, - longName, - subName, - expenseFk, - typeFk, - intrastatFk, - originFk, - supplyResponseFk, - numberOfItemsPerCask, - embalageCode, - quality, - isFloramondo) - SELECT iti.itemFk, - iti.product_name, - iti.product_name, - iti.company_name, - iti.expenseFk, - iti.itemTypeFk, - iti.intrastatFk, - iti.originFk, - iti.`srId`, - iti.NumberOfItemsPerCask, - iti.EmbalageCode, - iti.Quality, - TRUE - FROM itemToInsert iti; - - -- Inserta la foto de los articulos nuevos (prioridad alta) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) - SELECT i.id, PictureReference - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.srId - WHERE PictureReference IS NOT NULL - AND i.image IS NULL; - - INSERT INTO edi.`log`(tableName, fieldName,fieldValue) - SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) - FROM vn.itemImageQueue - WHERE attempts = 0; - - -- Inserta si se añadiesen tags nuevos - INSERT IGNORE INTO vn.tag (name, ediTypeFk) - SELECT description, type_id FROM edi.type; - - -- Desabilita el trigger para recalcular los tags al final - SET @isTriggerDisabled = TRUE; - - -- Inserta los tags sólo en los articulos nuevos - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.product_name, 1 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Producto' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.product_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.Quality, 3 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Calidad' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.Quality IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.company_name, 4 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Productor' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.company_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s1Value, 5 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef1 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s1Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s2Value, 6 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef2 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s2Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s3Value, 7 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef3 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s3Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s4Value, 8 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef4 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s4Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s5Value, 9 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef5 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s5Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s6Value, 10 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef6 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s6Value IS NULL; - - INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id - AND tp.`description` = 'Hoofdkleur 1' - LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value - LEFT JOIN vn.itemInk ik ON ik.longName = i.longName - WHERE ink.name IS NOT NULL - OR ik.color IS NOT NULL; - - CREATE OR REPLACE TABLE tmp.item - (PRIMARY KEY (id)) - SELECT i.id FROM vn.item i - JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; - - CALL vn.item_refreshTags(); - - DROP TABLE tmp.item; - - SELECT MIN(LatestDeliveryDateTime) INTO vLanded - FROM edi.supplyResponse sr - JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.floramondoConfig fc - WHERE mp.isLatestOrderDateTimeRelevant - AND di.LatestOrderDateTime > IF( - fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), - util.VN_CURDATE(), - util.VN_CURDATE() + INTERVAL 1 DAY); - - UPDATE vn.floramondoConfig - SET nextLanded = vLanded - WHERE vLanded IS NOT NULL; - - -- Elimina la oferta obsoleta - UPDATE vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID - LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk - SET b.quantity = 0 - WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() - OR i.supplyResponseFk IS NULL - OR sr.NumberOfUnits = 0) - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - -- Localiza las entradas de cada almacen - UPDATE edi.warehouseFloramondo - SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); - - IF vLanded IS NOT NULL THEN - -- Actualiza la oferta existente - UPDATE vn.buy b - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.offer o ON i.supplyResponseFk = o.`srId` - SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, - b.buyingValue = o.price - WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask - OR b.buyingValue <> o.price); - - -- Inserta el resto - SET vLastInserted := util.VN_NOW(); - - -- Inserta la oferta - INSERT INTO vn.buy ( - entryFk, - itemFk, - quantity, - buyingValue, - stickers, - packing, - `grouping`, - groupingMode, - packagingFk, - deliveryFk) - SELECT wf.entryFk, - i.id, - o.NumberOfUnits * o.NumberOfItemsPerCask quantity, - o.Price, - o.NumberOfUnits etiquetas, - o.NumberOfItemsPerCask packing, - GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, - 'packing', - o.embalageCode, - o.diId - FROM edi.offer o - JOIN vn.item i ON i.supplyResponseFk = o.srId - JOIN edi.warehouseFloramondo wf - JOIN vn.packaging p ON p.id - LIKE o.embalageCode - LEFT JOIN vn.buy b ON b.itemFk = i.id - AND b.entryFk = wf.entryFk - WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL - - INSERT INTO vn.itemCost( - itemFk, - warehouseFk, - cm3, - cm3delivery) - SELECT b.itemFk, - wf.warehouseFk, - @cm3 := vn.buy_getUnitVolume(b.id), - IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) - FROM warehouseFloramondo wf - JOIN vn.volumeConfig vc - JOIN vn.buy b ON b.entryFk = wf.entryFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk - AND ic.warehouseFk = wf.warehouseFk - WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) - ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); - - CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc - SELECT b.id - FROM vn.buy b - JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk - WHERE b.created >= vLastInserted; - - CALL vn.buy_recalcPrices(); - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'VNH' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.vnh = sub.total; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'ALGEMESI' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.algemesi = sub.total; - END IF; - - DROP TEMPORARY TABLE - edi.offer, - itemToInsert; - - SET @isTriggerDisabled = FALSE; - - COMMIT; - - -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias - UPDATE vn.item i - SET typeFk = 121 - WHERE i.longName LIKE 'Rosa Garden %' - AND typeFk = 17; - - UPDATE vn.item i - SET typeFk = 156 - WHERE i.longName LIKE 'Rosa ec %' - AND typeFk = 17; - - -- Refresca las fotos de los items existentes que mostramos (prioridad baja) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) - SELECT i.id, sr.PictureReference, 100 - FROM edi.supplyResponse sr - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN edi.supplyOffer so ON so.srId = sr.ID - JOIN hedera.image i2 ON i2.name = i.image - AND i2.collectionFk = 'catalog' - WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) - AND sr.NumberOfUnits; - - INSERT INTO edi.`log` - SET tableName = 'floramondo_offerRefresh', - fieldName = 'Tiempo de proceso', - fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); - - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); +proc: BEGIN + DECLARE vLanded DATETIME; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vFreeId INT; + DECLARE vSupplyResponseFk INT; + DECLARE vLastInserted DATETIME; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vStartingTime DATETIME; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vDayRange INT; + + DECLARE cur1 CURSOR FOR + SELECT id + FROM edi.item_free; + + DECLARE cur2 CURSOR FOR + SELECT srId + FROM itemToInsert; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); + SET @isTriggerDisabled = FALSE; + RESIGNAL; + END; + + IF 'test' = (SELECT environment FROM util.config) THEN + LEAVE proc; + END IF; + + IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN + LEAVE proc; + END IF; + + SELECT dayRange INTO vDayRange + FROM offerRefreshConfig; + + IF vDayRange IS NULL THEN + CALL util.throw("Variable vDayRange not declared"); + END IF; + + SET vStartingTime = util.VN_NOW(); + + TRUNCATE edi.offerList; + + INSERT INTO edi.offerList(supplier, total) + SELECT v.name, COUNT(DISTINCT sr.ID) total + FROM edi.supplyResponse sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + WHERE sr.NumberOfUnits > 0 + AND sr.EmbalageCode != 999 + GROUP BY sr.vmpID; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(*) total + FROM edi.supplyOffer sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.`filter` = sub.total; + + -- Elimina de la lista de items libres aquellos que ya existen + DELETE itf.* + FROM edi.item_free itf + JOIN vn.item i ON i.id = itf.id; + + CREATE OR REPLACE TEMPORARY TABLE tmp + (INDEX (`Item_ArticleCode`)) + ENGINE = MEMORY + SELECT t.* + FROM ( + SELECT * + FROM edi.supplyOffer + ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, + NumberOfUnits DESC LIMIT 10000000000000000000) t + GROUP BY t.srId; + + CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), + INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), + INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) + ENGINE = MEMORY + SELECT so.*, + ev1.type_description s1Value, + ev2.type_description s2Value, + ev3.type_description s3Value, + ev4.type_description s4Value, + ev5.type_description s5Value, + ev6.type_description s6Value, + eif1.feature ef1, + eif2.feature ef2, + eif3.feature ef3, + eif4.feature ef4, + eif5.feature ef5, + eif6.feature ef6 + FROM tmp so + LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode + AND eif1.presentation_order = 1 + AND eif1.expiry_date IS NULL + LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode + AND eif2.presentation_order = 2 + AND eif2.expiry_date IS NULL + LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode + AND eif3.presentation_order = 3 + AND eif3.expiry_date IS NULL + LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode + AND eif4.presentation_order = 4 + AND eif4.expiry_date IS NULL + LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode + AND eif5.presentation_order = 5 + AND eif5.expiry_date IS NULL + LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode + AND eif6.presentation_order = 6 + AND eif6.expiry_date IS NULL + LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature + AND so.s1 = ev1.type_value + LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature + AND so.s2 = ev2.type_value + LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature + AND so.s3 = ev3.type_value + LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature + AND so.s4 = ev4.type_value + LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature + AND so.s5 = ev5.type_value + LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature + AND so.s6 = ev6.type_value + ORDER BY Price; + + DROP TEMPORARY TABLE tmp; + + DELETE o + FROM edi.offer o + LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' + LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' + LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' + LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' + LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' + LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' + JOIN vn.floramondoConfig fc ON TRUE + WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) + OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) + OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) + OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) + OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) + OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); + + START TRANSACTION; + + -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos + UPDATE IGNORE edi.offer o + JOIN vn.item i + ON i.name = o.product_name + AND i.subname <=> o.company_name + AND i.value5 <=> o.s1Value + AND i.value6 <=> o.s2Value + AND i.value7 <=> o.s3Value + AND i.value8 <=> o.s4Value + AND i.value9 <=> o.s5Value + AND i.value10 <=> o.s6Value + AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask + AND i.EmbalageCode <=> o.EmbalageCode + AND i.quality <=> o.Quality + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) + LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk + AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) + SET i.supplyResponseFk = o.srID + WHERE (sr.ID IS NULL + OR sr.NumberOfUnits = 0 + OR di.LatestOrderDateTime < util.VN_NOW() + OR di.ID IS NULL) + AND it.isInventory + AND t.id IS NULL + AND po.id IS NULL; + + CREATE OR REPLACE TEMPORARY TABLE itemToInsert + ENGINE = MEMORY + SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk + FROM edi.offer o + LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId + WHERE i.id IS NULL + LIMIT vMaxNewItems; + + -- Reciclado de nº de item + OPEN cur1; + OPEN cur2; + + read_loop: LOOP + + FETCH cur2 INTO vSupplyResponseFk; + FETCH cur1 INTO vFreeId; + + IF vDone THEN + LEAVE read_loop; + END IF; + + UPDATE itemToInsert + SET itemFk = vFreeId + WHERE srId = vSupplyResponseFk; + + END LOOP; + + CLOSE cur1; + CLOSE cur2; + + -- Insertamos todos los items en Articles de la oferta + INSERT INTO vn.item(id, + `name`, + longName, + subName, + expenseFk, + typeFk, + intrastatFk, + originFk, + supplyResponseFk, + numberOfItemsPerCask, + embalageCode, + quality, + isFloramondo) + SELECT iti.itemFk, + iti.product_name, + iti.product_name, + iti.company_name, + iti.expenseFk, + iti.itemTypeFk, + iti.intrastatFk, + iti.originFk, + iti.`srId`, + iti.NumberOfItemsPerCask, + iti.EmbalageCode, + iti.Quality, + TRUE + FROM itemToInsert iti; + + -- Inserta la foto de los articulos nuevos (prioridad alta) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) + SELECT i.id, PictureReference + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.srId + WHERE PictureReference IS NOT NULL + AND i.image IS NULL; + + INSERT INTO edi.`log`(tableName, fieldName,fieldValue) + SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) + FROM vn.itemImageQueue + WHERE attempts = 0; + + -- Inserta si se añadiesen tags nuevos + INSERT IGNORE INTO vn.tag (name, ediTypeFk) + SELECT description, type_id FROM edi.type; + + -- Desabilita el trigger para recalcular los tags al final + SET @isTriggerDisabled = TRUE; + + -- Inserta los tags sólo en los articulos nuevos + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.product_name, 1 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Producto' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.product_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.Quality, 3 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Calidad' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.Quality IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.company_name, 4 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Productor' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.company_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s1Value, 5 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef1 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s1Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s2Value, 6 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef2 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s2Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s3Value, 7 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef3 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s3Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s4Value, 8 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef4 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s4Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s5Value, 9 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef5 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s5Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s6Value, 10 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef6 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s6Value IS NULL; + + INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + JOIN vn.tag t ON t.`name` = 'Color' + LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode + LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id + AND tp.`description` = 'Hoofdkleur 1' + LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value + LEFT JOIN vn.itemInk ik ON ik.longName = i.longName + WHERE ink.name IS NOT NULL + OR ik.color IS NOT NULL; + + CREATE OR REPLACE TABLE tmp.item + (PRIMARY KEY (id)) + SELECT i.id FROM vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; + + CALL vn.item_refreshTags(); + + DROP TABLE tmp.item; + + SELECT MIN(LatestDeliveryDateTime) INTO vLanded + FROM edi.supplyResponse sr + JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.floramondoConfig fc + WHERE mp.isLatestOrderDateTimeRelevant + AND di.LatestOrderDateTime > IF( + fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), + util.VN_CURDATE(), + util.VN_CURDATE() + INTERVAL 1 DAY); + + UPDATE vn.floramondoConfig + SET nextLanded = vLanded + WHERE vLanded IS NOT NULL; + + -- Elimina la oferta obsoleta + UPDATE vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID + LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk + SET b.quantity = 0 + WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() + OR i.supplyResponseFk IS NULL + OR sr.NumberOfUnits = 0) + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + -- Localiza las entradas de cada almacen + UPDATE edi.warehouseFloramondo + SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); + + IF vLanded IS NOT NULL THEN + -- Actualiza la oferta existente + UPDATE vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, + b.buyingValue = o.price + WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask + OR b.buyingValue <> o.price); + + -- Inserta el resto + SET vLastInserted := util.VN_NOW(); + + -- Inserta la oferta + INSERT INTO vn.buy ( + entryFk, + itemFk, + quantity, + buyingValue, + stickers, + packing, + `grouping`, + groupingMode, + packagingFk, + deliveryFk) + SELECT wf.entryFk, + i.id, + o.NumberOfUnits * o.NumberOfItemsPerCask quantity, + o.Price, + o.NumberOfUnits etiquetas, + o.NumberOfItemsPerCask packing, + GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, + 'packing', + o.embalageCode, + o.diId + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN edi.warehouseFloramondo wf + JOIN vn.packaging p ON p.id + LIKE o.embalageCode + LEFT JOIN vn.buy b ON b.itemFk = i.id + AND b.entryFk = wf.entryFk + WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL + + INSERT INTO vn.itemCost( + itemFk, + warehouseFk, + cm3, + cm3delivery) + SELECT b.itemFk, + wf.warehouseFk, + @cm3 := vn.buy_getUnitVolume(b.id), + IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) + FROM warehouseFloramondo wf + JOIN vn.volumeConfig vc + JOIN vn.buy b ON b.entryFk = wf.entryFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk + AND ic.warehouseFk = wf.warehouseFk + WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) + ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); + + CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc + SELECT b.id + FROM vn.buy b + JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk + WHERE b.created >= vLastInserted; + + CALL vn.buy_recalcPrices(); + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'VNH' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.vnh = sub.total; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.algemesi = sub.total; + END IF; + + DROP TEMPORARY TABLE + edi.offer, + itemToInsert; + + SET @isTriggerDisabled = FALSE; + + COMMIT; + + -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias + UPDATE vn.item i + SET typeFk = 121 + WHERE i.longName LIKE 'Rosa Garden %' + AND typeFk = 17; + + UPDATE vn.item i + SET typeFk = 156 + WHERE i.longName LIKE 'Rosa ec %' + AND typeFk = 17; + + -- Refresca las fotos de los items existentes que mostramos (prioridad baja) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) + SELECT i.id, sr.PictureReference, 100 + FROM edi.supplyResponse sr + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN edi.supplyOffer so ON so.srId = sr.ID + JOIN hedera.image i2 ON i2.name = i.image + AND i2.collectionFk = 'catalog' + WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) + AND sr.NumberOfUnits; + + INSERT INTO edi.`log` + SET tableName = 'floramondo_offerRefresh', + fieldName = 'Tiempo de proceso', + fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); + + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11170,38 +10989,6 @@ CREATE TABLE `recipe` ( -- -- Dumping events for database 'floranet' -- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `clean` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clean` ON SCHEDULE EVERY 1 DAY STARTS '2024-01-01 23:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN - DELETE - FROM `order` - WHERE created < CURDATE() - AND isPaid = FALSE; - - DELETE c.* - FROM catalogue c - LEFT JOIN `order` o ON o.catalogueFk = c.id - WHERE c.created < CURDATE() - AND o.id IS NULL; -END */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; -- -- Dumping routines for database 'floranet' @@ -11245,11 +11032,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `catalogue_get`(vLanded DATE, vPosta READS SQL DATA proc:BEGIN /** - * Returns list, price and all the stuff regarding the floranet items. + * Returns list, price and all the stuff regarding the floranet items, for the designed shop * * @param vLanded Delivery date * @param vPostalCode Delivery address postal code */ + DECLARE vAddressFk INT; DECLARE vLastCatalogueFk INT; DECLARE vLockName VARCHAR(20); DECLARE vLockTime INT; @@ -11260,7 +11048,7 @@ proc:BEGIN RESIGNAL; END; - + SET vLockName = 'catalogue_get'; SET vLockTime = 15; @@ -11271,6 +11059,15 @@ proc:BEGIN SELECT MAX(id) INTO vLastCatalogueFk FROM catalogue; + SELECT addressFk + INTO vAddressFk + FROM addressPostCode apc + WHERE apc.dayOfWeek = dayOfWeek(vLanded) + AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR + AND apc.postCode = vPostalCode + -- Aquí hay que incluir los criterios de selección de tienda + LIMIT 1; + INSERT INTO catalogue( name, price, @@ -11290,17 +11087,14 @@ proc:BEGIN it.name, CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image), i.description, - apc.addressFk + vAddressFk FROM vn.item i JOIN (SELECT itemFk, SUM(quantity * cost) price FROM recipe GROUP BY itemFk) r ON r.itemFk = i.id JOIN vn.itemType it ON it.id = i.typeFk - JOIN addressPostCode apc - ON apc.dayOfWeek = dayOfWeek(vLanded) - AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR - AND apc.postCode = vPostalCode - JOIN vn.address a ON a.id = apc.addressFk; + JOIN addressPostCode apc ON addressFk = vAddressFk + JOIN vn.address a ON a.id = vAddressFk; SELECT * FROM catalogue @@ -11324,28 +11118,28 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( - vName VARCHAR(100), - vPhone VARCHAR(15), - vEmail VARCHAR(100), +CREATE DEFINER=`root`@`localhost` PROCEDURE `contact_request`( + vName VARCHAR(100), + vPhone VARCHAR(15), + vEmail VARCHAR(100), vMessage TEXT) READS SQL DATA -BEGIN -/** - * Set actions for contact request - * - * @param vName Name - * @param vPhone Phone number - * @param vEmail e-mail - * @param vMessage text of the message - */ - - CALL vn.mail_insert( - 'floranet@verdnatura.es', - vEmail, - 'Contact request', - CONCAT('Phone: ',vPhone, ' Message: ', vMessage) - ); +BEGIN +/** + * Set actions for contact request + * + * @param vName Name + * @param vPhone Phone number + * @param vEmail e-mail + * @param vMessage text of the message + */ + + CALL vn.mail_insert( + 'floranet@verdnatura.es', + vEmail, + 'Contact request', + CONCAT('Phone: ',vPhone, ' Message: ', vMessage) + ); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11364,27 +11158,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryDate_get`(vPostalCode VARCHAR(15)) READS SQL DATA -BEGIN -/** - * Returns available dates for this postalCode, in the next seven days. - * - * @param vPostalCode Delivery address postal code - */ - DECLARE vCurrentDayOfWeek INT; - - SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); - - SELECT DISTINCT nextDay - FROM ( - SELECT CURDATE() + INTERVAL IF( - apc.dayOfWeek >= vCurrentDayOfWeek, - apc.dayOfWeek - vCurrentDayOfWeek, - 7 - apc.dayOfWeek - ) DAY nextDay, - NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime - FROM addressPostCode apc - WHERE apc.postCode = vPostalCode - HAVING nextDay > minDeliveryTime) sub; +BEGIN +/** + * Returns available dates for this postalCode, in the next seven days. + * + * @param vPostalCode Delivery address postal code + */ + DECLARE vCurrentDayOfWeek INT; + + SET vCurrentDayOfWeek = DAYOFWEEK(NOW()); + + SELECT DISTINCT nextDay + FROM ( + SELECT CURDATE() + INTERVAL IF( + apc.dayOfWeek >= vCurrentDayOfWeek, + apc.dayOfWeek - vCurrentDayOfWeek, + 7 - apc.dayOfWeek + ) DAY nextDay, + NOW() + INTERVAL apc.hoursInAdvance HOUR minDeliveryTime + FROM addressPostCode apc + WHERE apc.postCode = vPostalCode + HAVING nextDay > minDeliveryTime) sub; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -11500,7 +11294,7 @@ proc:BEGIN vNewTicketFk, c.itemFk, CONCAT('Entrega: ',c.name), - - c.price, + - apc.deliveryCost, 1 FROM catalogue c JOIN addressPostCode apc @@ -11518,7 +11312,7 @@ proc:BEGIN vNewTicketFk, r.elementFk, i.longName, - r.cost, + 0, r.quantity FROM catalogue c JOIN recipe r ON r.itemFk = c.itemFk @@ -28090,6 +27884,8 @@ DROP TABLE IF EXISTS `claimConfig`; CREATE TABLE `claimConfig` ( `id` int(10) unsigned NOT NULL, `maxResponsibility` int(11) DEFAULT NULL, + `monthsToRefund` int(11) DEFAULT NULL, + `minShipped` date DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `claimConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -28426,7 +28222,7 @@ CREATE TABLE `client` ( `transferorFk` int(11) DEFAULT NULL COMMENT 'Cliente que le ha transmitido la titularidad de la empresa', `lastSalesPersonFk` int(10) unsigned DEFAULT NULL COMMENT 'ultimo comercial que tuvo, para el calculo del peso en los rankings de equipo', `businessTypeFk` varchar(20) NOT NULL DEFAULT 'florist', - `hasIncoterms` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Received incoterms authorization from client', + `hasIncoterms__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-06-12 refs #7545 Received incoterms authorization from client', `rating` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa', `recommendedCredit` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa', `editorFk` int(10) unsigned DEFAULT NULL, @@ -28880,7 +28676,10 @@ CREATE TABLE `clientUnpaid` ( `clientFk` int(11) NOT NULL, `dated` date NOT NULL, `amount` double DEFAULT 0, + `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`clientFk`), + KEY `ClientUnpaid_editorFk` (`editorFk`), + CONSTRAINT `ClientUnpaid_editorFk` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `clientUnpaid_clientFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -33212,6 +33011,7 @@ CREATE TABLE `itemShelving` ( `isChecked` tinyint(1) DEFAULT NULL COMMENT 'Este valor cambia al escanear un carro. True: Existe. False: Nuevo. Null: No escaneado', `buyFk` int(11) DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, + `available` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `itemShelving_fk1_idx` (`itemFk`), KEY `itemShelving_fk2_idx` (`shelvingFk`), @@ -33381,6 +33181,21 @@ CREATE TABLE `itemShelvingSale` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle del producto que se retira de los carros, relacionando la linea de movimiento correspondiente'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemShelvingSaleReserve` +-- + +DROP TABLE IF EXISTS `itemShelvingSaleReserve`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemShelvingSaleReserve` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `saleFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `itemShelvingSaleReserve_ibfk_1` (`saleFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed itemShelvingSale to reserve'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `itemShelvingSaleSum` -- @@ -34371,6 +34186,8 @@ CREATE TABLE `mrwConfig` ( `counterWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', `serviceTypeWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', `portugalPostCodeTrim` int(10) unsigned DEFAULT NULL COMMENT 'It will trim the last characters of the postal code', + `notified` timestamp NULL DEFAULT NULL COMMENT 'Date when it was notified that the web service deadline was exceeded', + `clientTypeWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', PRIMARY KEY (`id`), CONSTRAINT `mrwConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -34528,6 +34345,7 @@ CREATE TABLE `operator` ( `labelerFk` int(10) unsigned DEFAULT NULL, `linesLimit` int(11) DEFAULT 20 COMMENT 'Límite de lineas en una colección para la asignación de pedidos', `volumeLimit` decimal(10,6) DEFAULT 0.500000 COMMENT 'Límite de volumen en una colección para la asignación de pedidos', + `isOnReservationMode` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`workerFk`), KEY `operator_FK` (`workerFk`), KEY `operator_FK_1` (`trainFk`), @@ -35019,7 +34837,7 @@ CREATE TABLE `parking` ( UNIQUE KEY `code_UNIQUE` (`code`), KEY `parking_fk1_idx` (`sectorFk`), CONSTRAINT `parking_fk1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `chkParkingCodeFormat` CHECK (char_length(`code`) > 4 and `code` like '%-%') + CONSTRAINT `chkParkingCodeFormat` CHECK (char_length(`code`) > 4 and `code` regexp '^[^ ]+-[^ ]+$') ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla con los parkings del altillo'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -35807,7 +35625,6 @@ CREATE TABLE `productionConfig` ( `pendingCollectionsAge` tinyint(3) unsigned DEFAULT 6, `maxNotAssignedCollectionLifeTime` time NOT NULL DEFAULT '00:10:00' COMMENT 'Tiempo de vida de las colecciones sin asignar. Cuando se supera son eliminadas', `maxProductionScopeDays` int(11) NOT NULL DEFAULT 1 COMMENT 'maximo numero de dias en F11', - `orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location', `stockScopeDays` int(11) DEFAULT 1 COMMENT 'Días a futuro al revisar el stock', `shortageAddressFk` int(11) DEFAULT NULL COMMENT 'Consignatario por defecto para añadir un item de alta', `clientSelfConsumptionFk` int(11) DEFAULT NULL COMMENT 'Cliente para crear el ticket de autoconsumo', @@ -35823,6 +35640,7 @@ CREATE TABLE `productionConfig` ( `itemOlderReviewHours` int(11) NOT NULL DEFAULT 0 COMMENT 'Horas que se tienen en cuenta para comprobar si un ítem es más viejo.', `sectorFromCode` varchar(15) DEFAULT NULL COMMENT 'Sector origen que se revisa ítems más nuevos al parkinear', `sectorToCode` varchar(15) DEFAULT NULL COMMENT 'Sector destino que se revisa ítems más nuevos al parkinear', + `orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location', PRIMARY KEY (`id`), KEY `productionConfig_FK` (`shortageAddressFk`), KEY `productionConfig_FK_1` (`clientSelfConsumptionFk`), @@ -36488,6 +36306,10 @@ CREATE TABLE `roadmap` ( `userFk` int(10) unsigned DEFAULT NULL, `price` decimal(10,2) DEFAULT NULL, `driverName` varchar(45) DEFAULT NULL, + `kmStart` mediumint(9) DEFAULT NULL, + `kmEnd` mediumint(9) DEFAULT NULL, + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `userFk` (`userFk`), KEY `roadmap_supplierFk` (`supplierFk`), @@ -36915,7 +36737,6 @@ CREATE TABLE `routesMonitor` ( `bufferFk` int(11) DEFAULT NULL COMMENT 'Buffer del sorter por el que se quiere sacar esa ruta', `isPickingAllowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Los tickets de esta ruta se pueden preparar', `editorFk` int(10) unsigned DEFAULT NULL, - `expeditionTruckFk` int(11) GENERATED ALWAYS AS (`roadmapStopFk`) VIRTUAL, PRIMARY KEY (`routeFk`), KEY `routesMonitor_FK` (`bufferFk`), KEY `routesMonitor_FK_2` (`beachFk`), @@ -39167,16 +38988,13 @@ CREATE TABLE `ticketPackaging` ( `quantity` int(10) DEFAULT 0, `created` timestamp NOT NULL DEFAULT current_timestamp(), `pvp` double DEFAULT NULL, - `workerFk` int(10) unsigned DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `ticketPackaging_fk1_idx` (`ticketFk`), KEY `ticketPackaging_fk2_idx` (`packagingFk`), - KEY `ticketPackaging_fk3_idx` (`workerFk`), KEY `ticketPackaging_fk_editor` (`editorFk`), CONSTRAINT `ticketPackaging_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `ticketPackaging_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, - CONSTRAINT `ticketPackaging_fk3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `ticketPackaging_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39593,6 +39411,21 @@ CREATE TABLE `tillConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `tillSerial` +-- + +DROP TABLE IF EXISTS `tillSerial`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `tillSerial` ( + `code` varchar(2) NOT NULL, + `description` varchar(30) DEFAULT NULL, + `account` varchar(10) DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `time` -- @@ -41995,15 +41828,33 @@ DELIMITER ;; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN - DELETE FROM itemImageQueue - WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemImageQueue_check` ON SCHEDULE EVERY 1 HOUR STARTS '2023-07-28 00:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN + DELETE FROM itemImageQueue + WHERE attempts >= (SELECT downloadMaxAttempts FROM itemConfig); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; /*!50003 SET character_set_results = @saved_cs_results */ ;; /*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `itemShelvingSale_doReserve` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemShelvingSale_doReserve` ON SCHEDULE EVERY 15 SECOND STARTS '2023-10-16 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.itemShelvingSale_doReserve */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `mysqlConnectionsSorter_kill` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -42689,37 +42540,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `client_getDebt`(`vClient` INT, `vDate` DATE) RETURNS decimal(10,2) READS SQL DATA -BEGIN -/** - * Returns the risk of a customer. - * - * @param vClient client id - * @param vDate date to check the risk - * @return Client risk - */ - DECLARE vDebt DECIMAL(10,2); - DECLARE vHasDebt BOOLEAN; - - SELECT COUNT(*) INTO vHasDebt - FROM `client` c - WHERE c.id = vClient AND c.typeFk = 'normal'; - - IF NOT vHasDebt THEN - RETURN 0; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); - INSERT INTO tmp.clientGetDebt SET clientFk = vClient; - - CALL vn.client_getDebt(vDate); - - SELECT risk INTO vDebt FROM tmp.risk; - - DROP TEMPORARY TABLE - tmp.clientGetDebt, - tmp.risk; - - RETURN vDebt; +BEGIN +/** + * Returns the risk of a customer. + * + * @param vClient client id + * @param vDate date to check the risk + * @return Client risk + */ + DECLARE vDebt DECIMAL(10,2); + DECLARE vHasDebt BOOLEAN; + + SELECT COUNT(*) INTO vHasDebt + FROM `client` c + WHERE c.id = vClient AND c.typeFk = 'normal'; + + IF NOT vHasDebt THEN + RETURN 0; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.clientGetDebt (clientFk INT); + INSERT INTO tmp.clientGetDebt SET clientFk = vClient; + + CALL vn.client_getDebt(vDate); + + SELECT risk INTO vDebt FROM tmp.risk; + + DROP TEMPORARY TABLE + tmp.clientGetDebt, + tmp.risk; + + RETURN vDebt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43744,8 +43595,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `getInventoryDate`() RETURNS date DETERMINISTIC -BEGIN - RETURN (SELECT inventoried FROM config LIMIT 1); +BEGIN + RETURN (SELECT inventoried FROM config LIMIT 1); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45248,6 +45099,44 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP FUNCTION IF EXISTS `sectorCollection_hasSalesReserved` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `sectorCollection_hasSalesReserved`(vSelf INT) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Devuelve si sectorCollection tiene reservas + * @param vSelf Id de sectorCollection + * + * returns BOOLEAN + */ + DECLARE vHasSalesReserved BOOLEAN; + + SELECT DISTINCT COUNT(*) INTO vHasSalesReserved + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup scsg ON sc.id = scsg.sectorCollectionFk + JOIN saleGroup sg ON sg.id = scsg.saleGroupFk + JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id + JOIN sale s ON s.id = sgd.saleFk + JOIN itemShelvingSale iss ON iss.saleFk = s.id + JOIN saleTracking st ON st.saleFk = s.id + WHERE sc.id = vSelf; + + RETURN vHasSalesReserved; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `specie_IsForbidden` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -45819,62 +45708,42 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_get`(vParamFk INT) RETURNS int(11) READS SQL DATA -proc:BEGIN - - /* Devuelve el número de ticket o collection consultando en varias tablas posibles - * - * @param vParamFk Número a validar - * @return vValidFk Identificador validado - */ - - DECLARE vValidFk INT; +BEGIN +/** + * Devuelve el número de ticket / collection / sectorCollection consultando + * en que tabla se encuantra en la última semana + * + * @param vParamFk Número a validar + * @return vReturn Identificador validado + */ + DECLARE vReturn INT DEFAULT NULL; + DECLARE vDated DATE; - -- Tabla vn.saleGroup - SELECT s.ticketFk INTO vValidFk - FROM vn.sale s - JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk - WHERE sg.id = vParamFk - AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()) - LIMIT 1; - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; + SET vDated = util.VN_CURDATE() - INTERVAL 1 WEEK; - -- Tabla vn.collection - SELECT c.id INTO vValidFk - FROM vn.collection c - WHERE c.id = vParamFk - AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; + SELECT COALESCE( + (SELECT s.ticketFk + FROM sale s + JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + WHERE sg.id = vParamFk + AND sg.created > vDated + LIMIT 1), + (SELECT c.id + FROM collection c + WHERE c.id = vParamFk + AND c.created > vDated), + (SELECT id + FROM ticket + WHERE id = vParamFk + AND shipped > vDated), + (SELECT id + FROM sectorCollection + WHERE id = vParamFk + AND created > vDated) + ) INTO vReturn; - -- Tabla vn.ticket - SELECT t.id INTO vValidFk - FROM vn.ticket t - WHERE t.id = vParamFk - AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; - - RETURN NULL; + RETURN vReturn; END ;; DELIMITER ; @@ -49618,6 +49487,209 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `claimRatio_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `claimRatio_add`() +BEGIN +/* +* Añade a la tabla greuges todos los cargos necesario y +* que luego lo utilizamos para calcular el recobro. +*/ + DECLARE vMonthToRefund INT + DEFAULT (SELECT monthsToRefund FROM claimConfig); + DECLARE vRecoveryGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'recovery'); + DECLARE vManaGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'mana'); + DECLARE vClaimGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'claim'); + DECLARE vDebtComponentType INT + DEFAULT (SELECT id FROM component WHERE code = 'debtCollection'); + + IF vMonthToRefund IS NULL + OR vRecoveryGreugeType IS NULL + OR vManaGreugeType IS NULL + OR vClaimGreugeType IS NULL + OR vDebtComponentType IS NULL THEN + + CALL util.throw('Required variables not found'); + END IF; + + -- Reclamaciones demasiado sensibles + INSERT INTO greuge( + shipped, + clientFk, + `description`, + amount, + greugeTypeFk, + ticketFk + ) + SELECT c.ticketCreated, + c.clientFk, + CONCAT('Claim ', c.id,' : ', s.concept), + ROUND(-1 * ((c.responsibility - 1) / 4) * s.quantity * + s.price * (100 - s.discount) / 100, 2), + vClaimGreugeType, + s.ticketFk + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved'; + + -- Reclamaciones que pasan a Maná + INSERT INTO greuge( + shipped, + clientFk, + `description`, + amount, + greugeTypeFk, + ticketFk + ) + SELECT c.ticketCreated, + c.clientFk, + CONCAT('Claim_mana ', c.id,' : ', s.concept), + ROUND(((c.responsibility - 1) / 4) * s.quantity * + s.price * (100 - s.discount) / 100, 2), + vManaGreugeType, + s.ticketFk + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved' + AND c.isChargedToMana; + + -- Marcamos para no repetir + UPDATE claimEnd ce + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + SET ce.isGreuge = TRUE + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved'; + + -- Recobros + CREATE OR REPLACE TEMPORARY TABLE tTicketList + (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY + SELECT DISTINCT s.ticketFk + FROM saleComponent sc + JOIN sale s ON sc.saleFk = s.id + JOIN ticket t ON t.id = s.ticketFk + JOIN ticketLastState ts ON ts.ticketFk = t.id + JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk + JOIN state st ON st.id = tt.stateFk + JOIN alertLevel al ON al.id = st.alertLevel + WHERE sc.componentFk = vDebtComponentType + AND NOT sc.isGreuge + AND t.shipped >= (SELECT minShipped FROM claimConfig) + AND t.shipped < util.VN_CURDATE() + AND al.code = 'DELIVERED'; + + DELETE g.* + FROM greuge g + JOIN tTicketList t ON t.ticketFk = g.ticketFk + WHERE g.greugeTypeFk = vRecoveryGreugeType; + + INSERT INTO greuge( + clientFk, + `description`, + amount, + shipped, + greugeTypeFk, + ticketFk + ) + SELECT t.clientFk, + 'Recobro', + - ROUND(SUM(sc.value * s.quantity), 2) dif, + DATE(t.shipped), + vRecoveryGreugeType, + tl.ticketFk + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN tTicketList tl ON tl.ticketFk = t.id + JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = vDebtComponentType + GROUP BY t.id + HAVING ABS(dif) > 1; + + UPDATE saleComponent sc + JOIN sale s ON s.id = sc.saleFk + JOIN tTicketList tl ON tl.ticketFk = s.ticketFk + SET sc.isGreuge = TRUE + WHERE sc.componentFk = vDebtComponentType; + + REPLACE claimRatio( + clientFk, + yearSale, + claimAmount, + claimingRate, + priceIncreasing + ) + SELECT c.id, + 12 * cac.invoiced, + totalClaims, + ROUND(totalClaims / (12 * cac.invoiced), 4), + 0 + FROM client c + LEFT JOIN bs.clientAnnualConsumption cac ON cac.clientFk = c.id + LEFT JOIN ( + SELECT c.clientFk, + ROUND(SUM(-1 * ((c.responsibility - 1) / 4) * + s.quantity * s.price * (100 - s.discount) + / 100)) totalClaims + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND cs.code = 'resolved' + AND c.ticketCreated >= util.VN_CURDATE() - INTERVAL 1 YEAR + GROUP BY c.clientFk + ) sub ON sub.clientFk = c.id; + + -- Calculamos el porcentaje del recobro para añadirlo al precio de venta + UPDATE claimRatio cr + JOIN ( + SELECT clientFk, IFNULL(SUM(amount), 0) greuge + FROM greuge + WHERE shipped <= util.VN_CURDATE() + GROUP BY clientFk + ) sub ON sub.clientFk = cr.clientFk + SET cr.priceIncreasing = GREATEST(0, ROUND(IFNULL(sub.greuge, 0) / + (IFNULL(cr.yearSale, 0) * vMonthToRefund / 12 ), 3)); + + -- Protección neonatos + UPDATE claimRatio cr + JOIN firstTicketShipped fts ON fts.clientFk = cr.clientFk + SET cr.priceIncreasing = 0, + cr.claimingRate = 0 + WHERE fts.shipped > util.VN_CURDATE() - INTERVAL 1 MONTH; + + DROP TEMPORARY TABLE tTicketList; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `clean` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51008,6 +51080,7 @@ BEGIN JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk + JOIN bs.clientDiedPeriod cdp ON cdp.countryFk = co.id WHERE cd.warning = 'third' AND cp.clientFk IS NULL AND sp.salesPersonFk IS NULL @@ -51370,6 +51443,108 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_addWithReservation` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_addWithReservation`( + vItemFk INT, + vQuantity INT, + vTicketFk INT, + vSaleGroupFk INT +) +BEGIN +/** + * En el ámbito de las colecciones se añade una línea de sale a un ticket + * de una colección en caso de tener disponible y se realiza la reserva. + * + * @param vItemFk id of item + * @param vQuantity quantity to be added to the ticket + * @param vTicketFk ticket to which the sales line is added + * @param vSaleGroupFk saleGroupFk id to add saleGroupDetail + */ + + DECLARE vWarehouseFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vAvailable INT; + DECLARE vSaleFk INT; + DECLARE vConcept VARCHAR(50); + DECLARE vItemName VARCHAR(50); + DECLARE vHasThrow BOOLEAN DEFAULT FALSE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT t.warehouseFk INTO vWarehouseFk + FROM ticket t + JOIN ticketCollection tc ON tc.ticketFk = t.id + WHERE t.id = vTicketFk; + + CALL cache.available_refresh( + vCacheAvailableFk, + FALSE, + vWarehouseFk, + util.VN_CURDATE()); + + SELECT available INTO vAvailable + FROM cache.available + WHERE calc_id = vCacheAvailableFk + AND item_id = vItemFk; + + IF vAvailable < vQuantity THEN + SET vHasThrow = TRUE; + ELSE + SELECT `name`, + CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) + INTO vItemName, vConcept + FROM item + WHERE id = vItemFk; + + START TRANSACTION; + + INSERT INTO sale + SET itemFk = vItemFk, + ticketFk = vTicketFk, + concept = vConcept, + quantity = vQuantity, + isAdded = TRUE; + + SELECT LAST_INSERT_ID() INTO vSaleFk; + + CALL sale_calculateComponent(vSaleFk, NULL); + CALL itemShelvingSale_addBySale(vSaleFk); + + IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN + SET vHasThrow = TRUE; + END IF; + END IF; + + IF vHasThrow THEN + CALL util.throw("There is no available for the selected item"); + END IF; + + IF vSaleGroupFk THEN + INSERT INTO saleGroupDetail + SET saleFk = vSaleFk, + saleGroupFk = vSaleGroupFk; + END IF; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `collection_assign` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51378,82 +51553,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( - vUserFk INT, - OUT vCollectionFk INT +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`( + vUserFk INT, + OUT vCollectionFk INT ) -BEGIN -/** - * Comprueba si existen colecciones libres que se ajustan - * al perfil del usuario y le asigna la más antigua. - * Añade un registro al semillero de colecciones. - * - * @param vUserFk Id de usuario - * @param vCollectionFk Id de colección - */ - DECLARE vHasTooMuchCollections BOOL; - - -- Si hay colecciones sin terminar, sale del proceso - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections - FROM productionConfig pc - LEFT JOIN tmp.collection ON TRUE; - - DROP TEMPORARY TABLE tmp.collection; - - IF vHasTooMuchCollections THEN - CALL util.throw('Hay colecciones pendientes'); - END IF; - - -- Se eliminan las colecciones sin asignar que estan obsoletas - INSERT INTO ticketTracking(stateFk, ticketFk) - SELECT s.id, tc.ticketFk - FROM `collection` c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN `state` s ON s.code = 'PRINTED_AUTO' - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - DELETE c.* - FROM `collection` c - JOIN productionConfig pc - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - INSERT INTO collectionHotbed(userFk) - VALUES(vUserFk); - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - SELECT MIN(c.id) INTO vCollectionFk - FROM `collection` c - JOIN operator o - ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk - AND c.workerFk IS NULL - AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) - JOIN ( - SELECT tc.collectionFk, SUM(sv.volume) volume - FROM ticketCollection tc - JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk - WHERE sv.shipped >= util.VN_CURDATE() - GROUP BY tc.collectionFk - ) sub ON sub.collectionFk = c.id - AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) - WHERE o.workerFk = vUserFk; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - END IF; - - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan + * al perfil del usuario y le asigna la más antigua. + * Añade un registro al semillero de colecciones. + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; + + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + CALL util.debugAdd('collection_assign', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk + )); -- Tmp + END IF; + + RESIGNAL; + END; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName + FROM productionConfig pc + LEFT JOIN tmp.collection ON TRUE; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('Hay colecciones pendientes'); + END IF; + + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM `collection` c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN `state` s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c.* + FROM `collection` c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed(userFk) + VALUES(vUserFk); + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM `collection` c + JOIN operator o + ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + JOIN ( + SELECT tc.collectionFk, SUM(sv.volume) volume + FROM ticketCollection tc + JOIN saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) sub ON sub.collectionFk = c.id + AND (volume <= o.volumeLimit OR o.volumeLimit IS NULL) + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + DO RELEASE_LOCK(vLockName); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51478,26 +51697,31 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tmp.collection; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; - CREATE TEMPORARY TABLE tmp.collection - SELECT c.id collectionFk, - date(c.created) created, - COUNT(DISTINCT tc.ticketFk) ticketTotalCount - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk - JOIN ticketState ts ON ts.ticketFk = tc.ticketFk - JOIN state s2 ON s2.id = ts.stateFk - JOIN productionConfig pc - JOIN vn.state ss on ss.code = 'PREPARED' - LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk - AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge - AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder - GROUP BY c.id - HAVING COUNT(*) > COUNT(DISTINCT st.id); + CREATE OR REPLACE TEMPORARY TABLE tmp.collection + ENGINE = MEMORY + SELECT c.id collectionFk, + DATE(c.created) created, + COUNT(DISTINCT tc.ticketFk) ticketTotalCount + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk + JOIN ticketState ts ON ts.ticketFk = tc.ticketFk + JOIN state s2 ON s2.id = ts.stateFk + JOIN productionConfig pc + JOIN vn.state ss ON ss.code = 'PREPARED' + LEFT JOIN vn.saleTracking st ON st.saleFk = s.id + AND st.stateFk = ss.id + WHERE c.workerFk = vWorkerFk + AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge + AND s.quantity + AND s2.order < pc.pendingCollectionsOrder + GROUP BY c.id + HAVING COUNT(*) > COUNT(DISTINCT st.id); SELECT * FROM tmp.collection; END ;; @@ -51508,6 +51732,123 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_getAssigned` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_getAssigned`( + vUserFk INT, + OUT vCollectionFk INT +) +BEGIN +/** + * Comprueba si existen colecciones libres que se ajustan al perfil del usuario + * y le asigna la más antigua. + * Añade un registro al semillero de colecciones y hace la reserva para la colección + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + END IF; + + RESIGNAL; + END; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + pc.collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName + FROM tmp.collection c + JOIN productionConfig pc; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('There are pending collections'); + END IF; + + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN state s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c + FROM collection c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed + SET userFk = vUserFk; + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM collection c + JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk + OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE collection + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + CALL itemShelvingSale_addByCollection(vCollectionFk); + + DO RELEASE_LOCK(vLockName); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `collection_getTickets` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51519,62 +51860,89 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_getTickets`(vParamFk INT) BEGIN /** - * Selecciona los tickets de una colección/ticket - * @param vParamFk ticketFk/collectionFk - * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones + * Selecciona los tickets de una colección/ticket/sectorCollection + * @param vParamFk ticketFk/collectionFk/sectorCollection + * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observation */ DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vYesterday DATE; -- Si los sacadores son los de pruebas, pinta los colores - SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + SELECT itemPackingTypeFk + INTO vItemPackingTypeFk + FROM collection WHERE id = vParamFk; + + SET vYesterday = util.yesterday(); - SELECT t.id ticketFk, - IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, - am.name agencyName, - t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description,'') observaciones, - cc.rgb - FROM vn.ticket t - LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.client c ON c.id = t.clientFk - LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id - AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk - AND t.shipped >= util.yesterday() - UNION ALL + WITH observation AS ( + SELECT tob.ticketFk, tob.description + FROM vn.ticketObservation tob + JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk + LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk + WHERE ot.`code` = 'itemPicker' + AND tc.collectionFk = vParamFk + ) SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description, '') observaciones, - IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` + w.id salesPersonFk, + IFNULL(ob.description,'') observaciones, + cc.rgb FROM vn.ticket t - JOIN vn.ticketCollection tc ON t.id = tc.ticketFk - LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 + LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk LEFT JOIN vn.collectionColors cc ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 + AND cc.shelve = tc.`level` + AND cc.trainFk = c2.trainFk LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id - AND tob.observationTypeFk = 1 - WHERE tc.collectionFk = vParamFk; - + LEFT JOIN observation ob ON ob.ticketFk = t.id + WHERE t.id = vParamFk + AND t.shipped >= vYesterday + UNION ALL + SELECT t.id ticketFk, + IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, + am.name agencyName, + t.warehouseFk, + w.id salesPersonFk, + ob.description, + IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` + FROM vn.ticket t + JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` + AND cc.trainFk = c2.trainFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN vn.worker w ON w.id = c.salesPersonFk + LEFT JOIN observation ob ON ob.ticketFk = t.id + WHERE tc.collectionFk = vParamFk + UNION ALL + SELECT sg.ticketFk, + NULL `level`, + am.name agencyName, + t.warehouseFk, + c.salesPersonFk, + ob.description, + NULL `rgb` + FROM vn.sectorCollection sc + JOIN vn.sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN vn.saleGroup sg ON sg.id = ss.saleGroupFk + JOIN vn.ticket t ON t.id = sg.ticketFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN observation ob ON ob.ticketFk = t.id + LEFT JOIN vn.client c ON c.id = t.clientFk + WHERE sc.id = vParamFk + AND t.shipped >= vYesterday; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51761,7 +52129,8 @@ BEGIN 'errorNumber', vErrorNumber, 'errorMsg', vErrorMsg, 'lockName', vLockName, - 'userFk', vUserFk + 'userFk', vUserFk, + 'ticketFk', vTicketFk )); -- Tmp END IF; @@ -53527,7 +53896,9 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `duaInvoiceInBooking`( + vDuaFk INT +) BEGIN /** * Genera el asiento de un DUA y marca las entradas como confirmadas @@ -53557,27 +53928,25 @@ BEGIN SET ii.booked = IFNULL(ii.booked, d.booked), ii.operated = IFNULL(ii.operated, d.operated), ii.issued = IFNULL(ii.issued, d.issued), - ii.bookEntried = IFNULL(ii.bookEntried, d.bookEntried), - e.isBooked = TRUE, - e.isConfirmed = TRUE + ii.bookEntried = IFNULL(ii.bookEntried, d.bookEntried) WHERE d.id = vDuaFk; SELECT ASIEN INTO vBookEntry FROM dua WHERE id = vDuaFk; - IF vBookEntry IS NULL THEN + IF vBookEntry IS NULL THEN SELECT YEAR(IFNULL(ii.bookEntried, d.bookEntried)) INTO vFiscalYear FROM invoiceIn ii - JOIN entry e ON e.invoiceInFk = ii.id + JOIN `entry` e ON e.invoiceInFk = ii.id JOIN duaEntry de ON de.entryFk = e.id JOIN dua d ON d.id = de.duaFk WHERE d.id = vDuaFk LIMIT 1; CALL ledger_nextTx(vFiscalYear, vBookEntry); - END IF; + END IF; OPEN vInvoicesIn; -l: LOOP + l: LOOP SET vDone = FALSE; FETCH vInvoicesIn INTO vInvoiceFk; @@ -53598,6 +53967,29 @@ l: LOOP JOIN duaInvoiceIn dii ON dii.invoiceInFk = ii.id SET ii.isBooked = TRUE WHERE dii.duaFk = vDuaFk; + + UPDATE `entry` e + JOIN ( + WITH entries AS ( + SELECT e.id, de.duaFk + FROM vn.`entry` e + JOIN vn.duaEntry de ON de.entryFk = e.id + WHERE de.duaFk = vDuaFk + AND (NOT e.isBooked OR NOT e.isConfirmed) + ), + notBookedEntries AS ( + SELECT e.id + FROM vn.duaEntry + WHERE duaFk = vDuaFk + AND NOT customsValue + ) + SELECT e.id + FROM entries e + LEFT JOIN notBookedEntries nbe ON nbe.entryFk = e.id + WHERE nbe.entryFk IS NULL + ) sub ON sub.id = e.id + SET e.isBooked = TRUE, + e.isConfirmed = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55487,14 +55879,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `expeditionPallet_printLabel` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT) BEGIN @@ -55506,7 +55898,16 @@ BEGIN */ DECLARE vPrinterFk INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + DECLARE vIsInExpeditionPallet BOOL; + + SELECT COUNT(id) INTO vIsInExpeditionPallet + FROM expeditionPallet + WHERE id = vSelf; + + IF NOT vIsInExpeditionPallet THEN + CALL util.throw("ExpeditionPallet not exists"); + END IF; + SELECT o.labelerFk INTO vPrinterFk FROM operator o WHERE o.workerFk = vUserFk; @@ -57145,7 +57546,6 @@ BEGIN */ DECLARE vTaxRowLimit INT; DECLARE vLines INT; - DECLARE vHasDistinctTransactions INT; SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig; @@ -57157,18 +57557,6 @@ BEGIN IF vLines >= vTaxRowLimit THEN CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit)); END IF; - - SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN invoiceInSerial iis ON iis.code = ii.serial - WHERE ii.id = vInvoiceInFk - AND iis.taxAreaFk = 'CEE' - AND transactionTypeSageFk; - - IF vHasDistinctTransactions > 1 THEN - CALL util.throw ('This invoice does not allow different types of transactions'); - END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57381,6 +57769,19 @@ BEGIN * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo */ DECLARE vFiscalYear INT; + DECLARE vHasDistinctTransactions INT; + + SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + JOIN invoiceInSerial iis ON iis.code = ii.serial + WHERE ii.id = vSelf + AND iis.taxAreaFk = 'CEE' + AND transactionTypeSageFk; + + IF vHasDistinctTransactions > 1 THEN + CALL util.throw ('This invoice does not allow different types of transactions'); + END IF; CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY @@ -59784,7 +60185,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserve` */; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addByCollection` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -59792,302 +60193,53 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserve`() -BEGIN -/** - * Reserva cantidades con ubicaciones para un conjunto de sales del mismo - * almacen. - * - * @table tmp.sale(saleFk, userFk) - */ - DECLARE vCalcFk INT; - DECLARE vWarehouseFk INT; - DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW()); - DECLARE vLastPickingOrder INT; - - SELECT t.warehouseFk, MAX(p.pickingOrder) - INTO vWarehouseFk, vLastPickingOrder - FROM ticket t - JOIN sale s ON s.ticketFk = t.id - JOIN tmp.sale ts ON ts.saleFk = s.id - LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk - LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk - LEFT JOIN shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN parking p ON p.id = sh.parkingFk - WHERE t.warehouseFk IS NOT NULL; - - IF vWarehouseFk IS NULL THEN - CALL util.throw('Warehouse not set'); - END IF; - - CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); - - SET @outstanding = 0; - SET @oldsaleFk = 0; - - CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity - (INDEX(saleFk)) - ENGINE = MEMORY - SELECT saleFk, userFk, quantityToReserve, itemShelvingFk - FROM( SELECT saleFk, - sub.userFk, - itemShelvingFk , - IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding), - @qtr := LEAST(@outstanding, available) quantityToReserve, - @outStanding := @outStanding - @qtr, - @oldsaleFk := saleFk - FROM( - SELECT ts.saleFk, - ts.userFk, - s.quantity, - ish.id itemShelvingFk, - ish.visible - IFNULL(ishr.reservedQuantity, 0) available - FROM tmp.sale ts - JOIN sale s ON s.id = ts.saleFk - JOIN itemShelving ish ON ish.itemFk = s.itemFk - LEFT JOIN ( - SELECT itemShelvingFk, SUM(quantity) reservedQuantity - FROM itemShelvingSale - WHERE NOT isPicked - GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON p.id = sh.parkingFk - JOIN sector sc ON sc.id = p.sectorFk - JOIN warehouse w ON w.id = sc.warehouseFk - JOIN productionConfig pc - WHERE w.id = vWarehouseFk - AND NOT sc.isHideForPickers - ORDER BY - s.id, - p.pickingOrder >= vLastPickingOrder, - sh.priority DESC, - ish.visible >= s.quantity DESC, - s.quantity MOD ish.grouping = 0 DESC, - ish.grouping DESC, - IF(pc.orderMode = 'Location', p.pickingOrder, ish.created) - )sub - )sub2 - WHERE quantityToReserve > 0; - - INSERT INTO itemShelvingSale( - itemShelvingFk, - saleFk, - quantity, - userFk) - SELECT itemShelvingFk, - saleFk, - quantityToReserve, - IFNULL(userFk, getUser()) - FROM tSalePlacementQuantity spl; - - DROP TEMPORARY TABLE tmp.sale; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveByCollection` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveByCollection`( - vCollectionFk INT(11) +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addByCollection`( + vCollectionFk INT(11) ) -BEGIN -/** - * Reserva cantidades con ubicaciones para el contenido de una colección - * - * @param vCollectionFk Identificador de collection - */ - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) - ENGINE = MEMORY - SELECT s.id saleFk, NULL userFk - FROM ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - LEFT JOIN ( - SELECT DISTINCT saleFk - FROM saleTracking st - JOIN state s ON s.id = st.stateFk - WHERE st.isChecked - AND s.semaphore = 1)st ON st.saleFk = s.id - WHERE tc.collectionFk = vCollectionFk - AND st.saleFk IS NULL - AND NOT s.isPicked; - - CALL itemShelvingSale_reserve(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveBySale` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveBySale`( - vSelf INT , - vQuantity INT, - vUserFk INT -) -BEGIN -/** - * Reserva cantida y ubicación para una saleFk - * - * @param vSelf Identificador de la venta - * @param vQuantity Cantidad a reservar - * @param vUserFk Id de usuario que realiza la reserva - */ - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - ENGINE = MEMORY - SELECT vSelf saleFk, vUserFk userFk; - - CALL itemShelvingSale_reserve(); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setQuantity` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( - vItemShelvingSaleFk INT(10), - vQuantity DECIMAL(10,0), - vIsItemShelvingSaleEmpty BOOLEAN -) -BEGIN -/** - * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity - * en vn.itemShelvingSale y vn.sale.isPicked en caso necesario. - * Si la reserva de la ubicación es fallida, se regulariza la situación - * - * @param vItemShelvingSaleFk Id itemShelvingSaleFK - * @param vQuantity Cantidad real que se ha cogido de la ubicación - * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha - * quedado vacio tras el movimiento - */ - DECLARE vSaleFk INT; - DECLARE vCursorSaleFk INT; - DECLARE vItemShelvingFk INT; - DECLARE vReservedQuantity INT; - DECLARE vRemainingQuantity INT; - DECLARE vItemFk INT; - DECLARE vUserFk INT; - DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE vSales CURSOR FOR - SELECT iss.saleFk, iss.userFk - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND s.itemFk = vItemFk - AND NOT iss.isPicked; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN - CALL util.throw('Booking completed'); - END IF; - - SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk - INTO vItemFk, vSaleFk, vItemShelvingFk - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND NOT iss.isPicked; - - UPDATE itemShelvingSale - SET isPicked = TRUE, - quantity = vQuantity - WHERE id = vItemShelvingSaleFk; - - UPDATE itemShelving - SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity)) - WHERE id = vItemShelvingFk; - - IF vIsItemShelvingSaleEmpty THEN - OPEN vSales; -l: LOOP - SET vDone = FALSE; - FETCH vSales INTO vCursorSaleFk, vUserFk; - IF vDone THEN - LEAVE l; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk, userFk)) - ENGINE = MEMORY - SELECT vCursorSaleFk, vUserFk; - - CALL itemShelvingSale_reserveWhitUser(); - DROP TEMPORARY TABLE tmp.sale; - - END LOOP; - CLOSE vSales; - - DELETE iss - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND s.itemFk = vItemFk - AND NOT iss.isPicked; - END IF; - - SELECT SUM(quantity) INTO vRemainingQuantity - FROM itemShelvingSale - WHERE saleFk = vSaleFk - AND NOT isPicked; - - IF vRemainingQuantity THEN - CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL); - - SELECT SUM(quantity) INTO vRemainingQuantity - FROM itemShelvingSale - WHERE saleFk = vSaleFk - AND NOT isPicked; - - IF NOT vRemainingQuantity <=> 0 THEN - SELECT SUM(iss.quantity) - INTO vReservedQuantity - FROM itemShelvingSale iss - WHERE iss.saleFk = vSaleFk; - - CALL saleTracking_new( - vSaleFk, - TRUE, - vReservedQuantity, - `account`.`myUser_getId`(), - NULL, - 'PREPARED', - TRUE); - - UPDATE sale s - SET s.quantity = vReservedQuantity - WHERE s.id = vSaleFk ; - END IF; - END IF; +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una colección + * + * @param vCollectionFk Identificador de collection + */ + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + WITH sales AS ( + SELECT s.id saleFk, s.quantity, SUM(IFNULL(iss.quantity, 0)) quantityReserved + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + WHERE tc.collectionFk = vCollectionFk + GROUP BY s.id + HAVING quantity <> quantityReserved + ), trackedSales AS ( + SELECT sa.saleFk + FROM sales sa + JOIN vn.saleTracking st ON st.saleFk = sa.saleFk + JOIN vn.`state` s ON s.id = st.stateFk + WHERE st.isChecked + AND s.`code` IN ('PREVIOUS_PREPARATION', 'OK PREVIOUS', 'OK STOWAWAY') + GROUP BY sa.saleFk + ) SELECT s.saleFk + FROM sales s + LEFT JOIN trackedSales ts ON ts.saleFk = s.saleFk + WHERE ts.saleFk IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60096,7 +60248,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingTransfer` */; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addBySale` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -60104,50 +60256,512 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingTransfer`(vItemShelvingFk INT, vShelvingFk VARCHAR(3)) +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addBySale`( + vSaleFk INT +) +proc: BEGIN +/** + * Reserva una línea de venta en la ubicación más óptima + * + * @param vSaleFk Id de sale + * @param vItemShelvingSaleFk Id de reserva + */ + DECLARE vLastPickingOrder INT; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vItemShelvingFk INT; + DECLARE vAvailable INT; + DECLARE vReservedQuantity INT; + DECLARE vOutStanding INT; + DECLARE vUserFk INT; + + DECLARE vItemShelvingAvailable CURSOR FOR + SELECT ish.id itemShelvingFk, + ish.available + FROM sale s + JOIN itemShelving ish ON ish.itemFk = s.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector sc ON sc.id = p.sectorFk + JOIN productionConfig pc + WHERE s.id = vSaleFk + AND NOT sc.isHideForPickers + ORDER BY s.id, + p.pickingOrder >= vLastPickingOrder, + sh.priority DESC, + ish.available >= s.quantity DESC, + s.quantity MOD ish.grouping = 0 DESC, + ish.grouping DESC, + IF(pc.orderMode = 'Location', p.pickingOrder, ish.created); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)) + INTO vLastPickingOrder, vOutStanding + FROM sale s + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = sh.parkingFk + WHERE s.id = vSaleFk; + + IF vOutStanding <= 0 THEN + LEAVE proc; + END IF; + + SELECT getUser() INTO vUserFk; + + OPEN vItemShelvingAvailable; + l: LOOP + SET vDone = FALSE; + FETCH vItemShelvingAvailable INTO vItemShelvingFk, vAvailable; + + IF vOutStanding <= 0 OR vDone THEN + LEAVE l; + END IF; + + START TRANSACTION; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + SELECT LEAST(vOutStanding, vAvailable) INTO vReservedQuantity; + SET vOutStanding = vOutStanding - vReservedQuantity; + + IF vReservedQuantity > 0 THEN + + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk) + SELECT vItemShelvingFk, + vSaleFk, + vReservedQuantity, + vUserFk; + + UPDATE itemShelving + SET available = available - vReservedQuantity + WHERE id = vItemShelvingFk; + + END IF; + + COMMIT; + END LOOP; + CLOSE vItemShelvingAvailable; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addBySectorCollection` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addBySectorCollection`(vSectorCollectionFk INT(11)) BEGIN /** - * Transfiere producto de una ubicación a otra, fusionando si coincide el - * packing y la fecha. + * Reserva cantidades con ubicaciones para el contenido de una preparación previa + * de la cual ya tiene generada la asociación del saleGroup con sectorCollection * - * @param vItemShelvingFk Identificador de itemShelving - * @param vShelvingFk Identificador de shelving + * @param vSectorCollectionFk Identificador de sectorCollection */ - DECLARE vNewItemShelvingFk INT DEFAULT 0; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + SELECT s.id + FROM sectorCollectionSaleGroup sc + JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk + JOIN sale s ON sg.saleFk = s.id + JOIN saleTracking str ON str.saleFk = s.id + JOIN `state` st ON st.id = str.stateFk + AND st.code = 'PREVIOUS_PREPARATION' + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + WHERE sc.sectorCollectionFk = vSectorCollectionFk + AND str.workerFk = account.myUser_getId() + AND iss.id IS NULL; - SELECT MAX(ish.id) - INTO vNewItemShelvingFk - FROM itemShelving ish - JOIN ( - SELECT - itemFk, - packing, - created, - buyFk - FROM itemShelving - WHERE id = vItemShelvingFk - ) ish2 - ON ish2.itemFk = ish.itemFk - AND ish2.packing = ish.packing - AND date(ish2.created) = date(ish.created) - AND ish2.buyFk = ish.buyFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - IF vNewItemShelvingFk THEN - UPDATE itemShelving ish - JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk - SET ish.visible = ish.visible + ish2.visible - WHERE ish.id = vNewItemShelvingFk; + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; - DELETE FROM itemShelving - WHERE id = vItemShelvingFk; - ELSE - UPDATE itemShelving - SET shelvingFk = vShelvingFk - WHERE id = vItemShelvingFk; - END IF; + IF vDone THEN + LEAVE l; + END IF; - SELECT true; + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_doReserve` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_doReserve`() +proc: BEGIN +/** + * Genera reservas de la tabla vn.itemShelvingSaleReserve + */ + DECLARE vDone BOOL; + DECLARE vSaleFk INT; + + DECLARE vSales CURSOR FOR + SELECT DISTINCT saleFk FROM tSale; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); + ROLLBACK; + RESIGNAL; + END; + + IF !GET_LOCK('vn.itemShelvingSale_doReserve', 0) THEN + LEAVE proc; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tSale + ENGINE = MEMORY + SELECT id, saleFk FROM itemShelvingSaleReserve; + + OPEN vSales; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + CALL itemShelvingSale_addBySale (vSaleFk); + END LOOP; + + CLOSE vSales; + + DELETE iss FROM itemShelvingSaleReserve iss JOIN tSale s ON s.id = iss.id; + + DROP TEMPORARY TABLE tSale; + + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reallocate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reallocate`( + vItemShelvingFk INT(10), + vItemFk INT(10) +) +BEGIN +/** + * Elimina reservas de un itemShelving e intenta reservar en otra ubicación + * + * @param vItemShelvingFk Id itemShelving + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + UPDATE itemShelving + SET visible = 0, + available = 0 + WHERE id = vItemShelvingFk + AND itemFk = vItemFk; + + INSERT INTO itemShelvingSaleReserve (saleFk) + SELECT DISTINCT iss.saleFk + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + + DELETE iss + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + COMMIT; + + CALL itemShelvingSale_doReserve(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setPicked` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setPicked`( + vSaleGroupFk INT(10) +) +BEGIN +/** + * Gestiona la reserva de un vn.saleGroup actualizando vn.itemShelvingSale.isPicked + * y cambiando el estado de la vn.sale + * + * @param vSaleGroupFk Id saleGroupFk + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF NOT (SELECT COUNT(*) FROM saleGroup WHERE id = vSaleGroupFk) THEN + CALL util.throw('Sale group not exists'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + JOIN saleGroupDetail sg ON sg.saleFk = s.id + SET iss.isPicked = TRUE + WHERE sg.saleGroupFk = vSaleGroupFk; + + CALL saleTracking_addPreparedSaleGroup(vSaleGroupFk); + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setQuantity` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN +) +BEGIN +/** + * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity + * en itemShelvingSale y sale.isPicked en caso necesario. + * Si la reserva de la ubicación es fallida, se regulariza la situación + * + * @param vItemShelvingSaleFk Id itemShelvingSaleFK + * @param vQuantity Cantidad real que se ha cogido de la ubicación + * @param vIsItemShelvingSaleEmpty determina si la ubicación itemShelvingSale se ha + * quedado vacio tras el movimiento + */ + DECLARE vSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vTotalQuantity INT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN + CALL util.throw('Reservation completed'); + END IF; + + SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk, SUM(IFNULL(iss.quantity,0)) + INTO vItemFk, vSaleFk, vItemShelvingFk, vReservedQuantity + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + IF vQuantity > vReservedQuantity + OR (vQuantity < vReservedQuantity AND + (NOT vIsItemShelvingSaleEmpty OR vIsItemShelvingSaleEmpty IS NULL)) + OR (vIsItemShelvingSaleEmpty IS NOT NULL AND vQuantity = vReservedQuantity) THEN + CALL util.throw('The quantity cannot be different from the reserved'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = TRUE, + quantity = vQuantity + WHERE id = vItemShelvingSaleFk; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + UPDATE itemShelving + SET visible = GREATEST(0, visible - vQuantity) + WHERE id = vItemShelvingFk; + + SELECT SUM(IF(isPicked, 0, quantity)), SUM(quantity) + INTO vRemainingQuantity, vTotalQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk; + + IF vRemainingQuantity = 0 AND NOT vIsItemShelvingSaleEmpty THEN + CALL saleTracking_new( + vSaleFk, + TRUE, + vTotalQuantity, + `account`.`myUser_getId`(), + NULL, + 'PREPARED', + TRUE); + + UPDATE sale s + SET s.quantity = vTotalQuantity, + isPicked = TRUE + WHERE s.id = vSaleFk; + END IF; + + COMMIT; + + IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN + INSERT INTO itemShelvingSaleReserve (saleFk) + SELECT vSaleFk; + CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_unpicked` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_unpicked`( + vSelf INT(11) +) +BEGIN +/** + * Desmarca una línea que ya estaba sacada, devolviendo la cantidad al itemShelving + * + * @param vSelf Identificador del itemShelvingSale + */ + DECLARE vSaleFk INT; + DECLARE vReservedQuantity INT; + DECLARE vIsSaleGroup BOOL; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT NOT isPicked FROM itemShelvingSale WHERE id = vSelf) THEN + CALL util.throw('Reserva no completada'); + END IF; + + SELECT ish.saleFk, ish.quantity, IF(sg.id, TRUE, FALSE) + INTO vSaleFk, vReservedQuantity, vIsSaleGroup + FROM itemShelvingSale ish + LEFT JOIN saleGroupDetail sg ON sg.saleFk = ish.saleFk + WHERE ish.id = vSelf; + + /*IF vIsSaleGroup THEN + CALL util.throw('Can not unpicked a sale group'); + END IF;*/ + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = FALSE + WHERE id = vSelf; + + UPDATE sale s + JOIN itemShelvingSale ish ON ish.saleFk = s.id + SET s.isPicked = FALSE + WHERE ish.id = vSelf; + + UPDATE itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + SET ish.visible = ish.visible + iss.quantity + WHERE iss.id = vSelf; + + CALL saleTracking_new( + vSaleFk, + FALSE, + vReservedQuantity, + `account`.`myUser_getId`(), + NULL, + 'ON_PREPARATION', + TRUE); + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60375,7 +60989,8 @@ proc:BEGIN sub.downstairs, sub.visible, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho, - sub.name itemColour + sub.name itemColour, + CAST(sub2.pendiente AS DECIMAL(10,0)) pendingAmount FROM (SELECT iss.itemFk, CONCAT(i.longName, ' ', IFNULL(i.size, ''),' ', IFNULL(i.subName, '') ) longName, '' size, @@ -60412,7 +61027,8 @@ proc:BEGIN 0, v.visible, v.visible nicho, - ik.name itemColour + ik.name itemColour, + CAST(sub5.pendiente AS DECIMAL(10,0)) pendingAmount FROM cache.visible v JOIN item i ON i.id = v.item_id LEFT JOIN ink ik ON ik.id = i.inkFk @@ -60631,167 +61247,167 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) -BEGIN - - /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. - * - * @param vShelvingFk Matrícula del carro o pallet - */ - - DECLARE vWarehouseFk INT; - DECLARE vStockScopeDays INT; - - SELECT s.warehouseFk, stockScopeDays - INTO vWarehouseFk, vStockScopeDays - FROM sector s - JOIN operator o ON s.id = o.sectorFk - JOIN productionConfig pc - WHERE o.workerFk = account.myUser_getId(); - - IF vWarehouseFk IS NULL - THEN CALL util.throw('WarehouseFk not setted'); - END IF; - - IF vStockScopeDays IS NULL - THEN CALL util.throw('StockScopeDays not setted'); - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tItems - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - SELECT itemFk, SUM(visible) visible - FROM itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - - CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay - (INDEX (itemFk, dated)) - ENGINE = MEMORY - SELECT dated, - SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, - t3.itemFk - FROM ( - SELECT t.itemFk, dated, SUM(amount) amount - FROM ( - SELECT t2.itemFk, t2.amount, t2.dated - FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock s - JOIN tmp.tItems i ON i.itemFk = s.item_id - WHERE s.warehouse_id = vWarehouseFk - UNION ALL - SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() - FROM itemShelving ish - JOIN tmp.tItems i ON i.itemFk = ish.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id - JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve - GROUP BY ish.itemFk - UNION ALL - SELECT iei.itemFk, SUM(quantity), landed - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND iei.warehouseInFk = vWarehouseFk - AND NOT isVirtualStock - GROUP BY iei.itemFk, iei.landed - UNION ALL - SELECT ieo.itemFk, SUM(quantity), shipped - FROM itemEntryOut ieo - JOIN tmp.tItems i ON i.itemFk = ieo.itemFk - WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ieo.warehouseOutFk = vWarehouseFk - GROUP BY ieo.itemFk, ieo.shipped - UNION ALL - SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) - FROM itemTicketOut ito - JOIN tmp.tItems i ON i.itemFk = ito.itemFk - WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY - AND ito.warehouseFk = vWarehouseFk - GROUP BY ito.itemFk, ito.shipped - ) t2 - JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t - GROUP BY t.itemFk, dated - ) t3; - - -- Se restan las entradas de hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry - FROM itemEntryIn iei - JOIN tmp.tItems i ON i.itemFk = iei.itemFk - WHERE iei.landed = util.VN_CURDATE() - AND iei.warehouseInFk = vWarehouseFk - AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock - sub.todayEntry - WHERE sbd.dated = util.VN_CURDATE(); - - -- Se añaden las lineas de venta servidas - UPDATE tmp.tStockByDay sbd - JOIN (SELECT s.itemFK, SUM(quantity) amount - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - WHERE t.warehouseFk = vWarehouseFk - AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() - AND s.isPicked - GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - -- Se añaden los items ubicados hoy - UPDATE tmp.tStockByDay sbd - JOIN (SELECT ish.itemFK, SUM(ish.visible) amount - 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 - WHERE s.warehouseFk = vWarehouseFk - AND NOT s.isReserve - AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() - GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk - SET sbd.stock = sbd.stock + sub.amount; - - SELECT ts.itemFk, - i.longName, - IF(ts.stock<=0, ts.dated, NULL) dated, - ts.stock, - sub4.visible, - sub4.shelvingFk - FROM( - SELECT IFNULL(sub2.minDated, sub.minDated) dated, - IFNULL(sub2.itemFk, sub.itemFk) itemFk - FROM(SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - GROUP BY itemFk)sub - LEFT JOIN ( - SELECT sbd.itemFk, - MIN(dated) minDated, - sbd.stock - FROM tmp.tItems ti - LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk - WHERE sbd.stock <= 0 - GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk - WHERE sub2.itemFk IS NOT NULL - OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 - LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated - JOIN (SELECT ish.itemFk, - ish.visible, - p.sectorFk, - ish.shelvingFk - FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN parking p ON p.id = parkingFk - LEFT JOIN vn.sector s ON s.id = p.sectorFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - ) sub4 ON sub4.itemFk = ts.itemFk - LEFT JOIN sector s ON s.id = sub4.sectorFk - LEFT JOIN item i ON i.id = ts.itemFk - WHERE NOT s.isReserve; - - DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; - +BEGIN + + /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. + * + * @param vShelvingFk Matrícula del carro o pallet + */ + + DECLARE vWarehouseFk INT; + DECLARE vStockScopeDays INT; + + SELECT s.warehouseFk, stockScopeDays + INTO vWarehouseFk, vStockScopeDays + FROM sector s + JOIN operator o ON s.id = o.sectorFk + JOIN productionConfig pc + WHERE o.workerFk = account.myUser_getId(); + + IF vWarehouseFk IS NULL + THEN CALL util.throw('WarehouseFk not setted'); + END IF; + + IF vStockScopeDays IS NULL + THEN CALL util.throw('StockScopeDays not setted'); + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tItems + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(visible) visible + FROM itemShelving + WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + GROUP BY itemFk; + + CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay + (INDEX (itemFk, dated)) + ENGINE = MEMORY + SELECT dated, + SUM(t3.amount) OVER (PARTITION BY t3.itemFk ORDER BY dated) stock, + t3.itemFk + FROM ( + SELECT t.itemFk, dated, SUM(amount) amount + FROM ( + SELECT t2.itemFk, t2.amount, t2.dated + FROM ( + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock s + JOIN tmp.tItems i ON i.itemFk = s.item_id + WHERE s.warehouse_id = vWarehouseFk + UNION ALL + SELECT ish.itemFk, - SUM(ish.visible), util.VN_CURDATE() + FROM itemShelving ish + JOIN tmp.tItems i ON i.itemFk = ish.itemFk + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id + JOIN sector s ON s.id = p.sectorFk + WHERE s.isReserve + GROUP BY ish.itemFk + UNION ALL + SELECT iei.itemFk, SUM(quantity), landed + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND iei.warehouseInFk = vWarehouseFk + AND NOT isVirtualStock + GROUP BY iei.itemFk, iei.landed + UNION ALL + SELECT ieo.itemFk, SUM(quantity), shipped + FROM itemEntryOut ieo + JOIN tmp.tItems i ON i.itemFk = ieo.itemFk + WHERE ieo.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ieo.warehouseOutFk = vWarehouseFk + GROUP BY ieo.itemFk, ieo.shipped + UNION ALL + SELECT i.itemFk, SUM(ito.quantity), DATE(ito.shipped) + FROM itemTicketOut ito + JOIN tmp.tItems i ON i.itemFk = ito.itemFk + WHERE ito.shipped BETWEEN util.VN_CURDATE() AND util.VN_CURDATE() + INTERVAL vStockScopeDays DAY + AND ito.warehouseFk = vWarehouseFk + GROUP BY ito.itemFk, ito.shipped + ) t2 + JOIN tmp.tItems i ON i.itemFk = t2.itemFk)t + GROUP BY t.itemFk, dated + ) t3; + + -- Se restan las entradas de hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT iei.itemFk, SUM(quantity) todayEntry + FROM itemEntryIn iei + JOIN tmp.tItems i ON i.itemFk = iei.itemFk + WHERE iei.landed = util.VN_CURDATE() + AND iei.warehouseInFk = vWarehouseFk + AND NOT iei.isVirtualStock) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock - sub.todayEntry + WHERE sbd.dated = util.VN_CURDATE(); + + -- Se añaden las lineas de venta servidas + UPDATE tmp.tStockByDay sbd + JOIN (SELECT s.itemFK, SUM(quantity) amount + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWarehouseFk + AND t.shipped BETWEEN util.VN_CURDATE() AND util.midnight() + AND s.isPicked + GROUP BY s.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + -- Se añaden los items ubicados hoy + UPDATE tmp.tStockByDay sbd + JOIN (SELECT ish.itemFK, SUM(ish.visible) amount + 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 + WHERE s.warehouseFk = vWarehouseFk + AND NOT s.isReserve + AND ish.created BETWEEN util.VN_CURDATE() AND util.midnight() + GROUP BY ish.itemFk) sub ON sub.itemFk = sbd.itemFk + SET sbd.stock = sbd.stock + sub.amount; + + SELECT ts.itemFk, + i.longName, + IF(ts.stock<=0, ts.dated, NULL) dated, + ts.stock, + sub4.visible, + sub4.shelvingFk + FROM( + SELECT IFNULL(sub2.minDated, sub.minDated) dated, + IFNULL(sub2.itemFk, sub.itemFk) itemFk + FROM(SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + GROUP BY itemFk)sub + LEFT JOIN ( + SELECT sbd.itemFk, + MIN(dated) minDated, + sbd.stock + FROM tmp.tItems ti + LEFT JOIN tmp.tStockByDay sbd ON sbd.itemFk = ti.itemFk + WHERE sbd.stock <= 0 + GROUP BY itemFk)sub2 ON sub2.itemFk =sub.itemFk + WHERE sub2.itemFk IS NOT NULL + OR (sub2.itemFk IS NULL AND sub.itemFk IS NOT NULL)) sub3 + LEFT JOIN tmp.tStockByDay ts ON ts.itemFk = sub3.itemFk AND ts.dated = sub3.dated + JOIN (SELECT ish.itemFk, + ish.visible, + p.sectorFk, + ish.shelvingFk + FROM itemShelving ish + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = parkingFk + LEFT JOIN vn.sector s ON s.id = p.sectorFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + ) sub4 ON sub4.itemFk = ts.itemFk + LEFT JOIN sector s ON s.id = sub4.sectorFk + LEFT JOIN item i ON i.id = ts.itemFk + WHERE NOT s.isReserve; + + DROP TEMPORARY TABLE tmp.tStockByDay, tmp.tItems; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60978,6 +61594,67 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_transfer` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_transfer`( + vItemShelvingFk INT, + vShelvingFk VARCHAR(10) +) +BEGIN +/** + * Transfiere producto de una ubicación a otra, fusionando si coincide el + * packing y la fecha. + * + * @param vItemShelvingFk Identificador de itemShelving + * @param vShelvingFk Identificador de shelving + */ + DECLARE vNewItemShelvingFk INT DEFAULT 0; + + SELECT MAX(ish.id) + INTO vNewItemShelvingFk + FROM itemShelving ish + JOIN ( + SELECT + itemFk, + packing, + created, + buyFk + FROM itemShelving + WHERE id = vItemShelvingFk + ) ish2 ON ish2.itemFk = ish.itemFk + AND ish2.packing = ish.packing + AND date(ish2.created) = date(ish.created) + AND ish2.buyFk = ish.buyFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; + + IF vNewItemShelvingFk THEN + UPDATE itemShelving ish + JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk + SET ish.visible = ish.visible + ish2.visible + WHERE ish.id = vNewItemShelvingFk; + + DELETE FROM itemShelving + WHERE id = vItemShelvingFk; + ELSE + UPDATE itemShelving + SET shelvingFk = vShelvingFk + WHERE id = vItemShelvingFk; + END IF; + SELECT true; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemShelving_update` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -62333,50 +63010,50 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getAtp`(vDated DATE) -BEGIN -/** - * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y - * almacén. - * - * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 - * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) - * @return tmp.itemAtp(itemFk, warehouseFk, quantity) - */ - CREATE OR REPLACE TEMPORARY TABLE tItemOrdered - (UNIQUE(itemFk, warehouseFk, dated)) - ENGINE = MEMORY - SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity - FROM ( - SELECT itemFk, warehouseFk, dated, quantity - FROM tmp.itemCalc - UNION ALL - SELECT itemFk, warehouseFk, vDated, 0 - FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 - ) t1 - GROUP BY itemFk, warehouseFk, dated - ORDER BY itemFk, warehouseFk, dated; - - SET @lastItemFk := 0; - SET @lastWareHouseFk := 0; - SET @lastQuantity := 0; - - CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp - (INDEX (itemFk, wareHouseFk)) - SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity - FROM ( - SELECT - itemFk, - IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, - @lastQuantity := quantity, - @lastQuantity := @lastQuantity + quantity) quantityAccumulated, - wareHouseFk, - @lastItemFk := itemFk, - @lastWareHouseFk := wareHouseFk - FROM tItemOrdered - )sub - GROUP BY itemFk, wareHouseFk; - - DROP TEMPORARY TABLE tItemOrdered; +BEGIN +/** + * Calcula el valor mínimo acumulado para cada artículo ordenado por fecha y + * almacén. + * + * @param vDated Si no hay movimientos en la fecha indicada, debe devolver 0 + * @table tmp.itemCalc(itemFk, wareHouseFk, dated, quantity) + * @return tmp.itemAtp(itemFk, warehouseFk, quantity) + */ + CREATE OR REPLACE TEMPORARY TABLE tItemOrdered + (UNIQUE(itemFk, warehouseFk, dated)) + ENGINE = MEMORY + SELECT itemFk, warehouseFk, dated, SUM(quantity) quantity + FROM ( + SELECT itemFk, warehouseFk, dated, quantity + FROM tmp.itemCalc + UNION ALL + SELECT itemFk, warehouseFk, vDated, 0 + FROM (SELECT DISTINCT itemFk, warehouseFk FROM tmp.itemCalc) t2 + ) t1 + GROUP BY itemFk, warehouseFk, dated + ORDER BY itemFk, warehouseFk, dated; + + SET @lastItemFk := 0; + SET @lastWareHouseFk := 0; + SET @lastQuantity := 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.itemAtp + (INDEX (itemFk, wareHouseFk)) + SELECT itemFk, wareHouseFk, MIN(quantityAccumulated) quantity + FROM ( + SELECT + itemFk, + IF(itemFk <> @lastItemFk OR wareHouseFk <> @lastWareHouseFk, + @lastQuantity := quantity, + @lastQuantity := @lastQuantity + quantity) quantityAccumulated, + wareHouseFk, + @lastItemFk := itemFk, + @lastWareHouseFk := wareHouseFk + FROM tItemOrdered + )sub + GROUP BY itemFk, wareHouseFk; + + DROP TEMPORARY TABLE tItemOrdered; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -62970,14 +63647,13 @@ BEGIN * @param vDated Fecha * @param vShowType Mostrar tipos */ - DECLARE vCalcFk INT; + DECLARE vAvailableCalcFk INT; + DECLARE vVisibleCalcFk INT; DECLARE vTypeFk INT; DECLARE vPriority INT DEFAULT 1; - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); - - -- Añadido temporalmente para que no se cuelgue la db - SET vShowType = TRUE; + CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); + CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); WITH itemTags AS ( SELECT i.id, @@ -63020,21 +63696,21 @@ BEGIN WHEN b.groupingMode = 'packing' THEN b.packing ELSE 1 END AS minQuantity, - iss.visible located, + v.visible located, b.price2 FROM vn.item i JOIN cache.available a ON a.item_id = i.id - AND a.calc_id = vCalcFk + AND a.calc_id = vAvailableCalcFk + LEFT JOIN cache.visible v ON v.item_id = i.id + AND v.calc_id = vVisibleCalcFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf LEFT JOIN vn.itemTag it ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.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 vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id - AND iss.warehouseFk = vWarehouseFk JOIN itemTags its WHERE a.available > 0 AND (i.typeFk = its.typeFk OR NOT vShowType) @@ -64541,197 +65217,206 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( - vDate DATE, - vWarehouseFk TINYINT, - vMaxDays TINYINT +CREATE DEFINER=`root`@`localhost` PROCEDURE `multipleInventory`( + vDate DATE, + vWarehouseFk TINYINT, + vMaxDays TINYINT ) -proc: BEGIN - DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; - DECLARE vDateFrom DATE DEFAULT vDate; - DECLARE vDateTo DATETIME; - DECLARE vDateToTomorrow DATETIME; - DECLARE vDefaultDayRange INT; - - IF vDate < util.VN_CURDATE() THEN - LEAVE proc; - END IF; - - IF vDate = util.VN_CURDATE() THEN - SELECT inventoried INTO vDateFrom - FROM config; - END IF; - - SELECT defaultDayRange INTO vDefaultDayRange - FROM comparativeConfig; - - SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; - SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; - - ALTER TABLE tmp.itemInventory - ADD `avalaible` INT NOT NULL, - ADD `sd` INT NOT NULL, - ADD `rest` INT NOT NULL, - ADD `expected` INT NOT NULL, - ADD `inventory` INT NOT NULL, - ADD `visible` INT NOT NULL, - ADD `life` TINYINT NOT NULL DEFAULT '0'; - - -- Calculo del inventario - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.inventory = sub.Subtotal, - ai.visible = sub.Subtotal, - ai.avalaible = sub.Subtotal, - ai.sd = sub.Subtotal; - - -- Cálculo del visible - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.visible = ai.visible + sub.Subtotal; - - -- Calculo del disponible - CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT sub.itemFk, - vWarehouseFk warehouseFk, - sub.dated, - SUM(sub.quantity) quantity - FROM ( - SELECT s.itemFk, - DATE(t.shipped) dated, - - s.quantity quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, t.landed, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - UNION ALL - SELECT b.itemFk, t.shipped, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - ) sub - GROUP BY sub.itemFk, sub.dated; - - CALL item_getAtp(vDate); - CALL travel_upcomingArrivals(vWarehouseFk, vDate); - - UPDATE tmp.itemInventory ai - JOIN ( - SELECT it.itemFk, - SUM(it.quantity) quantity, - im.quantity minQuantity - FROM tmp.itemCalc it - JOIN tmp.itemAtp im ON im.itemFk = it.itemFk - JOIN item i ON i.id = it.itemFk - LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk - WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, - t.landing, - vDateToTomorrow) - GROUP BY it.itemFk - ) sub ON sub.itemFk = ai.id - SET ai.avalaible = IF(sub.minQuantity > 0, - ai.avalaible, - ai.avalaible + sub.minQuantity), - ai.sd = ai.inventory + sub.quantity; - - DROP TEMPORARY TABLE - tmp.itemTravel, - tmp.itemCalc, - tmp.itemAtp; +proc: BEGIN + DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; + DECLARE vDateFrom DATE DEFAULT vDate; + DECLARE vDateTo DATETIME; + DECLARE vDateToTomorrow DATETIME; + DECLARE vDefaultDayRange INT; + + IF vDate < util.VN_CURDATE() THEN + LEAVE proc; + END IF; + + IF vDate = util.VN_CURDATE() THEN + SELECT inventoried INTO vDateFrom + FROM config; + END IF; + + SELECT defaultDayRange INTO vDefaultDayRange + FROM comparativeConfig; + + SET vDateTo = vDate + INTERVAL IFNULL(vMaxDays, vDefaultDayRange) DAY; + SET vDateToTomorrow = vDateTo + INTERVAL 1 DAY; + + ALTER TABLE tmp.itemInventory + ADD `avalaible` INT NOT NULL, + ADD `sd` INT NOT NULL, + ADD `rest` INT NOT NULL, + ADD `expected` INT NOT NULL, + ADD `inventory` INT NOT NULL, + ADD `visible` INT NOT NULL, + ADD `life` TINYINT NOT NULL DEFAULT '0'; + + -- Calculo del inventario + CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, + SUM(quantity) quantity + FROM ( + SELECT s.itemFk, - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateFrom AND util.dayEnd(vDate) + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY itemFk; + + UPDATE tmp.itemInventory ai + JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + SET ai.inventory = iic.quantity, + ai.visible = iic.quantity, + ai.avalaible = iic.quantity, + ai.sd = iic.quantity; + + -- Cálculo del visible + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) visible + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk; + + UPDATE tmp.itemInventory ai + JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id + SET ai.visible = ai.visible + ivc.visible; + + -- Calculo del disponible + CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT sub.itemFk, + vWarehouseFk warehouseFk, + sub.dated, + SUM(sub.quantity) quantity + FROM ( + SELECT s.itemFk, + DATE(t.shipped) dated, + - s.quantity quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, t.landed, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, t.shipped, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped BETWEEN vDateTomorrow AND vDateTo + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + ) sub + GROUP BY sub.itemFk, sub.dated; + + CALL item_getAtp(vDate); + CALL travel_upcomingArrivals(vWarehouseFk, vDate); + + UPDATE tmp.itemInventory ai + JOIN ( + SELECT it.itemFk, + SUM(it.quantity) quantity, + im.quantity minQuantity + FROM tmp.itemCalc it + JOIN tmp.itemAtp im ON im.itemFk = it.itemFk + JOIN item i ON i.id = it.itemFk + LEFT JOIN origin o ON o.id = i.originFk + LEFT JOIN tmp.itemTravel t ON t.wh = o.warehouseFk + WHERE it.dated < IF(vMaxDays < 0 AND t.landing IS NOT NULL, + t.landing, + vDateToTomorrow) + GROUP BY it.itemFk + ) sub ON sub.itemFk = ai.id + SET ai.avalaible = IF(sub.minQuantity > 0, + ai.avalaible, + ai.avalaible + sub.minQuantity), + ai.sd = ai.inventory + sub.quantity; + + DROP TEMPORARY TABLE + tmp.itemTravel, + tmp.itemCalc, + tItemInventoryCalc, + tItemVisibleCalc, + tmp.itemAtp; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65662,6 +66347,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY INTO vEndingDate FROM productionConfig; @@ -65678,7 +66368,8 @@ proc: BEGIN CALL prepareClientList(); CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems - (INDEX (ticketFk)) ENGINE = MEMORY + (INDEX (ticketFk)) + ENGINE = MEMORY SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped FROM tmp.productionTicket tt JOIN ticket t ON t.id = tt.ticketFk; @@ -67555,43 +68246,43 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT) -BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; - - START TRANSACTION; - - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET s.quantity = newQuantity - WHERE s.ticketFk = vTicketFk; - - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND stp.id IS NULL - AND it.isMergeable; - - COMMIT; - - DROP TEMPORARY TABLE tSalesToPreserve; +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND it.isMergeable + GROUP BY s.itemFk, s.price, s.discount; + + START TRANSACTION; + + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET s.quantity = newQuantity + WHERE s.ticketFk = vTicketFk; + + DELETE s.* + FROM sale s + LEFT JOIN tSalesToPreserve stp ON stp.id = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND stp.id IS NULL + AND it.isMergeable; + + COMMIT; + + DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68705,12 +69396,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk, problem, saleFk + SELECT ticketFk, problem ,saleFk FROM ( SELECT tl.ticketFk, - s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, - MOD(s.quantity, b.`grouping`) hasRounding + s.id saleFk, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk @@ -68718,9 +69408,9 @@ BEGIN JOIN item i ON i.id = s.itemFk JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk JOIN buy b ON b.id = bu.buyFk + WHERE MOD(s.quantity, b.`grouping`) GROUP BY tl.ticketFk - HAVING hasRounding - ) sub + )sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; @@ -69350,6 +70040,37 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sectorCollection_getMyPartial` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_getMyPartial`() +BEGIN +/** + * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas + * + */ + SELECT DISTINCT sc.id collectionFk, sc.created + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + LEFT JOIN vn.sale sl ON sl.id = sgd.saleFk + LEFT JOIN itemShelvingSale iss ON iss.saleFk = sl.id + WHERE sc.userFk = account.myUser_getId() + AND (scsg.sectorCollectionFk IS NULL OR NOT iss.isPicked) + AND sc.created > util.VN_CURDATE() - INTERVAL 1 DAY; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `sectorCollection_getSale` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -69404,30 +70125,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69577,41 +70298,43 @@ proc: BEGIN CALL util.throw('parkingNotExist'); LEAVE proc; END IF; + + IF vParam REGEXP '^[0-9]+$' THEN + -- Se comprueba si es una preparación previa + SELECT COUNT(*) INTO vIsSaleGroup + FROM vn.saleGroup sg + WHERE sg.id = vParam; - -- Se comprueba si es una preparación previa - SELECT COUNT(*) INTO vIsSaleGroup - FROM vn.saleGroup sg - WHERE sg.id = vParam; + IF vIsSaleGroup THEN + CALL vn.saleGroup_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; - IF vIsSaleGroup THEN - CALL vn.saleGroup_setParking(vParam, vParkingFk); - LEAVE proc; + -- Se comprueba si es un ticket + SELECT COUNT(*) INTO vIsTicket + FROM vn.ticket t + WHERE t.id = vParam + AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + + IF vIsTicket THEN + CALL vn.ticket_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; + + -- Se comprueba si es una coleccion de tickets + SELECT COUNT(*) INTO vIsCollection + FROM vn.collection c + WHERE c.id = vParam + AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + + IF vIsCollection THEN + CALL vn.collection_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; + ELSE + -- Por descarte, se considera una matrícula + CALL vn.shelving_setParking(vParam, vParkingFk); END IF; - - -- Se comprueba si es un ticket - SELECT COUNT(*) INTO vIsTicket - FROM vn.ticket t - WHERE t.id = vParam - AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsTicket THEN - CALL vn.ticket_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Se comprueba si es una coleccion de tickets - SELECT COUNT(*) INTO vIsCollection - FROM vn.collection c - WHERE c.id = vParam - AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsCollection THEN - CALL vn.collection_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Por descarte, se considera una matrícula - CALL vn.shelving_setParking(vParam, vParkingFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72571,14 +73294,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_Clone` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT) BEGIN @@ -72590,6 +73313,11 @@ BEGIN */ DECLARE vStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO ticket ( clientFk, shipped, @@ -72722,7 +73450,10 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`(vDateFrom DATE, vDateTo DATE) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`( + vDateFrom DATE, + vDateTo DATE +) BEGIN DECLARE vIsDone BOOL; DECLARE vLanding DATE; @@ -72762,9 +73493,16 @@ BEGIN DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); DECLARE vMessage TEXT; - + SET vIsDone = FALSE; - FETCH rsTicket INTO vTicketFk,vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk,vShipment; + FETCH rsTicket INTO + vTicketFk, + vClientFk, + vWarehouseFk, + vCompanyFk, + vAddressFk, + vAgencyModeFk, + vShipment; IF vIsDone THEN LEAVE myLoop; @@ -72790,7 +73528,7 @@ BEGIN AND isDefaultAddress; END IF; - CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk,FALSE); + CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk, FALSE); SET vLanding = NULL; SELECT landed INTO vLanding FROM tmp.zoneGetLanded LIMIT 1; @@ -72811,16 +73549,22 @@ BEGIN SET clonedFrom = vTicketFk WHERE id = vNewTicket; - INSERT INTO sale (ticketFk, itemFk, concept, quantity, price, - discount, priceFixed, isPriceFixed) + INSERT INTO sale (ticketFk, + itemFk, + concept, + quantity, + price, + discount, + priceFixed, + isPriceFixed) SELECT vNewTicket, - saleOrig.itemFk, - saleOrig.concept, - saleOrig.quantity, - saleOrig.price, - saleOrig.discount, - saleOrig.priceFixed, - saleOrig.isPriceFixed + saleOrig.itemFk, + saleOrig.concept, + saleOrig.quantity, + saleOrig.price, + saleOrig.discount, + saleOrig.priceFixed, + saleOrig.isPriceFixed FROM sale saleOrig WHERE saleOrig.ticketFk = vTicketFk; @@ -72846,20 +73590,20 @@ BEGIN ,attenderFk, ticketFk) SELECT description, - ordered, - shipped, - quantity, - price, - itemFk, - clientFk, - response, - total, - buyed, - requesterFk, - attenderFk, - vNewTicket + ordered, + shipped, + quantity, + price, + itemFk, + clientFk, + response, + total, + buyed, + requesterFk, + attenderFk, + vNewTicket FROM ticketRequest - WHERE ticketFk =vTicketFk; + WHERE ticketFk =vTicketFk; SELECT id INTO vSalesPersonFK FROM observationType @@ -72912,7 +73656,7 @@ BEGIN IF NOT vIsDuplicateMail THEN CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage); END IF; - CALL ticketStateUpdate (vNewTicket, 'FIXING'); + CALL ticket_setState(vNewTicket, 'FIXING'); ELSE CALL ticketCalculateClon(vNewTicket, vTicketFk); END IF; @@ -73366,60 +74110,62 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) -BEGIN -/** - * Splita las lineas de ticket que no estan ubicadas - * - * @param vTicketFk Id ticket - */ - DECLARE vNewTicketFk INT; - DECLARE vTotalLines INT; - DECLARE vLinesToSplit INT; - - DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - - SELECT COUNT(*) INTO vTotalLines - FROM sale - WHERE ticketFk = vTicketFk; - - CREATE TEMPORARY TABLE tmp.SalesToSplit - SELECT s.id saleFk - FROM ticket t - JOIN sale s ON t.id = s.ticketFk - LEFT JOIN ( - SELECT ish.itemFk itemFk, - SUM(ish.visible) visible, - s.warehouseFk warehouseFk - 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 - GROUP BY ish.itemFk, - s.warehouseFk - ) issw ON issw.itemFk = s.itemFk - AND issw.warehouseFk = t.warehouseFk - WHERE s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND NOT s.isPicked - AND NOT s.reserved - AND t.id = vTicketFk; - - SELECT COUNT(*) INTO vLinesToSplit - FROM tmp.SalesToSplit; - - IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - SET vNewTicketFk = vTicketFk; - ELSE - CALL ticket_Clone(vTicketFk, vNewTicketFk); - UPDATE sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id - SET s.ticketFk = vNewTicketFk; - END IF; - - CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); - - DROP TEMPORARY TABLE tmp.SalesToSplit; +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`( + vTicketFk INT +) +BEGIN +/** + * Splita las lineas de ticket que no estan ubicadas + * + * @param vTicketFk Id ticket + */ + DECLARE vNewTicketFk INT; + DECLARE vTotalLines INT; + DECLARE vLinesToSplit INT; + + DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; + + SELECT COUNT(*) INTO vTotalLines + FROM sale + WHERE ticketFk = vTicketFk; + + CREATE TEMPORARY TABLE tmp.SalesToSplit + SELECT s.id saleFk + FROM ticket t + JOIN sale s ON t.id = s.ticketFk + LEFT JOIN ( + SELECT ish.itemFk itemFk, + SUM(ish.visible) visible, + s.warehouseFk warehouseFk + 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 + GROUP BY ish.itemFk, + s.warehouseFk + ) issw ON issw.itemFk = s.itemFk + AND issw.warehouseFk = t.warehouseFk + WHERE s.quantity > IFNULL(issw.visible, 0) + AND s.quantity > 0 + AND NOT s.isPicked + AND NOT s.reserved + AND t.id = vTicketFk; + + SELECT COUNT(*) INTO vLinesToSplit + FROM tmp.SalesToSplit; + + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN + SET vNewTicketFk = vTicketFk; + ELSE + CALL ticket_Clone(vTicketFk, vNewTicketFk); + UPDATE sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + SET s.ticketFk = vNewTicketFk; + END IF; + + CALL ticket_setState(vNewTicketFk, 'FIXING'); + + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73437,84 +74183,84 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT) -BEGIN -/** -* Crea u actualiza la información del CMR asociado con -* un ticket específico en caso de que sea necesario. -* -* @param vSelf El id del ticket -*/ - DECLARE vCmrFk INT; - SELECT cmrFk INTO vCmrFk - FROM ticket - WHERE id = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tTicket - SELECT wo.firstName, - v.numberPlate, - com.id companyFk, - a.id addressFk, - c2.defaultAddressFk, - IFNULL(sat.supplierFk, su.id) supplierFk, - t.landed - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN company com ON com.id = t.companyFk - JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk - JOIN supplier su ON su.id = sa.supplierFk - LEFT JOIN route r ON r.id = t.routeFk - LEFT JOIN worker wo ON wo.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk - LEFT JOIN agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN agency ag ON ag.id = am.agencyFk - LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id - AND wo.isFreelance - WHERE al.code IN ('PACKED', 'DELIVERED') - AND co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND t.id = vSelf - GROUP BY t.id; - - IF vCmrFk THEN - UPDATE cmr c - JOIN tTicket t - SET c.senderInstruccions = t.firstName, - c.truckPlate = t.numberPlate, - c.companyFk = t.companyFk, - c.addressToFk = t.addressFk, - c.addressFromFk = t.defaultAddressFk, - c.supplierFk = t.supplierFk, - c.ead = t.landed - WHERE id = vCmrFk; - ELSE - INSERT INTO cmr ( - senderInstruccions, - truckPlate, - companyFk, - addressToFk, - addressFromFk, - supplierFk, - ead - ) - SELECT * FROM tTicket; - - IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN - UPDATE ticket - SET cmrFk = LAST_INSERT_ID() - WHERE id = vSelf; - END IF; - END IF; - - DROP TEMPORARY TABLE tTicket; +BEGIN +/** +* Crea u actualiza la información del CMR asociado con +* un ticket específico en caso de que sea necesario. +* +* @param vSelf El id del ticket +*/ + DECLARE vCmrFk INT; + SELECT cmrFk INTO vCmrFk + FROM ticket + WHERE id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tTicket + SELECT wo.firstName, + v.numberPlate, + com.id companyFk, + a.id addressFk, + c2.defaultAddressFk, + IFNULL(sat.supplierFk, su.id) supplierFk, + t.landed + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN company com ON com.id = t.companyFk + JOIN client c2 ON c2.id = com.clientFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplier su ON su.id = sa.supplierFk + LEFT JOIN route r ON r.id = t.routeFk + LEFT JOIN worker wo ON wo.id = r.workerFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency ag ON ag.id = am.agencyFk + LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id + AND wo.isFreelance + WHERE al.code IN ('PACKED', 'DELIVERED') + AND co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND t.id = vSelf + GROUP BY t.id; + + IF vCmrFk THEN + UPDATE cmr c + JOIN tTicket t + SET c.senderInstruccions = t.firstName, + c.truckPlate = t.numberPlate, + c.companyFk = t.companyFk, + c.addressToFk = t.addressFk, + c.addressFromFk = t.defaultAddressFk, + c.supplierFk = t.supplierFk, + c.ead = t.landed + WHERE id = vCmrFk; + ELSE + INSERT INTO cmr ( + senderInstruccions, + truckPlate, + companyFk, + addressToFk, + addressFromFk, + supplierFk, + ead + ) + SELECT * FROM tTicket; + + IF (SELECT EXISTS(SELECT * FROM tTicket)) THEN + UPDATE ticket + SET cmrFk = LAST_INSERT_ID() + WHERE id = vSelf; + END IF; + END IF; + + DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75115,7 +75861,11 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_split`(vTicketFk INT, vTicketFutureFk INT, vDated DATE) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_split`( + vTicketFk INT, + vTicketFutureFk INT, + vDated DATE +) proc:BEGIN /** * Mueve las lineas con problemas a otro ticket existente o a uno nuevo. @@ -75133,61 +75883,57 @@ proc:BEGIN FROM tmp.salesToSplit WHERE ticketFk = vTicketFk; - SELECT count(*) INTO vTotalLines - FROM vn.sale s + SELECT COUNT(*) INTO vTotalLines + FROM sale s WHERE s.ticketFk = vTicketFk; SET vHasFullProblem = (vTotalLines = vProblemLines); -- Ticket completo IF vHasFullProblem THEN - - UPDATE vn.ticket - SET landed = vDated + INTERVAL 1 DAY, + UPDATE ticket + SET landed = vDated + INTERVAL 1 DAY, shipped = vDated, - nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) + nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname) WHERE id = vTicketFk; - SELECT "moved" message, NULL ticketFuture; + SELECT 'moved' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket a futuro existe IF vTicketFutureFk THEN - - UPDATE vn.sale s - JOIN tmp.salesToSplit ss ON s.id = ss.saleFk + UPDATE sale s + JOIN tmp.salesToSplit ss ON s.id = ss.saleFk SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE ss.ticketFk = vTicketFk; - SELECT "future" message, NULL ticketFuture; + SELECT 'future' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket nuevo - CALL vn.ticket_Clone(vTicketFk, vTicketFutureFk); + CALL ticket_Clone(vTicketFk, vTicketFutureFk); - UPDATE vn.ticket t - JOIN vn.productionConfig pc + UPDATE ticket t + JOIN productionConfig pc SET t.routeFk = IF(t.shipped = vDated , t.routeFk, NULL), - t.landed = vDated + INTERVAL 1 DAY, + t.landed = vDated + INTERVAL 1 DAY, t.shipped = vDated, t.agencyModeFk = pc.defautlAgencyMode, t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - - UPDATE vn.sale s - JOIN tmp.salesToSplit sts ON sts.saleFk = s.id + + UPDATE sale s + JOIN tmp.salesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE sts.ticketFk = vTicketFk; - CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING'); + CALL ticket_setState(vTicketFutureFk, 'FIXING'); - SELECT "new" message,vTicketFutureFk ticketFuture; + SELECT 'new' message, vTicketFutureFk ticketFuture; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75204,8 +75950,11 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitItemPackingType`(vTicketFk INT, vOriginalItemPackingTypeFk VARCHAR(1)) -proc:BEGIN +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitItemPackingType`( + vTicketFk INT, + vOriginalItemPackingTypeFk VARCHAR(1) +) +BEGIN /** * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. * Respeta el id inicial para el tipo propuesto. @@ -75227,22 +75976,27 @@ proc:BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + DELETE FROM vn.sale WHERE quantity = 0 AND ticketFk = vTicketFk; - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale + CREATE OR REPLACE TEMPORARY TABLE tmp.sale (PRIMARY KEY (id)) + ENGINE = MEMORY SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id WHERE s.ticketFk = vTicketFk; - DROP TEMPORARY TABLE IF EXISTS tmp.saleGroup; - CREATE TEMPORARY TABLE tmp.saleGroup - SELECT itemPackingTypeFk , sum(litros) AS totalLitros + CREATE OR REPLACE TEMPORARY TABLE tmp.saleGroup + ENGINE = MEMORY + SELECT itemPackingTypeFk, SUM(litros) totalLitros FROM tmp.sale GROUP BY itemPackingTypeFk; @@ -75250,10 +76004,10 @@ proc:BEGIN FROM tmp.saleGroup WHERE itemPackingTypeFk IS NOT NULL; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketIPT; - CREATE TEMPORARY TABLE tmp.ticketIPT - (ticketFk INT, - itemPackingTypeFk VARCHAR(1)); + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT ( + ticketFk INT, + itemPackingTypeFk VARCHAR(1) + ) ENGINE = MEMORY; CASE vPackingTypesToSplit WHEN 0 THEN @@ -75294,7 +76048,7 @@ proc:BEGIN SELECT itemPackingTypeFk INTO vItemPackingTypeFk FROM tmp.saleGroup sg - WHERE NOT ISNULL(sg.itemPackingTypeFk) + WHERE sg.itemPackingTypeFk IS NOT NULL ORDER BY sg.itemPackingTypeFk LIMIT 1; @@ -75305,8 +76059,9 @@ proc:BEGIN WHERE ts.itemPackingTypeFk IS NULL; END CASE; - DROP TEMPORARY TABLE tmp.sale; - DROP TEMPORARY TABLE tmp.saleGroup; + DROP TEMPORARY TABLE + tmp.sale, + tmp.saleGroup; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -80930,126 +81685,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255), + vHasInsert BOOL ) -BEGIN -/** - * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. - * @param vSelf Id de la zona - * @param vParentFk Id del geo a calcular - * @param vSearch Cadena a buscar - * @param vHasInsert Indica si inserta en tmp.zoneNodes - * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; - - CREATE OR REPLACE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id - FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk - FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - CREATE OR REPLACE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM tNodes; - - CREATE OR REPLACE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF NOT ROW_COUNT() THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE tChilds, tParents; - END IF; - - IF NOT vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tZones - SELECT g.id, - g.name, - g.parentFk, - g.sons, - NOT g.sons OR `type` = 'country' isChecked, - i.isIncluded selected, - g.`depth`, - vSelf - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i ON i.geoFk = g.id - AND i.zoneFk = vSelf - ORDER BY g.`depth`, selected DESC, g.name; - - IF vHasInsert THEN - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT id, - name, - parentFk, - sons, - isChecked, - vSelf - FROM tZones - WHERE selected - OR (selected IS NULL AND vParentFk IS NOT NULL); - ELSE - SELECT id, - name, - parentFk, - sons, - selected - FROM tZones - ORDER BY `depth`, selected DESC, name; - END IF; - - DROP TEMPORARY TABLE tNodes, tZones; +BEGIN +/** + * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch Cadena a buscar + * @param vHasInsert Indica si inserta en tmp.zoneNodes + * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; + + CREATE OR REPLACE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id + FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk + FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + CREATE OR REPLACE TEMPORARY TABLE tChilds + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM tNodes; + + CREATE OR REPLACE TEMPORARY TABLE tParents + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF NOT ROW_COUNT() THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE tChilds, tParents; + END IF; + + IF NOT vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id + FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tZones + SELECT g.id, + g.name, + g.parentFk, + g.sons, + NOT g.sons OR `type` = 'country' isChecked, + i.isIncluded selected, + g.`depth`, + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i ON i.geoFk = g.id + AND i.zoneFk = vSelf + ORDER BY g.`depth`, selected DESC, g.name; + + IF vHasInsert THEN + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT id, + name, + parentFk, + sons, + isChecked, + vSelf + FROM tZones + WHERE selected + OR (selected IS NULL AND vParentFk IS NOT NULL); + ELSE + SELECT id, + name, + parentFk, + sons, + selected + FROM tZones + ORDER BY `depth`, selected DESC, name; + END IF; + + DROP TEMPORARY TABLE tNodes, tZones; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81232,48 +81987,48 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) -BEGIN -/** - * Devuelve los códigos postales incluidos en una zona - */ - DECLARE vGeoFk INT DEFAULT NULL; - - CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( - geoFk INT, - name VARCHAR(100), - parentFk INT, - sons INT, - isChecked BOOL DEFAULT 0, - zoneFk INT, - PRIMARY KEY zoneNodesPk (zoneFk, geoFk), - INDEX(geoFk)) - ENGINE = MEMORY; - - CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - - UPDATE tmp.zoneNodes - SET isChecked = 0 - WHERE parentFk IS NULL; - - myLoop: LOOP - SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes - WHERE NOT isChecked - LIMIT 1; - - CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); - UPDATE tmp.zoneNodes - SET isChecked = TRUE - WHERE geoFk = vGeoFk; - - IF vGeoFk IS NULL THEN - LEAVE myLoop; - END IF; - END LOOP; - - DELETE FROM tmp.zoneNodes - WHERE sons > 0; +BEGIN +/** + * Devuelve los códigos postales incluidos en una zona + */ + DECLARE vGeoFk INT DEFAULT NULL; + + CREATE OR REPLACE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneNodesPk (zoneFk, geoFk), + INDEX(geoFk)) + ENGINE = MEMORY; + + CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); + + UPDATE tmp.zoneNodes + SET isChecked = 0 + WHERE parentFk IS NULL; + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes + WHERE NOT isChecked + LIMIT 1; + + CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + END LOOP; + + DELETE FROM tmp.zoneNodes + WHERE sons > 0; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -89804,4 +90559,4 @@ USE `vn2008`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-06-25 7:26:45 +-- Dump completed on 2024-07-09 5:48:04 diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql index 90ff6b30d..41525b2eb 100644 --- a/db/dump/.dump/triggers.sql +++ b/db/dump/.dump/triggers.sql @@ -3616,6 +3616,46 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientUnpaid_beforeInsert` + BEFORE INSERT ON `clientUnpaid` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`clientUnpaid_beforeUpdate` + BEFORE UPDATE ON `clientUnpaid` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`cmr_beforeDelete` BEFORE DELETE ON `cmr` FOR EACH ROW @@ -4671,11 +4711,9 @@ BEGIN IF NEW.isBooked = OLD.isBooked AND ( NOT (NEW.supplierFk <=> OLD.supplierFk) OR NOT (NEW.dated <=> OLD.dated) OR - NOT (NEW.invoiceNumber <=> OLD.invoiceNumber) OR NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.companyFk <=> OLD.companyFk) OR NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) OR - NOT (NEW.invoiceAmount <=> OLD.invoiceAmount) OR NOT (NEW.typeFk <=> OLD.typeFk) ) THEN @@ -6144,6 +6182,7 @@ DELIMITER ;; BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); + SET NEW.available = NEW.visible; END */;; DELIMITER ; @@ -6160,48 +6199,20 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_afterInsert` - AFTER INSERT ON `itemShelving` - FOR EACH ROW -INSERT INTO vn.itemShelvingLog( itemShelvingFk, - workerFk, - accion, - itemFk, - shelvingFk, - visible, - `grouping`, - packing) - VALUES( NEW.id, - NEW.userFk, - 'CREA REGISTRO', - NEW.itemFk, - NEW.shelvingFk, - NEW.visible, - NEW.`grouping`, - NEW.packing - ) */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_beforeUpdate` BEFORE UPDATE ON `itemShelving` FOR EACH ROW BEGIN + SET NEW.editorFk = account.myUser_getId(); IF NEW.userFk IS NULL THEN SET NEW.userFk = account.myUser_getId(); END IF; + + IF (NEW.visible <> OLD.visible) THEN + SET NEW.available = GREATEST(NEW.available + NEW.visible - OLD.visible, 0); + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6220,7 +6231,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_afterUpdate` AFTER UPDATE ON `itemShelving` FOR EACH ROW -INSERT INTO itemShelvingLog +BEGIN + INSERT INTO itemShelvingLog SET itemShelvingFk = NEW.id, workerFk = account.myUser_getId(), accion = 'CAMBIO', @@ -6228,7 +6240,10 @@ INSERT INTO itemShelvingLog shelvingFk = NEW.shelvingFk, visible = NEW.visible, `grouping` = NEW.`grouping`, - packing = NEW.packing */;; + packing = NEW.packing, + available = NEW.available; + +END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; @@ -6297,12 +6312,12 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelvingSale_afterInsert` AFTER INSERT ON `itemShelvingSale` FOR EACH ROW -BEGIN - - UPDATE vn.sale - SET isPicked = TRUE - WHERE id = NEW.saleFk; - +BEGIN + + UPDATE sale s + JOIN operator o ON o.workerFk = account.myUser_getId() + SET s.isPicked = IF(o.isOnReservationMode, s.isPicked, TRUE) + WHERE id = NEW.saleFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10924,4 +10939,4 @@ USE `vn2008`; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-06-25 7:27:06 +-- Dump completed on 2024-07-09 5:48:24 -- 2.40.1 From 3f0335cf37e4fe4a9f83d50c51683e269e9ec5f5 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 08:37:36 +0200 Subject: [PATCH 405/413] feat: refs #7644 Added with recursive buy-label --- print/templates/reports/buy-label/buy-label.js | 2 +- print/templates/reports/buy-label/sql/buys.sql | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/print/templates/reports/buy-label/buy-label.js b/print/templates/reports/buy-label/buy-label.js index b6e0a5031..7d626c052 100755 --- a/print/templates/reports/buy-label/buy-label.js +++ b/print/templates/reports/buy-label/buy-label.js @@ -7,7 +7,7 @@ module.exports = { name: 'buy-label', mixins: [vnReport], async serverPrefetch() { - this.buys = await this.rawSqlFromDef('buys', [this.id]); + this.buys = await this.rawSqlFromDef('buys', [this.id, this.id]); this.maxLabelNum = Math.max(...this.buys.map(buy => buy.labelNum)); const date = new Date(); this.weekNum = moment(date).isoWeek(); diff --git a/print/templates/reports/buy-label/sql/buys.sql b/print/templates/reports/buy-label/sql/buys.sql index 41fd3556b..e05ca2a66 100644 --- a/print/templates/reports/buy-label/sql/buys.sql +++ b/print/templates/reports/buy-label/sql/buys.sql @@ -1,4 +1,15 @@ -SELECT ROW_NUMBER() OVER(ORDER BY b.id) labelNum, +WITH RECURSIVE numbers AS ( + SELECT 1 n + UNION ALL + SELECT n + 1 + FROM numbers + WHERE n < ( + SELECT MAX(stickers) + FROM buy + WHERE entryFk = ? + ) +) +SELECT ROW_NUMBER() OVER(ORDER BY b.id, num.n) labelNum, i.name, i.`size`, i.category, @@ -15,4 +26,6 @@ SELECT ROW_NUMBER() OVER(ORDER BY b.id) labelNum, LEFT JOIN producer p ON p.id = i.producerFk LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN origin o ON o.id = i.originFk - WHERE b.entryFk = ? \ No newline at end of file + JOIN numbers num + WHERE b.entryFk = ? + AND num.n <= b.stickers \ No newline at end of file -- 2.40.1 From 6430fb5b5178b1ce2046250d51d0d9a025cb0e30 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 08:43:02 +0200 Subject: [PATCH 406/413] refactor: refs #7662 Requested changes --- db/routines/vn/procedures/ticket_splitItemPackingType.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index 87fbafe13..db2d1e4c1 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -10,6 +10,7 @@ BEGIN * * @param vSelf Id ticket * @param vItemPackingTypeFk Tipo para el que se reserva el número de ticket original + * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; DECLARE vNewTicketFk INT; @@ -101,7 +102,6 @@ BEGIN FROM sale s JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk - WHERE s.ticketFk = vSelf FOR UPDATE; UPDATE sale s -- 2.40.1 From 3e4bf55eedfd296acf536e505af37d3958eea445 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 11:03:17 +0200 Subject: [PATCH 407/413] fix: refs #7490 Correction --- db/routines/vn/procedures/duaInvoiceInBooking.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index 6d0c9f517..10c0714e5 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -81,7 +81,7 @@ BEGIN AND (NOT e.isBooked OR NOT e.isConfirmed) ), notBookedEntries AS ( - SELECT e.id + SELECT entryFk FROM vn.duaEntry WHERE duaFk = vDuaFk AND NOT customsValue -- 2.40.1 From be83fa672957c57014cce14e8d20ef497e706985 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 11:13:55 +0200 Subject: [PATCH 408/413] fix: refs #7622 Fix --- modules/client/back/model-config.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index fc1254dd8..e6690ee5f 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -5,7 +5,7 @@ "AddressObservation": { "dataSource": "vn" }, - "AddressShortage": { + "AddressWaste": { "dataSource": "vn" }, "BankEntity": { -- 2.40.1 From 769ee33ab21effdc47c4a5eba644318eac773400 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 11:40:24 +0200 Subject: [PATCH 409/413] fix: refs #7126 Added addressWaste type --- db/routines/bs/procedures/waste_addSales.sql | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index 07ae088e5..14559e617 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -11,22 +11,14 @@ BEGIN SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) value, SUM ( IF( - a.nickname IN ( - 'MERMA: FALTAS', - 'MERMA: CONTENEDOR', - 'MERMA: TRANSPORTE/OTROS' - ), + aw.type = 'internal', (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, 0 ) ) internalWaste, SUM ( IF( - a.nickname IN ( - 'MERMA: RECLAMACION BASURA', - 'MERMA: RECLAMACION TALLER', - 'MERMA: RECLAMACION FALTAS' - ), + aw.type = 'external', (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, IF(c.code = 'manaClaim', sc.value * s.quantity, @@ -39,6 +31,7 @@ BEGIN JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.ticket t ON t.id = s.ticketFk STRAIGHT_JOIN vn.address a ON a.id = t.addressFk + LEFT JOIN vn.addressWaste aw ON aw.addressFk = a.id JOIN vn.warehouse w ON w.id = t.warehouseFk JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = w.id -- 2.40.1 From c3051ebcfbe70dc2dc923e705d2d00daf4ca00c6 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 11:43:15 +0200 Subject: [PATCH 410/413] fix: refs #7126 Fix --- db/routines/bs/procedures/waste_addSales.sql | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index 14559e617..4727efec9 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -36,8 +36,8 @@ BEGIN JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = w.id JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id - LEFT JOIN component c ON c.id = sc.componentFk + LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id + LEFT JOIN vn.component c ON c.id = sc.componentFk WHERE w.isManaged AND YEAR(t.shipped) = YEAR(util.VN_CURDATE()) AND WEEK(t.shipped, 4) = WEEK(util.VN_CURDATE(), 4) -- 2.40.1 From f4e5f0205dc28621ea5b779a0abce2e03bb1c331 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 11:56:32 +0200 Subject: [PATCH 411/413] fix: refs #7126 Fix --- db/routines/bs/procedures/waste_addSales.sql | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index 4727efec9..ab87a0392 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -1,6 +1,8 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`() BEGIN + CALL cache.last_buy_refresh (FALSE); + REPLACE bs.waste SELECT YEAR(t.shipped), WEEK(t.shipped, 4), @@ -11,14 +13,14 @@ BEGIN SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) value, SUM ( IF( - aw.type = 'internal', + aw.`type` = 'internal', (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, 0 ) ) internalWaste, SUM ( IF( - aw.type = 'external', + aw.`type` = 'external', (b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity, IF(c.code = 'manaClaim', sc.value * s.quantity, @@ -30,7 +32,7 @@ BEGIN JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.ticket t ON t.id = s.ticketFk - STRAIGHT_JOIN vn.address a ON a.id = t.addressFk + JOIN vn.address a FORCE INDEX (PRIMARY) ON a.id = t.addressFk LEFT JOIN vn.addressWaste aw ON aw.addressFk = a.id JOIN vn.warehouse w ON w.id = t.warehouseFk JOIN cache.last_buy lb ON lb.item_id = i.id -- 2.40.1 From bb7002b7022a12d30d8deeefe18856a9c0ece812 Mon Sep 17 00:00:00 2001 From: guillermo Date: Tue, 9 Jul 2024 12:00:55 +0200 Subject: [PATCH 412/413] fix: refs #7126 Minor change --- db/routines/bs/procedures/waste_addSales.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index ab87a0392..234719582 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -10,7 +10,7 @@ BEGIN it.id, s.itemFk, SUM(s.quantity), - SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) value, + SUM((b.buyingValue + b.freightValue + b.comissionValue + b.packageValue) * s.quantity) `value`, SUM ( IF( aw.`type` = 'internal', -- 2.40.1 From 889982dd82e09e038ae3a89766b50481742b4a56 Mon Sep 17 00:00:00 2001 From: guillermo Date: Wed, 10 Jul 2024 12:00:54 +0200 Subject: [PATCH 413/413] refactor: refs #7126 Requested changes --- db/routines/bs/procedures/waste_addSales.sql | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/db/routines/bs/procedures/waste_addSales.sql b/db/routines/bs/procedures/waste_addSales.sql index 234719582..3e189d2e6 100644 --- a/db/routines/bs/procedures/waste_addSales.sql +++ b/db/routines/bs/procedures/waste_addSales.sql @@ -1,7 +1,10 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `bs`.`waste_addSales`() BEGIN - CALL cache.last_buy_refresh (FALSE); + DECLARE vDateFrom DATE DEFAULT util.VN_CURDATE() - INTERVAL WEEKDAY(CURDATE()) DAY; + DECLARE vDateTo DATE DEFAULT vDateFrom + INTERVAL 6 DAY; + + CALL cache.last_buy_refresh(FALSE); REPLACE bs.waste SELECT YEAR(t.shipped), @@ -40,9 +43,8 @@ BEGIN JOIN vn.buy b ON b.id = lb.buy_id LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id LEFT JOIN vn.component c ON c.id = sc.componentFk - WHERE w.isManaged - AND YEAR(t.shipped) = YEAR(util.VN_CURDATE()) - AND WEEK(t.shipped, 4) = WEEK(util.VN_CURDATE(), 4) + WHERE t.shipped BETWEEN vDateFrom AND vDateTo + AND w.isManaged GROUP BY it.id, i.id; END$$ DELIMITER ; -- 2.40.1