diff --git a/.eslintrc.yml b/.eslintrc.yml index edbc47195..0d74348f2 100644 --- a/.eslintrc.yml +++ b/.eslintrc.yml @@ -36,3 +36,7 @@ rules: jasmine/no-focused-tests: 0 jasmine/prefer-toHaveBeenCalledWith: 0 arrow-spacing: ["error", { "before": true, "after": true }] + no-restricted-syntax: + - "error" + - selector: "NewExpression[callee.name='Date']" + message: "Use Date.vnNew() instead of new Date()." diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index a9e5f2e60..f3575672f 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -29,10 +29,8 @@ module.exports = Self => { }); Self.getSales = async(ctx, collectionOrTicketFk, print, source, options) => { - const models = Self.app.models; const userId = ctx.req.accessToken.userId; const myOptions = {userId}; - const $t = ctx.req.__; if (typeof options == 'object') Object.assign(myOptions, options); @@ -59,22 +57,6 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); - for (let ticket of tickets) { - 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}) - ); - } - } - } - } - return getCollection(id, tickets, sales, placements, myOptions); }; diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 48301a366..3c2f6cb2d 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -57,10 +57,10 @@ module.exports = Self => { ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY pickingOrder) currentItemShelving, COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) totalItemShelving, sh.code, - p2.code parkingCode, - p2.pickingOrder pickingOrder, - p.code parkingCodePrevia, - p.pickingOrder pickingOrderPrevia, + p2.code parkingCodePrevia, + p2.pickingOrder pickingOrderPrevia, + p.code parkingCode, + p.pickingOrder pickingOrder, iss.id itemShelvingSaleFk, iss.isPicked, iss.itemShelvingFk @@ -73,7 +73,7 @@ module.exports = Self => { JOIN item i ON i.id = s.itemFk 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 shelving sh ON sh.id = 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 @@ -114,7 +114,7 @@ module.exports = Self => { JOIN item i ON i.id = s.itemFk 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 shelving sh ON sh.id = 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 diff --git a/back/methods/collection/spec/assign.spec.js b/back/methods/collection/spec/assign.spec.js index 745343819..b00631d22 100644 --- a/back/methods/collection/spec/assign.spec.js +++ b/back/methods/collection/spec/assign.spec.js @@ -28,9 +28,10 @@ describe('ticket assign()', () => { await tx.rollback(); }); - it('should throw an error when there is not picking tickets', async() => { + it('should throw an error when there are no picking tickets', async() => { try { await models.Collection.assign(ctx, options); + fail('Expected an error to be thrown, but none was thrown.'); } catch (e) { expect(e.message).toEqual('There are not picking tickets'); } diff --git a/back/methods/mrw-config/cancelShipment.js b/back/methods/mrw-config/cancelShipment.js index 56d206529..98aa8be39 100644 --- a/back/methods/mrw-config/cancelShipment.js +++ b/back/methods/mrw-config/cancelShipment.js @@ -39,6 +39,9 @@ module.exports = Self => { const xmlString = response.data; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); + + await Self.rawSql('CALL util.debugAdd(?,?);', ['cancelShipment', xmlDoc]); + const result = xmlDoc.getElementsByTagName('Mensaje')[0].textContent; return result.toLowerCase().includes('se ha cancelado correctamente'); }; diff --git a/back/methods/workerActivity/add.js b/back/methods/workerActivity/add.js index 4592a0797..89131491d 100644 --- a/back/methods/workerActivity/add.js +++ b/back/methods/workerActivity/add.js @@ -31,7 +31,7 @@ module.exports = Self => { return await Self.rawSql(` INSERT INTO workerActivity (workerFk, workerActivityTypeFk, model) SELECT ?, ?, ? - FROM workerTimeControlParams wtcp + FROM workerTimeControlConfig wtcc LEFT JOIN ( SELECT wa.workerFk, wa.created, @@ -44,7 +44,7 @@ module.exports = Self => { ) sub ON TRUE WHERE sub.workerFk IS NULL OR sub.code <> ? - OR TIMESTAMPDIFF(SECOND, sub.created, util.VN_NOW()) > wtcp.dayBreak;` + OR TIMESTAMPDIFF(SECOND, sub.created, util.VN_NOW()) > wtcc.dayBreak;` , [userId, code, model, userId, code], myOptions); }; }; diff --git a/back/model-config.json b/back/model-config.json index 364ffabdf..b543071c9 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -79,6 +79,9 @@ "ImageCollectionSize": { "dataSource": "vn" }, + "ImageConfig": { + "dataSource": "vn" + }, "ImageContainer": { "dataSource": "imageStorage" }, diff --git a/back/models/expedition_PrintOut.json b/back/models/expedition_PrintOut.json index dd49b0234..23a2fdbc4 100644 --- a/back/models/expedition_PrintOut.json +++ b/back/models/expedition_PrintOut.json @@ -14,9 +14,6 @@ }, "itemFk": { "type": "number" - }, - "isChecked": { - "type": "boolean" } } } \ No newline at end of file diff --git a/back/models/image-config.json b/back/models/image-config.json new file mode 100644 index 000000000..11f4c2284 --- /dev/null +++ b/back/models/image-config.json @@ -0,0 +1,22 @@ +{ + "name": "ImageConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "hedera.imageConfig" + } + }, + "properties": { + "url": { + "type": "string" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$authenticated", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/back/models/say-simple-config.json b/back/models/say-simple-config.json index edc4caa43..d5d4f8a6f 100644 --- a/back/models/say-simple-config.json +++ b/back/models/say-simple-config.json @@ -13,6 +13,9 @@ }, "url": { "type": "string" + }, + "defaultChannel": { + "type": "number" } }, "acls": [ diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index 870b24f49..6bcfe2c9f 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -2084,7 +2084,7 @@ INSERT INTO `ACL` VALUES (756,'Route','findOne','READ','ALLOW','ROLE','employee' INSERT INTO `ACL` VALUES (757,'Route','getRoutesByWorker','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (758,'Route','canViewAllRoute','READ','ALLOW','ROLE','deliveryAssistant',NULL); INSERT INTO `ACL` VALUES (759,'Route','cmr','READ','ALLOW','ROLE','employee',NULL); -INSERT INTO `ACL` VALUES (760,'Route','downloadCmrsZip','READ','ALLOW','ROLE','employee',NULL); +INSERT INTO `ACL` VALUES (760,'Cmr','downloadZip','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (761,'Route','downloadZip','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (762,'Route','filter','READ','ALLOW','ROLE','employee',NULL); INSERT INTO `ACL` VALUES (763,'Route','getByWorker','READ','ALLOW','ROLE','employee',NULL); diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index e4e59a6bf..e6c0e6674 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -2955,55 +2955,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 */ ; @@ -3021,21 +3021,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 */ ; @@ -3224,18 +3224,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 */ ; @@ -4516,29 +4516,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 */ ; @@ -5465,82 +5465,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 */ ; @@ -7285,27 +7285,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 */ ; @@ -7323,89 +7323,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 */ ; @@ -10429,28 +10429,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 */ ; @@ -10469,27 +10469,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 */ ; @@ -42397,37 +42397,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`vn`@`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 */ ; @@ -51221,93 +51221,93 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_addWithReservation`( - vItemFk INT, - vQuantity INT, - vTicketFk INT, - vSaleGroupFk INT, - vSectorFk INT +CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_addWithReservation`( + vItemFk INT, + vQuantity INT, + vTicketFk INT, + vSaleGroupFk INT, + vSectorFk 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, vSectorFk); - - 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; +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, vSectorFk); + + 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 */ ; @@ -51324,145 +51324,145 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_assign`( - vUserFk INT, - OUT vCollectionFk INT +CREATE DEFINER=`vn`@`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; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vCollectionWorker INT; - DECLARE vMaxNotAssignedCollectionLifeTime TIME; - - DECLARE vCollections CURSOR FOR - WITH collections AS ( - SELECT tc.collectionFk, - SUM(sv.volume) volume, - c.saleTotalCount, - c.itemPackingTypeFk, - c.trainFk, - c.warehouseFk, - c.wagons - FROM vn.ticketCollection tc - JOIN vn.collection c ON c.id = tc.collectionFk - JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk - WHERE c.workerFk IS NULL - AND sv.shipped >= util.VN_CURDATE() - GROUP BY tc.collectionFk - ) SELECT c.collectionFk - FROM collections c - JOIN vn.operator o - WHERE o.workerFk = vUserFk - AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) - AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - -- Si hay colecciones sin terminar, sale del proceso - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime - INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime - 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' - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime; - - DELETE FROM `collection` - WHERE workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - - INSERT INTO collectionHotbed(userFk) VALUES(vUserFk); - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - - OPEN vCollections; - l: LOOP - SET vDone = FALSE; - FETCH vCollections INTO vCollectionFk; - - IF vDone THEN - LEAVE l; - END IF; - - BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - SET vCollectionFk = NULL; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT workerFk INTO vCollectionWorker - FROM `collection` - WHERE id = vCollectionFk FOR UPDATE; - - IF vCollectionWorker IS NULL THEN - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; - - COMMIT; - LEAVE l; - END IF; - - ROLLBACK; - END; - END LOOP; - CLOSE vCollections; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - - START TRANSACTION; - - SELECT workerFk INTO vCollectionWorker - FROM `collection` - WHERE id = vCollectionFk FOR UPDATE; - - IF vCollectionWorker IS NULL THEN - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; - END IF; - - COMMIT; - END IF; +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 vDone BOOL DEFAULT FALSE; + DECLARE vCollectionWorker INT; + DECLARE vMaxNotAssignedCollectionLifeTime TIME; + + DECLARE vCollections CURSOR FOR + WITH collections AS ( + SELECT tc.collectionFk, + SUM(sv.volume) volume, + c.saleTotalCount, + c.itemPackingTypeFk, + c.trainFk, + c.warehouseFk, + c.wagons + FROM vn.ticketCollection tc + JOIN vn.collection c ON c.id = tc.collectionFk + JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE c.workerFk IS NULL + AND sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) SELECT c.collectionFk + FROM collections c + JOIN vn.operator o + WHERE o.workerFk = vUserFk + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + -- Si hay colecciones sin terminar, sale del proceso + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime + INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime + 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' + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime; + + DELETE FROM `collection` + WHERE workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + + INSERT INTO collectionHotbed(userFk) VALUES(vUserFk); + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + + OPEN vCollections; + l: LOOP + SET vDone = FALSE; + FETCH vCollections INTO vCollectionFk; + + IF vDone THEN + LEAVE l; + END IF; + + BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + SET vCollectionFk = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + COMMIT; + LEAVE l; + END IF; + + ROLLBACK; + END; + END LOOP; + CLOSE vCollections; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + END IF; + + COMMIT; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51530,146 +51530,146 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `collection_getAssigned`( - vUserFk INT, - OUT vCollectionFk INT +CREATE DEFINER=`vn`@`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. - * - * @param vUserFk Id de usuario - * @param vCollectionFk Id de colección - */ - DECLARE vHasTooMuchCollections BOOL; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vCollectionWorker INT; - DECLARE vMaxNotAssignedCollectionLifeTime TIME; - - DECLARE vCollections CURSOR FOR - WITH collections AS ( - SELECT tc.collectionFk, - SUM(sv.volume) volume, - c.saleTotalCount, - c.itemPackingTypeFk, - c.trainFk, - c.warehouseFk, - c.wagons - FROM vn.ticketCollection tc - JOIN vn.collection c ON c.id = tc.collectionFk - JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk - WHERE c.workerFk IS NULL - AND sv.shipped >= util.VN_CURDATE() - GROUP BY tc.collectionFk - ) SELECT c.collectionFk - FROM collections c - JOIN vn.operator o - WHERE o.workerFk = vUserFk - AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) - AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL) - AND o.numberOfWagons = c.wagons - AND o.trainFk = c.trainFk - AND o.warehouseFk = c.warehouseFk; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - -- Si hay colecciones sin terminar, sale del proceso - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CALL collection_get(vUserFk); - - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime - INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime - 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' - WHERE c.workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime; - - DELETE FROM `collection` - WHERE workerFk IS NULL - AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime; - - -- Se añade registro al semillero - - INSERT INTO collectionHotbed(userFk) VALUES(vUserFk); - - -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion - - OPEN vCollections; - l: LOOP - SET vDone = FALSE; - FETCH vCollections INTO vCollectionFk; - - IF vDone THEN - LEAVE l; - END IF; - - BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - SET vCollectionFk = NULL; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT workerFk INTO vCollectionWorker - FROM `collection` - WHERE id = vCollectionFk FOR UPDATE; - - IF vCollectionWorker IS NULL THEN - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; - - COMMIT; - LEAVE l; - END IF; - - ROLLBACK; - END; - END LOOP; - CLOSE vCollections; - - IF vCollectionFk IS NULL THEN - CALL collection_new(vUserFk, vCollectionFk); - - START TRANSACTION; - - SELECT workerFk INTO vCollectionWorker - FROM `collection` - WHERE id = vCollectionFk FOR UPDATE; - - IF vCollectionWorker IS NULL THEN - UPDATE `collection` - SET workerFk = vUserFk - WHERE id = vCollectionFk; - END IF; - - COMMIT; - END IF; - CALL itemShelvingSale_addByCollection(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 vDone BOOL DEFAULT FALSE; + DECLARE vCollectionWorker INT; + DECLARE vMaxNotAssignedCollectionLifeTime TIME; + + DECLARE vCollections CURSOR FOR + WITH collections AS ( + SELECT tc.collectionFk, + SUM(sv.volume) volume, + c.saleTotalCount, + c.itemPackingTypeFk, + c.trainFk, + c.warehouseFk, + c.wagons + FROM vn.ticketCollection tc + JOIN vn.collection c ON c.id = tc.collectionFk + JOIN vn.saleVolume sv ON sv.ticketFk = tc.ticketFk + WHERE c.workerFk IS NULL + AND sv.shipped >= util.VN_CURDATE() + GROUP BY tc.collectionFk + ) SELECT c.collectionFk + FROM collections c + JOIN vn.operator o + WHERE o.workerFk = vUserFk + AND (c.saleTotalCount <= o.linesLimit OR o.linesLimit IS NULL) + AND (c.itemPackingTypeFk = o.itemPackingTypeFk OR o.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + -- Si hay colecciones sin terminar, sale del proceso + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, pc.maxNotAssignedCollectionLifeTime + INTO vHasTooMuchCollections, vMaxNotAssignedCollectionLifeTime + 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' + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > vMaxNotAssignedCollectionLifeTime; + + DELETE FROM `collection` + WHERE workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), created) > vMaxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + + INSERT INTO collectionHotbed(userFk) VALUES(vUserFk); + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + + OPEN vCollections; + l: LOOP + SET vDone = FALSE; + FETCH vCollections INTO vCollectionFk; + + IF vDone THEN + LEAVE l; + END IF; + + BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + SET vCollectionFk = NULL; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + COMMIT; + LEAVE l; + END IF; + + ROLLBACK; + END; + END LOOP; + CLOSE vCollections; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + + START TRANSACTION; + + SELECT workerFk INTO vCollectionWorker + FROM `collection` + WHERE id = vCollectionFk FOR UPDATE; + + IF vCollectionWorker IS NULL THEN + UPDATE `collection` + SET workerFk = vUserFk + WHERE id = vCollectionFk; + END IF; + + COMMIT; + END IF; + CALL itemShelvingSale_addByCollection(vCollectionFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60050,53 +60050,53 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_addByCollection`( - vCollectionFk INT(11) +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_addByCollection`( + vCollectionFk INT(11) ) -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, NULL); - END LOOP; - CLOSE vSales; +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, NULL); + END LOOP; + CLOSE vSales; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60437,56 +60437,56 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_doReserve`() -proc: BEGIN -/** - * Genera reservas de la tabla vn.itemShelvingSaleReserve - */ - DECLARE vDone BOOL; - DECLARE vSaleFk INT; - DECLARE vSectorFk INT; - - DECLARE vSales CURSOR FOR - SELECT DISTINCT saleFk, sectorFk 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, sectorFk FROM itemShelvingSaleReserve; - - OPEN vSales; - - myLoop: LOOP - SET vDone = FALSE; - FETCH vSales INTO vSaleFk, vSectorFk; - - IF vDone THEN - LEAVE myLoop; - END IF; - - CALL itemShelvingSale_addBySale (vSaleFk, vSectorFk); - END LOOP; - - CLOSE vSales; - - DELETE iss FROM itemShelvingSaleReserve iss - JOIN tSale s ON s.id = iss.id AND s.sectorFk = iss.sectorFk; - - DROP TEMPORARY TABLE tSale; - - DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); +proc: BEGIN +/** + * Genera reservas de la tabla vn.itemShelvingSaleReserve + */ + DECLARE vDone BOOL; + DECLARE vSaleFk INT; + DECLARE vSectorFk INT; + + DECLARE vSales CURSOR FOR + SELECT DISTINCT saleFk, sectorFk 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, sectorFk FROM itemShelvingSaleReserve; + + OPEN vSales; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk, vSectorFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + CALL itemShelvingSale_addBySale (vSaleFk, vSectorFk); + END LOOP; + + CLOSE vSales; + + DELETE iss FROM itemShelvingSaleReserve iss + JOIN tSale s ON s.id = iss.id AND s.sectorFk = iss.sectorFk; + + DROP TEMPORARY TABLE tSale; + + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60571,37 +60571,37 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_setPicked`( - vSaleGroupFk INT(10) +CREATE DEFINER=`vn`@`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; +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 */ ; @@ -60618,114 +60618,114 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( - vItemShelvingSaleFk INT(10), - vQuantity DECIMAL(10,0), - vIsItemShelvingSaleEmpty BOOLEAN, - vSectorFk INT +CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN, + vSectorFk INT ) -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 - * @param vSectorFk Id del sector - */ - DECLARE vSaleFk INT; - DECLARE vItemShelvingFk INT; - DECLARE vReservedQuantity INT; - DECLARE vRemainingQuantity INT; - DECLARE vItemFk INT; - DECLARE vTotalQuantity INT; - DECLARE vStateCode VARCHAR(45); - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - IF vQuantity > vReservedQuantity - OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) - OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN - CALL util.throw('The quantity cannot be different from the reserved'); - END IF; - - 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)), - IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED') - INTO vItemFk, - vSaleFk, - vItemShelvingFk, - vReservedQuantity, - vStateCode - FROM itemShelvingSale iss - JOIN sale s ON s.id = iss.saleFk - LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk - WHERE iss.id = vItemShelvingSaleFk - AND NOT iss.isPicked; - - IF vQuantity > vReservedQuantity - OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) - OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) 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 OR id = vItemShelvingSaleFk, 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, - vStateCode, - 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, sectorFk) - SELECT vSaleFk, vSectorFk; - CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk, vSectorFk); - END IF; +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 + * @param vSectorFk Id del sector + */ + DECLARE vSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vTotalQuantity INT; + DECLARE vStateCode VARCHAR(45); + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF vQuantity > vReservedQuantity + OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) + OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN + CALL util.throw('The quantity cannot be different from the reserved'); + END IF; + + 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)), + IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED') + INTO vItemFk, + vSaleFk, + vItemShelvingFk, + vReservedQuantity, + vStateCode + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + IF vQuantity > vReservedQuantity + OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) + OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) 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 OR id = vItemShelvingSaleFk, 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, + vStateCode, + 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, sectorFk) + SELECT vSaleFk, vSectorFk; + CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60742,63 +60742,63 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `itemShelvingSale_unpicked`( - vSelf INT(11) +CREATE DEFINER=`vn`@`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; +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 */ ; @@ -61293,167 +61293,167 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`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 */ ; @@ -63193,50 +63193,50 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`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 */ ; @@ -65424,176 +65424,176 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `multipleInventory`( - vDate DATE, - vWarehouseFk TINYINT, - vMaxDays TINYINT +CREATE DEFINER=`vn`@`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; - DECLARE vCalcFk 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; - - -- Cálculo del visible - CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); - - CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT item_id, visible - FROM cache.visible - WHERE calc_id = vCalcFk; - - UPDATE tmp.itemInventory it - LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id - LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id - SET it.inventory = iic.quantity, - it.visible = ivc.visible, - it.avalaible = iic.quantity, - it.sd = iic.quantity; - - -- 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); - - CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc - (PRIMARY KEY (itemFk)) - ENGINE = MEMORY - 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; - - UPDATE tmp.itemInventory it - JOIN tItemAvailableCalc iac ON iac.itemFk = it.id - SET it.avalaible = IF(iac.minQuantity > 0, - it.avalaible, - it.avalaible + iac.minQuantity), - it.sd = it.inventory + iac.quantity; - - DROP TEMPORARY TABLE - tmp.itemTravel, - tmp.itemCalc, - tmp.itemAtp, - tItemInventoryCalc, - tItemVisibleCalc, - tItemAvailableCalc; +proc: BEGIN + DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; + DECLARE vDateFrom DATE DEFAULT vDate; + DECLARE vDateTo DATETIME; + DECLARE vDateToTomorrow DATETIME; + DECLARE vDefaultDayRange INT; + DECLARE vCalcFk 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; + + -- Cálculo del visible + CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); + + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT item_id, visible + FROM cache.visible + WHERE calc_id = vCalcFk; + + UPDATE tmp.itemInventory it + LEFT JOIN tItemInventoryCalc iic ON iic.itemFk = it.id + LEFT JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id + SET it.inventory = iic.quantity, + it.visible = ivc.visible, + it.avalaible = iic.quantity, + it.sd = iic.quantity; + + -- 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); + + CREATE OR REPLACE TEMPORARY TABLE tItemAvailableCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + 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; + + UPDATE tmp.itemInventory it + JOIN tItemAvailableCalc iac ON iac.itemFk = it.id + SET it.avalaible = IF(iac.minQuantity > 0, + it.avalaible, + it.avalaible + iac.minQuantity), + it.sd = it.inventory + iac.quantity; + + DROP TEMPORARY TABLE + tmp.itemTravel, + tmp.itemCalc, + tmp.itemAtp, + tItemInventoryCalc, + tItemVisibleCalc, + tItemAvailableCalc; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70251,30 +70251,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`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 */ ; @@ -74173,62 +74173,62 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `ticket_DelayTruckSplit`( - vTicketFk INT +CREATE DEFINER=`vn`@`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; +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 */ ; @@ -74246,84 +74246,84 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`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 */ ; @@ -81979,126 +81979,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`vn`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`vn`@`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 */ ; @@ -82281,48 +82281,48 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`vn`@`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 */ ; diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index 68d8be097..e5d5f53dc 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -1254,9 +1254,9 @@ INSERT INTO `vn`.`saleComponent`(`saleFk`, `componentFk`, `value`) INSERT INTO `vn`.`itemShelving` (`itemFk`, `shelvingFk`, `visible`, `grouping`, `packing`,`buyFk`, `userFk`) VALUES - (2, 'GVC', 1, 1, 1, 2,1106), - (4, 'HEJ', 1, 1, 1, NULL,1106), - (1, 'UXN', 2, 12, 12, NULL,1106); + (2, 11, 1, 1, 1, 2,1106), + (4, 12, 1, 1, 1, NULL,1106), + (1, 13, 2, 12, 12, NULL,1106); INSERT INTO `vn`.`itemShelvingSale` (`itemShelvingFk`, `saleFk`, `quantity`, `created`, `userFk`) VALUES @@ -1505,32 +1505,32 @@ INSERT INTO `vn`.`awb` (id, code, package, weight, created, amount, transitoryFk (9, '99610289193', 302, 2972, util.VN_CURDATE(), 3871, 442, 1), (10, '07546500856', 185, 2364, util.VN_CURDATE(), 5321, 442, 1); -INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseOutFk`, `agencyModeFk`, `m3`, `kg`,`ref`, `totalEntries`, `cargoSupplierFk`, `awbFK`, `daysInForward`) - VALUES (1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 2, 1, 100.00, 1000, 'first travel', 1, 1, 1, NULL), - (2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 150.00, 2000, 'second travel', 2, 2, 2, NULL), - (3, util.VN_CURDATE(), util.VN_CURDATE(), 1, 2, 1, 0.00, 0.00, 'third travel', 1, 1, 3, NULL), - (4, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 3, 1, 50.00, 500, 'fourth travel', 0, 2, 4, NULL), - (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5, NULL), - (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6, NULL), - (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7, 2), - (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10, NULL), - (10, DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10, 2), - (11, util.VN_CURDATE() - INTERVAL 1 DAY , util.VN_CURDATE(), 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, NULL), - (12, util.VN_CURDATE() , util.VN_CURDATE() + INTERVAL 1 DAY, 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, NULL); +INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseOutFk`, `agencyModeFk`, `m3`, `kg`,`ref`, `totalEntries`, `cargoSupplierFk`, `awbFK`, `isRaid`, `daysInForward`) + VALUES (1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH), 1, 2, 1, 100.00, 1000, 'first travel', 1, 1, 1, FALSE, NULL), + (2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 2, 1, 150.00, 2000, 'second travel', 2, 2, 2, FALSE, NULL), + (3, util.VN_CURDATE(), util.VN_CURDATE(), 1, 2, 1, 0.00, 0.00, 'third travel', 1, 1, 3, FALSE, NULL), + (4, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 3, 1, 50.00, 500, 'fourth travel', 0, 2, 4, FALSE, NULL), + (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5, FALSE, NULL), + (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6, FALSE,NULL), + (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7, TRUE, 2), + (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10, FALSE, NULL), + (10, DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL +5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10, TRUE, 2), + (11, util.VN_CURDATE() - INTERVAL 1 DAY , util.VN_CURDATE(), 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, FALSE, NULL), + (12, util.VN_CURDATE() , util.VN_CURDATE() + INTERVAL 1 DAY, 6, 3, 0, 50.00, 500, 'eleventh travel', 1, 2, 4, FALSE, NULL); -INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `evaNotes`) - VALUES - (1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 442, 'IN2001', 'Movement 1', 0, ''), - (2, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 442, 'IN2002', 'Movement 2', 0, 'observation two'), - (3, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 0, 442, 'IN2003', 'Movement 3', 0, 'observation three'), - (4, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 69, 'IN2004', 'Movement 4', 0, 'observation four'), - (5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 'observation five'), - (6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 'observation six'), - (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 'observation seven'), - (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1,''), - (9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, ''), - (10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 10', 1, ''), - (99, 69, '2000-12-01 00:00:00.000', 11, 0, 442, 'IN2009', 'Movement 99', 0, ''); +INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `evaNotes`, `typeFk`) + VALUES + (1, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 1, 1, 442, 'IN2001', 'Movement 1', 0, '', 'packaging'), + (2, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 442, 'IN2002', 'Movement 2', 0, 'observation two', 'product'), + (3, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 0, 442, 'IN2003', 'Movement 3', 0, 'observation three', 'product'), + (4, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 2, 0, 69, 'IN2004', 'Movement 4', 0, 'observation four', 'product'), + (5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 'observation five', 'product'), + (6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 'observation six', 'product'), + (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 'observation seven', 'product'), + (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, '', 'product'), + (9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, '', 'product'), + (10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 10', 1, '', 'product'), + (99, 69, util.VN_CURDATE() - INTERVAL 1 MONTH, 11, 0, 442, 'IN2009', 'Movement 99', 0, '', 'product'); INSERT INTO `vn`.`entryConfig` (`defaultEntry`, `inventorySupplierFk`, `defaultSupplierFk`) VALUES (2, 4, 1); @@ -2521,10 +2521,6 @@ INSERT INTO `vn`.`queuePriority`(`id`, `priority`, `code`) (2, 'Normal', 'normal'), (3, 'Baja', 'low'); -INSERT INTO `vn`.`workerTimeControlParams` (`id`, `dayBreak`, `weekBreak`, `weekScope`, `dayWorkMax`, `dayStayMax`, `weekMaxBreak`, `weekMaxScope`, `askInOut`) - VALUES - (1, 43200, 129600, 734400, 43200, 50400, 259200, 1296000, 36000); - INSERT IGNORE INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11'); INSERT INTO `vn`.`thermograph`(`id`, `model`) @@ -3425,7 +3421,7 @@ INSERT INTO vn.buy INSERT INTO vn.itemShelving SET id = 9931, itemFk = 999993, - shelvingFk = 'NCC', + shelvingFk = 16, visible = 10, `grouping` = 5, packing = 10; @@ -3752,7 +3748,7 @@ INSERT vn.sale USE vn; DELETE ish.* FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk JOIN vn.warehouse w ON w.id = s.warehouseFk @@ -3761,22 +3757,22 @@ DELETE ish.* FROM vn.itemShelving ish INSERT INTO vn.itemShelving (itemFk, shelvingFk, visible, created, `grouping`, packing, packagingFk, userFk, isChecked) VALUES - (999991, 'NAA', 8, '2023-09-20', 1, 20, NULL, 103, NULL), - (999998, 'NAA', 80, '2023-09-20', 10, 30, NULL, 103, NULL), - (1000001, 'NAA', 6, '2023-09-20', 3, 50, NULL, 103, NULL), - (1000000, 'NBB', 50, '2023-09-18', 25, 500, NULL, 103, NULL), - (999993, 'NBB', 25, '2023-09-18', NULL, 10, NULL, 103, NULL), - (999999, 'NBB', 30, '2023-09-18', 10, 500, NULL, 103, NULL), - (999993, 'NCC', 25, '2023-09-20', 5, 10, NULL, 103, NULL), - (999997, 'NCC', 10, '2023-09-20', NULL, 100, NULL, 103, NULL), - (999999, 'NCC', 40, '2023-09-20', 10, 500, NULL, 103, NULL), - (999995, 'NDD', 10, '2023-09-19', NULL, 20, NULL, 103, NULL), - (999994, 'NDD', 48, '2023-09-19', 4, 20, NULL, 103, NULL), - (1000001, 'NEE', 6, '2023-09-21', 3, 50, NULL, 103, NULL), - (999992, 'NEE', 50, '2023-09-21', NULL, 1, NULL, 103, NULL), - (1000000, 'NEE', 25, '2023-09-21', 25, 500, NULL, 103, NULL), - (999996, 'PAA', 5, '2023-09-27', 1, 5, NULL, 103, NULL), - (999997, 'PCC', 10, '2023-09-27', 5, 100, NULL, 103, NULL); + (999991, 14, 8, '2023-09-20', 1, 20, NULL, 103, NULL), + (999998, 14, 80, '2023-09-20', 10, 30, NULL, 103, NULL), + (1000001, 14, 6, '2023-09-20', 3, 50, NULL, 103, NULL), + (1000000, 15, 50, '2023-09-18', 25, 500, NULL, 103, NULL), + (999993, 15, 25, '2023-09-18', NULL, 10, NULL, 103, NULL), + (999999, 15, 30, '2023-09-18', 10, 500, NULL, 103, NULL), + (999993, 16, 25, '2023-09-20', 5, 10, NULL, 103, NULL), + (999997, 16, 10, '2023-09-20', NULL, 100, NULL, 103, NULL), + (999999, 16, 40, '2023-09-20', 10, 500, NULL, 103, NULL), + (999995, 17, 10, '2023-09-19', NULL, 20, NULL, 103, NULL), + (999994, 17, 48, '2023-09-19', 4, 20, NULL, 103, NULL), + (1000001, 18, 6, '2023-09-21', 3, 50, NULL, 103, NULL), + (999992, 18, 50, '2023-09-21', NULL, 1, NULL, 103, NULL), + (1000000, 18, 25, '2023-09-21', 25, 500, NULL, 103, NULL), + (999996, 19, 5, '2023-09-27', 1, 5, NULL, 103, NULL), + (999997, 21, 10, '2023-09-27', 5, 100, NULL, 103, NULL); -- Previous for Bolas de madera INSERT IGNORE INTO vn.sectorCollection @@ -4008,10 +4004,17 @@ INSERT IGNORE INTO pbx.queueMember UPDATE vn.department SET pbxQueue = '1000' WHERE name = "CAMARA"; UPDATE vn.department SET pbxQueue = '2000' WHERE name = "VENTAS"; -INSERT INTO srt.buffer (id, x, y, `size`, `length`, stateFk, typeFk, isActive, code, stratus, hasWorkerWaiting, reserve, routeFk, dayMinute, lastUnloaded, hasStrapper, typeDefaultFk, motors, editorFk) +INSERT INTO vn.workerRelatives (workerFk, isDescendant, disabilityGradeFk, birthed, adoptionYear, isDependend, isJointCustody, updated) + VALUES + (1106, 1, NULL, 0, NULL, 0, 0, '2024-10-29 08:42:44.000'); +INSERT INTO vn.routeAction (id, name, price, isMainlineDelivered) VALUES(1, 'Pintar traje', 50.00, 0); +INSERT INTO vn.routeComplement (id, dated, workerFk, price, routeActionFk) VALUES(1, util.VN_CURDATE(), 9, 50.00, 1); + + +INSERT INTO srt.buffer (id, x, y, `size`, `length`, stateFk, typeFk, isActive, code, stratus, hasWorkerWaiting, reserve, routeFk, dayMinute, lastUnloaded, hasStrapper, typeDefaultFk, motors, editorFk) VALUES (0, 0, 0, 0, NULL, 3, 1, 0, 'ENT', 0, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), (1, 0, 9900, 0, NULL, 1, 0, 0, 'NOK', 0, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), - (2, 0, 0, 450, 13000, 1, 0, 1, '01A', 1, 1, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), + (2, 0, 0, 450, 13000, 1, 0, 1, '01A', 1, 1, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), (3, 1400, 0, 450, 13000, 1, 0, 1, '01B', 1, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), (4, 0, 500, 500, 13000, 1, 4, 1, '02A', 2, 1, NULL, NULL, NULL, NULL, 1, 4, 13, NULL), (5, 1400, 500, 500, 13000, 1, 4, 1, '02B', 2, 1, NULL, NULL, NULL, NULL, 1, 4, 13, NULL), @@ -4021,11 +4024,12 @@ INSERT INTO srt.buffer (id, x, y, `size`, `length`, stateFk, typeFk, isActive, c (9, 1400, 1500, 500, 13000, 1, 1, 1, '04B', 4, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL), (10, 0, 2000, 500, 13000, 1, 1, 1, '05A', 5, 0, NULL, NULL, NULL, NULL, 0, 1, 1, NULL); +INSERT IGNORE INTO vn.saySimpleCountry (countryFk, channel) + VALUES (19, '1169'), + (8, '1183'); -INSERT IGNORE INTO vn.saySimpleCountry (countryFk, channel) - VALUES (19, 1169), - (8, 1183), - (NULL, 1320); +INSERT IGNORE INTO vn.saySimpleConfig (url, defaultChannel) + VALUES ('saysimle-url-mock', 1320); -INSERT IGNORE INTO vn.saySimpleConfig (url) - VALUES ('saysimle-url-mock'); \ No newline at end of file +INSERT INTO vn.workerIrpf (workerFk,spouseNif, geographicMobilityDate) + VALUES (1106,'26493101E','2019-09-20'); diff --git a/db/routines/account/views/myUser.sql b/db/routines/account/views/myUser.sql index f520d893b..8d927dc0f 100644 --- a/db/routines/account/views/myUser.sql +++ b/db/routines/account/views/myUser.sql @@ -7,8 +7,7 @@ AS SELECT `u`.`id` AS `id`, `u`.`email` AS `email`, `u`.`nickname` AS `nickname`, `u`.`lang` AS `lang`, - `u`.`role` AS `role`, - `u`.`recoverPass` AS `recoverPass` + `u`.`role` AS `role` FROM `account`.`user` `u` WHERE `u`.`name` = `myUser_getName`() WITH CASCADED CHECK OPTION diff --git a/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql b/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql index 863005373..b698f0e3e 100644 --- a/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql +++ b/db/routines/bs/procedures/inventoryDiscrepancyDetail_replace.sql @@ -32,7 +32,7 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tVisible SELECT itemFk, SUM(visible) totalVisible FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector sc ON sc.id = p.sectorFk WHERE sc.warehouseFk = vWarehouseFk diff --git a/db/routines/cache/procedures/availableNoRaids_refresh.sql b/db/routines/cache/procedures/availableNoRaids_refresh.sql index efbbf6a13..447300305 100644 --- a/db/routines/cache/procedures/availableNoRaids_refresh.sql +++ b/db/routines/cache/procedures/availableNoRaids_refresh.sql @@ -53,7 +53,7 @@ proc: BEGIN WHERE t.landed BETWEEN vInventoryDate AND vStartDate AND t.warehouseInFk = vWarehouse AND s.name != 'INVENTARIO' - AND NOT t.daysInForward + AND NOT t.isRaid GROUP BY b.itemFk ) c JOIN vn.item i ON i.id = c.itemFk diff --git a/db/routines/edi/triggers/supplyResponse_afterUpdate.sql b/db/routines/edi/triggers/supplyResponse_afterUpdate.sql index 28a8c9466..f3e5aaefd 100644 --- a/db/routines/edi/triggers/supplyResponse_afterUpdate.sql +++ b/db/routines/edi/triggers/supplyResponse_afterUpdate.sql @@ -14,7 +14,7 @@ BEGIN b.stickers = NEW.NumberOfUnits WHERE i.supplyResponseFk = NEW.ID AND am.name = 'LOGIFLORA' - AND tr.daysInForward + AND tr.isRaid AND tr.landed >= util.VN_CURDATE(); END$$ diff --git a/db/routines/hedera/procedures/item_getVisible.sql b/db/routines/hedera/procedures/item_getVisible.sql index 365161bdf..d5bbe9d76 100644 --- a/db/routines/hedera/procedures/item_getVisible.sql +++ b/db/routines/hedera/procedures/item_getVisible.sql @@ -59,7 +59,7 @@ BEGIN JOIN vn.travel t ON t.id = e.travelFk WHERE t.landed BETWEEN vDateInv AND vDate AND t.warehouseInFk = vWarehouse - AND NOT t.daysInForward + AND NOT t.isRaid UNION ALL SELECT b.itemFk, -b.quantity FROM vn.buy b @@ -67,7 +67,7 @@ BEGIN JOIN vn.travel t ON t.id = e.travelFk WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() AND t.warehouseOutFk = vWarehouse - AND NOT t.daysInForward + AND NOT t.isRaid AND t.isDelivered UNION ALL SELECT m.itemFk, -m.quantity diff --git a/db/routines/stock/procedures/log_refreshBuy.sql b/db/routines/stock/procedures/log_refreshBuy.sql index d8e727f17..874e14072 100644 --- a/db/routines/stock/procedures/log_refreshBuy.sql +++ b/db/routines/stock/procedures/log_refreshBuy.sql @@ -6,12 +6,11 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tValues; CREATE TEMPORARY TABLE tValues ENGINE = MEMORY - SELECT - b.id buyFk, + SELECT b.id buyFk, e.id entryFk, t.id travelFk, b.itemFk, - t.daysInForward, + t.isRaid, ADDTIME(t.shipped, IFNULL(t.shipmentHour, '00:00:00')) shipped, t.warehouseOutFk, @@ -50,7 +49,7 @@ BEGIN itemFk, TIMESTAMPADD(DAY, life, @dated), quantity, - IF(isIn, isReceived, isDelivered) AND NOT daysInForward + IF(isIn, isReceived, isDelivered) AND NOT isRaid FROM tValues WHERE isIn OR !lessThanInventory; @@ -65,7 +64,7 @@ BEGIN itemFk, created, quantity, - IF(isIn, isDelivered, isReceived) AND NOT daysInForward + IF(isIn, isDelivered, isReceived) AND NOT isRaid FROM tValues WHERE !isIn OR !lessThanInventory; diff --git a/db/routines/vn/functions/address_getGeo.sql b/db/routines/vn/functions/address_getGeo.sql index 04155c30c..213eb91c3 100644 --- a/db/routines/vn/functions/address_getGeo.sql +++ b/db/routines/vn/functions/address_getGeo.sql @@ -14,9 +14,12 @@ BEGIN SELECT p.geoFk INTO vGeoFk FROM address a JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode + JOIN postCode p ON p.townFk = t.id + AND (p.code = a.postalCode OR a.postalCode IS NULL) + JOIN zoneGeo zg ON zg.id = p.geoFk WHERE a.id = vSelf - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + ORDER BY (a.city SOUNDS LIKE t.name) DESC, + (p.code = a.postalCode) DESC LIMIT 1; RETURN vGeoFk; diff --git a/db/routines/vn/functions/client_getGeo.sql b/db/routines/vn/functions/client_getGeo.sql new file mode 100644 index 000000000..9c2e3212e --- /dev/null +++ b/db/routines/vn/functions/client_getGeo.sql @@ -0,0 +1,27 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`client_getGeo`(vSelf INT) + RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Returns the geo for the passed client. + * + * @param vSelf The address id + * @return The geo id + */ + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM client c + JOIN town t ON t.provinceFk = c.provinceFk + JOIN postCode p ON p.townFk = t.id + AND (p.code = c.postcode OR c.postcode IS NULL) + JOIN zoneGeo zg ON zg.id = p.geoFk + WHERE c.id = vSelf + ORDER BY (c.city SOUNDS LIKE t.name) DESC, + (p.code = c.postcode) DESC + LIMIT 1; + + RETURN vGeoFk; +END$$ +DELIMITER ; diff --git a/db/routines/vn/functions/entry_getCommission.sql b/db/routines/vn/functions/entry_getCommission.sql index 4a19f4e63..a4afdabd4 100644 --- a/db/routines/vn/functions/entry_getCommission.sql +++ b/db/routines/vn/functions/entry_getCommission.sql @@ -1,58 +1,51 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`entry_getCommission`(vTravelFk INT, - vCurrencyFk INT, - vSupplierFk INT + vCurrencyFk INT, + vSupplierFk INT ) RETURNS int(11) NOT DETERMINISTIC READS SQL DATA BEGIN - DECLARE vCommission INT; - DECLARE vCurrentCommission INT; - DECLARE vIsCurrencyUsd INT; - DECLARE vLastEntryFk INT; - - SELECT count(*) INTO vIsCurrencyUsd - FROM currency c - WHERE c.code = 'USD' AND id = vCurrencyFk; - - IF NOT vIsCurrencyUsd THEN - - SELECT e.id INTO vLastEntryFk - FROM vn.entry e - JOIN vn.travel tr ON tr.id = e.travelFk - WHERE e.supplierFk = vSupplierFk - ORDER BY tr.landed DESC - LIMIT 1; - - IF vLastEntryFk THEN - - SELECT commission INTO vCurrentCommission - FROM vn.entry - WHERE id = vLastEntryFk; - - ELSE - - SELECT commission INTO vCurrentCommission - FROM supplier s - WHERE s.id = vSupplierFk; - - END IF; - - RETURN vCurrentCommission; - - ELSE + DECLARE vCommission INT; + DECLARE vCurrentCommission INT; + DECLARE vIsNotEUR INT; + DECLARE vLastEntryFk INT; + SELECT count(*) INTO vIsNotEUR + FROM currency c + WHERE c.code <> 'EUR' AND id = vCurrencyFk; + + IF vIsNotEUR THEN SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission FROM travel t LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped WHERE t.id = vTravelFk ORDER BY r.`dated` DESC LIMIT 1; - + RETURN IFNULL(vCommission, 0); - - END IF; - + ELSE + SELECT e.id INTO vLastEntryFk + FROM `entry` e + JOIN travel tr ON tr.id = e.travelFk + WHERE e.supplierFk = vSupplierFk + ORDER BY tr.landed DESC + LIMIT 1; + + IF vLastEntryFk THEN + SELECT commission INTO vCurrentCommission + FROM `entry` + WHERE id = vLastEntryFk; + + ELSE + SELECT commission INTO vCurrentCommission + FROM supplier s + WHERE s.id = vSupplierFk; + + END IF; + + RETURN vCurrentCommission; + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/functions/hasItemsInSector.sql b/db/routines/vn/functions/hasItemsInSector.sql index 7a5c4cf60..faf9e8a90 100644 --- a/db/routines/vn/functions/hasItemsInSector.sql +++ b/db/routines/vn/functions/hasItemsInSector.sql @@ -9,7 +9,7 @@ BEGIN SELECT count(*) INTO vItemCount FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; diff --git a/db/routines/vn/functions/itemsInSector_get.sql b/db/routines/vn/functions/itemsInSector_get.sql index 254ebe1b5..9043e55cb 100644 --- a/db/routines/vn/functions/itemsInSector_get.sql +++ b/db/routines/vn/functions/itemsInSector_get.sql @@ -10,7 +10,7 @@ BEGIN SELECT count(*) INTO vItemCount FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; diff --git a/db/routines/vn/functions/supplier_getGeo.sql b/db/routines/vn/functions/supplier_getGeo.sql new file mode 100644 index 000000000..86984272c --- /dev/null +++ b/db/routines/vn/functions/supplier_getGeo.sql @@ -0,0 +1,29 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`supplier_getGeo`(vSelf INT) + RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Returns the geo for the passed supplier. + * + * @param vSelf The address id + * @return The geo id + */ + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM supplier s + JOIN town t ON t.provinceFk = s.provinceFk + JOIN postCode p ON p.townFk = t.id + AND (p.code = s.postCode OR s.postCode IS NULL) + LEFT JOIN supplierAddress sad ON sad.supplierFk = s.id + JOIN zoneGeo zg ON zg.id = p.geoFk + WHERE s.id = vSelf + ORDER BY (s.city SOUNDS LIKE t.name) DESC, + (p.code = s.postCode) DESC, + (p.code = sad.postalCode) DESC + LIMIT 1; + + RETURN vGeoFk; +END$$ +DELIMITER ; diff --git a/db/routines/vn/functions/timeWorkerControl_getDirection.sql b/db/routines/vn/functions/timeWorkerControl_getDirection.sql deleted file mode 100644 index c0f1e67ea..000000000 --- a/db/routines/vn/functions/timeWorkerControl_getDirection.sql +++ /dev/null @@ -1,65 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` FUNCTION `vn`.`timeWorkerControl_getDirection`(vUserFk INT, vTimed DATETIME) - RETURNS varchar(6) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci - NOT DETERMINISTIC - READS SQL DATA -BEGIN -/** - * Verifica la dirección de la fichada - * @param vUserFk Identificador del trabajador - * @param vTimed Hora de la fichada - * @return Retorna sentido de la fichada 'in, out, middle' - */ - - DECLARE vPrevious DATETIME ; - DECLARE vNext DATETIME ; - DECLARE vPreviousDirection VARCHAR(3) ; - DECLARE vNextDirection VARCHAR(3) ; - DECLARE vDayStayMax INT; - DECLARE vTimedSeconds INT; - DECLARE vLastTimeIn INT; - - SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds; - - SELECT dayStayMax INTO vDayStayMax - FROM vn.workerTimeControlParams; - - SELECT timed, direction INTO vNext,vNextDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk - AND direction IN ('in','out') - AND timed > vTimed - ORDER BY timed ASC - LIMIT 1; - - SELECT timed, direction INTO vPrevious, vPreviousDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk - AND direction IN ('in','out') - AND timed < vTimed - ORDER BY timed DESC - LIMIT 1; - - IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN - RETURN 'middle'; - END IF; - - - IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN - IF vPreviousDirection = 'in' THEN - RETURN 'out'; - ELSE - SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn - FROM vn.workerTimeControl - WHERE userFk = vUserFk - AND direction ='in' - AND timed < vPrevious; - IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN - RETURN 'out'; - END IF; - END IF; - END IF; - - RETURN 'in'; -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/absoluteInventoryHistory.sql b/db/routines/vn/procedures/absoluteInventoryHistory.sql index 3ea8cf4de..d0d9ffac2 100644 --- a/db/routines/vn/procedures/absoluteInventoryHistory.sql +++ b/db/routines/vn/procedures/absoluteInventoryHistory.sql @@ -39,7 +39,7 @@ BEGIN AND vWarehouseFk IN (tr.warehouseInFk, 0) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable - AND NOT tr.daysInForward + AND NOT tr.isRaid UNION ALL SELECT tr.shipped, NULL, @@ -58,7 +58,7 @@ BEGIN AND s.id <> (SELECT supplierFk FROM inventoryConfig) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable - AND NOT tr.daysInForward + AND NOT tr.isRaid UNION ALL SELECT t.shipped, NULL, diff --git a/db/routines/vn/procedures/available_traslate.sql b/db/routines/vn/procedures/available_traslate.sql index 513f58e36..bfd5b34c8 100644 --- a/db/routines/vn/procedures/available_traslate.sql +++ b/db/routines/vn/procedures/available_traslate.sql @@ -42,7 +42,7 @@ proc: BEGIN WHERE t.landed BETWEEN vDatedInventory AND vDatedFrom AND t.warehouseInFk = vWarehouseLanding AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid GROUP BY c.itemFk; -- Tabla con el ultimo dia de last_buy para cada producto @@ -57,7 +57,7 @@ proc: BEGIN JOIN travel tr ON tr.id = e.travelFk LEFT JOIN tItemRange i ON t.itemFk = i.itemFk WHERE t.warehouseFk = vWarehouseShipment - AND NOT tr.daysInForward + AND NOT tr.isRaid ON DUPLICATE KEY UPDATE tItemRange.dated = GREATEST(tItemRange.dated, tr.landed); @@ -94,7 +94,7 @@ proc: BEGIN JOIN tItemRangeLive ir ON ir.itemFk = b.itemFk WHERE NOT e.isExcludedFromAvailable AND b.quantity <> 0 - AND NOT t.daysInForward + AND NOT t.isRaid AND t.warehouseInFk = vWarehouseLanding AND t.landed >= vDatedFrom AND (ir.dated IS NULL OR t.landed <= ir.dated) diff --git a/db/routines/vn/procedures/collectionPlacement_get.sql b/db/routines/vn/procedures/collectionPlacement_get.sql index 239dbd3a2..8d2301e1e 100644 --- a/db/routines/vn/procedures/collectionPlacement_get.sql +++ b/db/routines/vn/procedures/collectionPlacement_get.sql @@ -83,7 +83,7 @@ BEGIN AND s.semaphore = 1 GROUP BY st.saleFk) st ON st.saleFk = ts.saleFk JOIN itemShelving ish ON ish.itemFk = ts.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector sc ON sc.id = p.sectorFk JOIN sectorType st ON st.id = sc.typeFk diff --git a/db/routines/vn/procedures/entry_getTransfer.sql b/db/routines/vn/procedures/entry_getTransfer.sql index 9527e0bf2..873827db2 100644 --- a/db/routines/vn/procedures/entry_getTransfer.sql +++ b/db/routines/vn/procedures/entry_getTransfer.sql @@ -166,7 +166,7 @@ BEGIN LEFT JOIN tmp.buyUltimateFromInterval bufi ON bufi.itemFk = i.id LEFT JOIN buy b3 ON b3.id = bufi.buyFk WHERE ic.display - AND NOT tr.daysInForward + AND NOT tr.isRaid AND (ti.visible OR ti.available) ORDER BY i.typeFk, i.name, i.id, i.size, i.category, o.name; diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql index 12b6d0ef6..c417f6789 100644 --- a/db/routines/vn/procedures/entry_isEditable.sql +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -9,16 +9,18 @@ BEGIN * * @param vSelf Id de entrada */ - DECLARE vIsEditable BOOL; + DECLARE vIsNotEditable BOOL DEFAULT FALSE; - SELECT e.isBooked INTO vIsEditable + SELECT TRUE INTO vIsNotEditable FROM `entry` e - JOIN entryType et ON et.code = e.typeFk - WHERE NOT et.isInformal - AND e.id = vSelf; + LEFT JOIN entryType et ON et.code = e.typeFk + WHERE e.id = vSelf + AND e.isBooked + AND (e.typeFk IS NULL OR NOT et.isInformal); - IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN + IF vIsNotEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN CALL util.throw(CONCAT('Entry ', vSelf, ' is not editable')); END IF; + END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index fbf0cef90..3201900e6 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -1,10 +1,15 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`entry_splitByShelving`(vShelvingFk VARCHAR(3), vFromEntryFk INT, vToEntryFk INT) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`entry_splitByShelving`( + vShelvingCode VARCHAR(10), + vFromEntryFk INT, + vToEntryFk INT +) BEGIN /** - * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula + * Divide las compras entre dos entradas de + * acuerdo con lo ubicado en una matricula. * - * @param vShelvingFk Identificador de vn.shelving + * @param vShelvingCode Código de vn.shelving * @param vFromEntryFk Entrada origen * @param vToEntryFk Entrada destino */ @@ -14,7 +19,7 @@ BEGIN DECLARE vDone BOOLEAN DEFAULT FALSE; DECLARE cur CURSOR FOR - SELECT bb.id buyFk, + SELECT bb.id buyFk, LEAST(bb.stickers, FLOOR(ish.visible / ish.packing)) ishStickers, bb.stickers buyStickers FROM itemShelving ish @@ -23,7 +28,7 @@ BEGIN WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + WHERE ish.shelvingFk = vShelvingCode COLLATE utf8_general_ci AND NOT ish.isSplit GROUP BY ish.id; @@ -107,9 +112,10 @@ BEGIN UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); END IF; - UPDATE itemShelving - SET isSplit = TRUE - WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci; + UPDATE itemShelving ish + JOIN shelving sh ON sh.id = ish.shelvingFk + SET ish.isSplit = TRUE + WHERE sh.code = vShelvingCode COLLATE utf8_general_ci; END LOOP; CLOSE cur; END$$ diff --git a/db/routines/vn/procedures/entry_updateComission.sql b/db/routines/vn/procedures/entry_updateComission.sql index e2de2a4a5..8db28f97d 100644 --- a/db/routines/vn/procedures/entry_updateComission.sql +++ b/db/routines/vn/procedures/entry_updateComission.sql @@ -22,7 +22,7 @@ BEGIN FROM vn.entry e JOIN vn.travel t ON t.id = e.travelFk JOIN vn.warehouse w ON w.id = t.warehouseInFk - WHERE t.shipped >= util.VN_CURDATE() + WHERE t.landed >= util.VN_CURDATE() AND e.currencyFk = vCurrency AND NOT e.isBooked; @@ -33,7 +33,7 @@ BEGIN SET e.commission = vComission; SELECT `name` INTO vCurrencyName - FROM currency + FROM currency WHERE id = vCurrency; CALL entry_recalc(); diff --git a/db/routines/vn/procedures/expeditionScan_Put.sql b/db/routines/vn/procedures/expeditionScan_Put.sql index fc7d4da23..999b9af10 100644 --- a/db/routines/vn/procedures/expeditionScan_Put.sql +++ b/db/routines/vn/procedures/expeditionScan_Put.sql @@ -4,12 +4,12 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`expeditionScan_Put`( vExpeditionFk INT ) BEGIN - IF NOT (SELECT TRUE FROM expedition WHERE id = vExpeditionFk LIMIT 1) THEN - CALL util.throw('Expedition not exists'); + IF NOT EXISTS (SELECT id FROM expeditionPallet WHERE id = vPalletFk) THEN + CALL util.throw('Pallet not exists'); END IF; - IF NOT (SELECT TRUE FROM expeditionPallet WHERE id = vPalletFk LIMIT 1) THEN - CALL util.throw('Pallet not exists'); + IF NOT EXISTS (SELECT id FROM expedition WHERE id = vExpeditionFk) THEN + CALL util.throw('Expedition not exists'); END IF; REPLACE expeditionScan(expeditionFk, palletFk) diff --git a/db/routines/vn/procedures/inventoryMake.sql b/db/routines/vn/procedures/inventoryMake.sql index 65dceef3d..316083db0 100644 --- a/db/routines/vn/procedures/inventoryMake.sql +++ b/db/routines/vn/procedures/inventoryMake.sql @@ -137,7 +137,7 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk WHERE tr.warehouseInFk = vWarehouseFk AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday - AND NOT tr.daysInForward + AND NOT tr.isRaid GROUP BY b.itemFk; -- Transfers @@ -150,7 +150,7 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk WHERE tr.warehouseOutFk = vWarehouseFk AND tr.shipped BETWEEN vDateLastInventory AND vDateYesterday - AND NOT tr.daysInForward + AND NOT tr.isRaid GROUP BY b.itemFk ) sub ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut; diff --git a/db/routines/vn/procedures/itemPlacementSupplyAiming.sql b/db/routines/vn/procedures/itemPlacementSupplyAiming.sql index b96860623..ae0890564 100644 --- a/db/routines/vn/procedures/itemPlacementSupplyAiming.sql +++ b/db/routines/vn/procedures/itemPlacementSupplyAiming.sql @@ -1,5 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyAiming`(vShelvingFk VARCHAR(10), quantity INT, vItemFk INT) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyAiming`( + vShelvingCode VARCHAR(10), + vQuantity INT, + vItemFk INT +) BEGIN SELECT ish.itemFk, @@ -9,21 +13,21 @@ BEGIN ish.itemShelvingFk, ish.shelving, ish.stock, - LEAST(ish.stock,quantity) as total, + LEAST(ish.stock,vQuantity) total, CONCAT( - CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)), + CAST(FLOOR(LEAST(ish.stock, vQuantity) / ish.packing) AS DECIMAL(10,0)), ' x ', ish.packing, IF ( - LEAST(ish.stock,quantity) MOD ish.packing, - CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))), + LEAST(ish.stock, vQuantity) MOD ish.packing, + CONCAT(' + ',CAST(LEAST(ish.stock, vQuantity) MOD ish.packing AS DECIMAL(10,0))), '' ), ' = ', - LEAST(ish.stock,quantity) - ) as proposal - FROM vn.itemShelvingPlacementSupplyStock ish - WHERE ish.shelving = vShelvingFk COLLATE utf8_general_ci + LEAST(ish.stock, vQuantity) + ) proposal + FROM itemShelvingPlacementSupplyStock ish + WHERE ish.shelving = vShelvingCode COLLATE utf8_general_ci AND ish.itemFk = vItemFk; END$$ diff --git a/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql b/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql index 958dc7e78..d2648ca6c 100644 --- a/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql +++ b/db/routines/vn/procedures/itemPlacementSupplyGetOrder.sql @@ -1,5 +1,7 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyGetOrder`(vSector INT ) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyGetOrder`( + vSectorFk INT +) BEGIN DECLARE vId INT; @@ -7,31 +9,35 @@ BEGIN DECLARE vNextParkingFk INT; SELECT sh.parkingFk INTO vLastParkingFk - FROM vn.itemShelvingPlacementSupply isps - JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + FROM itemShelvingPlacementSupply isps + JOIN itemShelving ish ON ish.id = isps.itemShelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk WHERE isps.userFk = getUser() ORDER BY isps.created DESC LIMIT 1; - SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); + SET vNextParkingFk = itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); SELECT ipsl.id INTO vId - FROM vn.itemPlacementSupplyList ipsl - JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk + FROM itemPlacementSupplyList ipsl + JOIN itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk WHERE ipsl.saldo > 0 AND (ipsl.repoUserFk is NULL OR ipsl.repoUserFk = getUser()) - AND ipsl.sectorFk = vSector - ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created + AND ipsl.sectorFk = vSectorFk + ORDER BY ipsl.repoUserFk DESC, + ipsl.priority DESC, + (ispss.parkingFk = vNextParkingFk) DESC, + ispss.parking DESC, + ipsl.created LIMIT 1; - UPDATE vn.itemPlacementSupply + UPDATE itemPlacementSupply SET repoUserFk = getUser() WHERE id = vId; - SELECT * FROM vn.itemPlacementSupplyList + SELECT * FROM itemPlacementSupplyList WHERE id = vId - AND sectorFk = vSector; + AND sectorFk = vSectorFk; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql index cefa64d13..92c17b82f 100644 --- a/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql +++ b/db/routines/vn/procedures/itemPlacementSupplyStockGetTargetList.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyStockGetTargetList`(vItemFk INT,vSectorFk INT) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemPlacementSupplyStockGetTargetList`( + vItemFk INT, + vSectorFk INT +) BEGIN /** * Devuelve la lista de ubicaciones para itemFk en ese sector. Se utiliza en la preparación previa. @@ -13,11 +16,11 @@ BEGIN SUM(ish.visible) stockTotal, ish.created, p.pickingOrder - FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk - JOIN vn.parking p ON p.id = sh.parkingFk - JOIN vn.sector sc ON sc.id = p.sectorFk - JOIN vn.warehouse w ON w.id = sc.warehouseFk + FROM itemShelving ish + JOIN shelving sh ON sh.id = 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 WHERE ish.visible > 0 AND ish.itemFk = vItemFk GROUP BY ish.id diff --git a/db/routines/vn/procedures/itemShelvingLog_get.sql b/db/routines/vn/procedures/itemShelvingLog_get.sql index 52e7a273f..5a943e867 100644 --- a/db/routines/vn/procedures/itemShelvingLog_get.sql +++ b/db/routines/vn/procedures/itemShelvingLog_get.sql @@ -1,14 +1,14 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`(vShelvingFk VARCHAR(10) ) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingLog_get`( + vShelvingCode VARCHAR(10) +) BEGIN - /** * Devuelve el log de los item en cada carro * - * @param vShelvingFk Matrícula del carro + * @param vShelvingCode Matrícula del carro * */ - SELECT isl.itemShelvingFk, isl.created, isl.accion, @@ -28,8 +28,9 @@ BEGIN 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; - + JOIN shelving sh ON sh.id = isl.shelvingFk + WHERE sh.code = vShelvingCode COLLATE utf8mb3_unicode_ci + OR isl.itemFk = vShelvingCode -- ?? Respeto porque ya estaba + ORDER BY isl.created DESC; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingMatch.sql b/db/routines/vn/procedures/itemShelvingMatch.sql index 850c7907b..4ffa66fcb 100644 --- a/db/routines/vn/procedures/itemShelvingMatch.sql +++ b/db/routines/vn/procedures/itemShelvingMatch.sql @@ -20,7 +20,7 @@ BEGIN LEFT JOIN ( SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk LEFT JOIN parking pk ON pk.id = sh.parkingFk WHERE ish.created BETWEEN vFromTimed AND vToTimed GROUP BY itemFk diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql index 06736732a..eeec60248 100644 --- a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql +++ b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql @@ -27,7 +27,7 @@ proc: BEGIN ish.available FROM sale s JOIN itemShelving ish ON ish.itemFk = s.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector sc ON sc.id = p.sectorFk JOIN productionConfig pc @@ -61,7 +61,7 @@ proc: BEGIN 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 shelving sh ON sh.id = ish.shelvingFk LEFT JOIN parking p ON p.id = sh.parkingFk WHERE s.id = vSaleFk; diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index cde1b6872..1975180d1 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -3,7 +3,8 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setQ vItemShelvingSaleFk INT(10), vQuantity DECIMAL(10,0), vIsItemShelvingSaleEmpty BOOLEAN, - vSectorFk INT + vSectorFk INT, + vShelvingFk VARCHAR(10) ) BEGIN /** @@ -24,6 +25,7 @@ BEGIN DECLARE vItemFk INT; DECLARE vTotalQuantity INT; DECLARE vStateCode VARCHAR(45); + DECLARE vCurrentShelvingFk VARCHAR(10); DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN @@ -45,18 +47,26 @@ BEGIN iss.saleFk, iss.itemShelvingFk, SUM(IFNULL(iss.quantity,0)), - IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED') + IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED'), + sh.code INTO vItemFk, vSaleFk, vItemShelvingFk, vReservedQuantity, - vStateCode + vStateCode, + vCurrentShelvingFk FROM itemShelvingSale iss JOIN sale s ON s.id = iss.saleFk - LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = iss.saleFk + LEFT JOIN shelving sh ON sh.id = ish.shelvingFk WHERE iss.id = vItemShelvingSaleFk AND NOT iss.isPicked; + IF NOT (vCurrentShelvingFk <=> vShelvingFk) THEN + CALL util.throw('The shelving can not be different from the shelving reserved'); + END IF; + IF vQuantity > vReservedQuantity OR (vQuantity < vReservedQuantity AND NOT vIsItemShelvingSaleEmpty) OR (vQuantity = vReservedQuantity AND vIsItemShelvingSaleEmpty) THEN diff --git a/db/routines/vn/procedures/itemShelving_add.sql b/db/routines/vn/procedures/itemShelving_add.sql index 92d1609e4..a8f0b5250 100644 --- a/db/routines/vn/procedures/itemShelving_add.sql +++ b/db/routines/vn/procedures/itemShelving_add.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_add`( - vShelvingFk VARCHAR(8), + vShelvingCode VARCHAR(10), vBarcode VARCHAR(22), vQuantity INT, vPackagingFk VARCHAR(10), @@ -12,7 +12,7 @@ BEGIN /** * Añade registro o lo actualiza si ya existe. * - * @param vShelvingFk matrícula del carro + * @param vShelvingCode 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 @@ -23,10 +23,15 @@ BEGIN **/ DECLARE vItemFk INT; DECLARE vBuyFk INT; + DECLARE vShelvingFk INT; SELECT id INTO vBuyFk FROM buy WHERE id = vBarcode; + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; + SELECT barcodeToItem(vBarcode) INTO vItemFk; IF vBuyFk IS NULL THEN @@ -40,7 +45,7 @@ BEGIN END IF; IF (SELECT COUNT(*) FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + WHERE shelvingFk = vShelvingFk AND itemFk = vItemFk AND packing = vPacking AND buyFk = vBuyFk) THEN @@ -48,7 +53,9 @@ BEGIN UPDATE itemShelving SET visible = visible + vQuantity, available = available + vQuantity - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + WHERE shelvingFk = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking; ELSE diff --git a/db/routines/vn/procedures/itemShelving_addByClaim.sql b/db/routines/vn/procedures/itemShelving_addByClaim.sql index 5e7cdf3fc..55ac3e337 100644 --- a/db/routines/vn/procedures/itemShelving_addByClaim.sql +++ b/db/routines/vn/procedures/itemShelving_addByClaim.sql @@ -1,29 +1,38 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addByClaim`(vClaimFk INT, vShelvingFk VARCHAR(3)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addByClaim`( + vClaimFk INT, + vShelvingCode VARCHAR(10) +) BEGIN /** * Insert items of claim into itemShelving. * * @param vClaimFk The claim - * @param vShelvingFk The shelving + * @param vShelvingCode The shelving code * @table tmp.buyUltimate */ DECLARE vWarehouseFk INT; + DECLARE vShelvingFk INT; SELECT t.warehouseFk INTO vWarehouseFk FROM claim c JOIN ticket t ON t.id = c.ticketFk WHERE c.id = vClaimFk; + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; + CALL buy_getUltimate(NULL, vWarehouseFk, util.VN_CURDATE()); INSERT INTO itemShelving (itemFk, shelvingFk, packing, `grouping`, visible) - SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity AS visible + SELECT s.itemFk, vShelvingFk, b.packing, b.`grouping`, cb.quantity visible FROM claim c JOIN claimBeginning cb ON c.id = cb.claimFk JOIN sale s ON s.id = cb.saleFk JOIN ticket t ON t.id = s.ticketFk - JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk AND bu.warehouseFk = t.warehouseFk + JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + AND bu.warehouseFk = t.warehouseFk JOIN buy b ON b.id = bu.buyFk WHERE c.id = vClaimFk; END$$ diff --git a/db/routines/vn/procedures/itemShelving_addList.sql b/db/routines/vn/procedures/itemShelving_addList.sql index ade92b9fd..04fa1e10c 100644 --- a/db/routines/vn/procedures/itemShelving_addList.sql +++ b/db/routines/vn/procedures/itemShelving_addList.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_addList`( - vShelvingFk VARCHAR(3), + vShelvingCode VARCHAR(10), vList TEXT, vIsChecking BOOL, vWarehouseFk INT @@ -13,7 +13,7 @@ BEGIN * Cuando es TRUE sólo inserta los elementos de la colección que no están ya en * ese shelving, actualizando los valores del campo itemShelving.isChecked * - * @param vShelvingFk Identificador de shelving + * @param vShelvingCode Código de shelving * @param vList JSON array con esta estructura: '[value1, value2, ...]' * @param vIsChecking Define si hay que añadir o comprobar los items * @param vWarehouseFk Identificador de warehouse @@ -24,6 +24,11 @@ BEGIN DECLARE vPath VARCHAR(6); DECLARE vItemFk INT; DECLARE vIsChecked BOOL; + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; WHILE vCounter < vListLength DO SET vPath = CONCAT('$[', vCounter, ']'); @@ -34,17 +39,17 @@ BEGIN SELECT IF(COUNT(*), TRUE, FALSE) INTO vIsChecked FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + WHERE shelvingFk = vShelvingFk AND itemFk = vItemFk; END IF; IF NOT vIsChecking OR NOT vIsChecked THEN - CALL itemShelving_add(vShelvingFk, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); + CALL itemShelving_add(vShelvingCode, vBarcode, 1, NULL, NULL, NULL, vWarehouseFk); END IF; UPDATE itemShelving SET isChecked = vIsChecked - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + WHERE shelvingFk = vShelvingFk AND itemFk = vItemFk AND isChecked IS NULL; diff --git a/db/routines/vn/procedures/itemShelving_get.sql b/db/routines/vn/procedures/itemShelving_get.sql index 07384b721..0038257c2 100644 --- a/db/routines/vn/procedures/itemShelving_get.sql +++ b/db/routines/vn/procedures/itemShelving_get.sql @@ -1,10 +1,12 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_get`(IN vSelf VARCHAR(8)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_get`( + vShelvingCode VARCHAR(10) +) BEGIN /** -* Lista artículos de itemshelving +* Lista artículos de itemShelving. * -* @param vSelf matrícula del carro +* @param vShelvingCode Matrícula del carro **/ SELECT ish.itemFk item, i.name, @@ -19,12 +21,13 @@ BEGIN ish.isChecked, ic.url, ish.available, - ish.buyFk + ish.buyFk, + ish.shelvingFk FROM itemShelving ish JOIN item i ON i.id = ish.itemFk - JOIN shelving s ON vSelf = s.code COLLATE utf8_unicode_ci - LEFT JOIN parking p ON s.parkingFk = p.id + JOIN shelving s ON s.id = ish.shelvingFk + LEFT JOIN parking p ON p.id = s.parkingFk JOIN hedera.imageConfig ic - WHERE ish.shelvingFk COLLATE utf8_unicode_ci = vSelf; + WHERE s.code COLLATE utf8_unicode_ci = vShelvingCode; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelving_getAlternatives.sql b/db/routines/vn/procedures/itemShelving_getAlternatives.sql index 89176c4f5..3eff3254b 100644 --- a/db/routines/vn/procedures/itemShelving_getAlternatives.sql +++ b/db/routines/vn/procedures/itemShelving_getAlternatives.sql @@ -1,21 +1,31 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getAlternatives`(vShelvingFk VARCHAR(10)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getAlternatives`( + vShelvingCode VARCHAR(10) +) BEGIN /** - * Devuelve un listado de posibles ubicaciones alternativas a ubicar los item de la matricula - * del carro que se le ha pasado. + * Devuelve un listado de posibles ubicaciones alternativas a ubicar + * los item de la matricula del carro que se le ha pasado. * - * @param vShelvingFk matricula del carro + * @param vShelvingCode Matricula del carro */ - SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; + + SELECT is2.id,is2.shelvingFk, p.code, is2.itemFk , is2.visible, p.pickingOrder FROM itemShelving is2 - JOIN shelving sh ON sh.code = is2.shelvingFk + JOIN shelving sh ON sh.id = is2.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk - LEFT JOIN operator o ON o.sectorFk = s.id AND o.workerFk = account.myUser_getId() + LEFT JOIN operator o ON o.sectorFk = s.id + AND o.workerFk = account.myUser_getId() JOIN warehouse wh ON wh.id = s.warehouseFk - JOIN itemShelving is3 ON is3.itemFk = is2.itemFk AND is3.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - WHERE is2.shelvingFk <> vShelvingFk COLLATE utf8_unicode_ci + JOIN itemShelving is3 ON is3.itemFk = is2.itemFk + AND is3.shelvingFk = vShelvingFk + WHERE is2.shelvingFk <> vShelvingFk GROUP BY is2.id ORDER BY p.pickingOrder DESC; END$$ diff --git a/db/routines/vn/procedures/itemShelving_getInfo.sql b/db/routines/vn/procedures/itemShelving_getInfo.sql index f02100e8b..f4c8c5b35 100644 --- a/db/routines/vn/procedures/itemShelving_getInfo.sql +++ b/db/routines/vn/procedures/itemShelving_getInfo.sql @@ -16,7 +16,7 @@ BEGIN ish.itemFk itemFk, sh.priority FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.`code` = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking pk ON pk.id = sh.parkingFk WHERE ish.itemFk = vItemFk ORDER BY sh.priority DESC, created ASC; diff --git a/db/routines/vn/procedures/itemShelving_getItemDetails.sql b/db/routines/vn/procedures/itemShelving_getItemDetails.sql index 4e641ca72..36f9830f0 100644 --- a/db/routines/vn/procedures/itemShelving_getItemDetails.sql +++ b/db/routines/vn/procedures/itemShelving_getItemDetails.sql @@ -1,14 +1,14 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getItemDetails`( vBarcodeItem INT, - vShelvingFK VARCHAR(10) + vShelvingCode VARCHAR(10) ) BEGIN /** * Obtiene el precio y visible de un item * * @param vBarcodeItem barcode de artículo - * @param vShelvingFK Ubicación actual del artículo + * @param vShelvingCode Ubicación actual del artículo */ DECLARE vIsItem BOOL; DECLARE vBuyFk INT; @@ -38,18 +38,19 @@ BEGIN WITH visible AS( SELECT itemFk, IFNULL(buyingValue, 0) + - IFNULL(freightValue, 0) + - IFNULL(comissionValue, 0) + - IFNULL(packageValue, 0) itemCost - FROM vn.buy b + IFNULL(freightValue, 0) + + IFNULL(comissionValue, 0) + + IFNULL(packageValue, 0) itemCost + FROM vn.buy b WHERE b.id = vBuyFk ) SELECT v.itemFk, - vShelvingFK, + vShelvingCode, v.itemCost, SUM(ish.visible) visible FROM vn.itemShelving ish + JOIN vn.shelving sh ON sh.id = ish.shelvingFK JOIN visible v - WHERE ish.shelvingFK = vShelvingFK COLLATE utf8mb3_general_ci - AND ish.itemFk = v.itemFk; + WHERE sh.code = vShelvingCode COLLATE utf8mb3_general_ci + AND ish.itemFk = v.itemFk; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelving_getSaleDate.sql b/db/routines/vn/procedures/itemShelving_getSaleDate.sql index d8ab6ed0c..fad4d5abc 100644 --- a/db/routines/vn/procedures/itemShelving_getSaleDate.sql +++ b/db/routines/vn/procedures/itemShelving_getSaleDate.sql @@ -1,14 +1,20 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_getSaleDate`( + vShelvingCode VARCHAR(10) +) BEGIN - - /* Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. - * - * @param vShelvingFk Matrícula del carro o pallet - */ - +/** + * Devuelve la mínima fecha en que se necesita cada producto en esa matrícula. + * + * @param vShelvingCode Matrícula del carro o pallet + */ DECLARE vWarehouseFk INT; DECLARE vStockScopeDays INT; + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; SELECT s.warehouseFk, stockScopeDays INTO vWarehouseFk, vStockScopeDays @@ -30,7 +36,7 @@ BEGIN ENGINE = MEMORY SELECT itemFk, SUM(visible) visible FROM itemShelving - WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci + WHERE shelvingFk = vShelvingFk GROUP BY itemFk; CREATE OR REPLACE TEMPORARY TABLE tmp.tStockByDay @@ -52,7 +58,7 @@ BEGIN 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 shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON sh.parkingFk = p.id JOIN sector s ON s.id = p.sectorFk WHERE s.isReserve @@ -110,7 +116,7 @@ BEGIN UPDATE tmp.tStockByDay sbd JOIN (SELECT ish.itemFK, SUM(ish.visible) amount FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk WHERE s.warehouseFk = vWarehouseFk @@ -150,10 +156,10 @@ BEGIN p.sectorFk, ish.shelvingFk FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = 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 + WHERE ish.shelvingFk = vShelvingFk ) sub4 ON sub4.itemFk = ts.itemFk LEFT JOIN sector s ON s.id = sub4.sectorFk LEFT JOIN item i ON i.id = ts.itemFk diff --git a/db/routines/vn/procedures/itemShelving_inventory.sql b/db/routines/vn/procedures/itemShelving_inventory.sql index b57df02e0..9ae96c7a8 100644 --- a/db/routines/vn/procedures/itemShelving_inventory.sql +++ b/db/routines/vn/procedures/itemShelving_inventory.sql @@ -42,7 +42,7 @@ BEGIN JOIN item i ON i.id = ish.itemFk JOIN itemType it ON it.id = i.typeFk JOIN tmp.stockMisfit sm ON sm.itemFk = ish.itemFk - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk LEFT JOIN ( SELECT s.itemFk, sum(s.quantity) notPrepared diff --git a/db/routines/vn/procedures/itemShelving_selfConsumption.sql b/db/routines/vn/procedures/itemShelving_selfConsumption.sql index 083d8d74c..5820b9d28 100644 --- a/db/routines/vn/procedures/itemShelving_selfConsumption.sql +++ b/db/routines/vn/procedures/itemShelving_selfConsumption.sql @@ -1,6 +1,6 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_selfConsumption`( - vShelvingFk VARCHAR(10) COLLATE utf8_general_ci, + vShelvingCode VARCHAR(10) COLLATE utf8_general_ci, vItemFk INT, vQuantity INT ) @@ -9,9 +9,9 @@ BEGIN * Leave the indicated amount on the shelve * and create a ticket with the difference. * - * @param vShelvingFk id of the shelve where the item is located. - * @param vItemFk article of which the self-consumption ticket is to be created. - * @param vQuantity amount that will stay on the shelve + * @param vShelvingCode Code of the shelve where the item is located + * @param vItemFk Item of which the self-consumption ticket is to be created + * @param vQuantity Amount that will stay on the shelve */ DECLARE vVisible INT; DECLARE vClientFk INT; @@ -21,6 +21,11 @@ BEGIN DECLARE vAgencyModeFk INT; DECLARE vItemShelvingFk INT; DECLARE vAddressFk INT; + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code = vShelvingCode; SELECT c.id, pc.clientSelfConsumptionFk, @@ -37,7 +42,7 @@ BEGIN JOIN parking p ON p.sectorFk = s.id JOIN shelving s2 ON s2.parkingFk = p.id JOIN productionConfig pc - WHERE s2.code = vShelvingFk; + WHERE s2.id = vShelvingFk; IF vClientFk IS NULL THEN CALL util.throw('The company does not have a customer assigned'); @@ -47,7 +52,7 @@ BEGIN CALL util.throw('The shelf cannot have NULL or negative quantities'); END IF; - IF vShelvingFk IS NULL THEN + IF vShelvingCode IS NULL THEN CALL util.throw('The shelf is necessary'); END IF; diff --git a/db/routines/vn/procedures/itemShelving_transfer.sql b/db/routines/vn/procedures/itemShelving_transfer.sql index 95d70227f..e0e6af110 100644 --- a/db/routines/vn/procedures/itemShelving_transfer.sql +++ b/db/routines/vn/procedures/itemShelving_transfer.sql @@ -1,7 +1,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`itemShelving_transfer`( vItemShelvingFk INT, - vShelvingFk VARCHAR(10) + vShelvingCode VARCHAR(10) ) BEGIN /** @@ -9,9 +9,14 @@ BEGIN * fusionando si coincide el packing y la fecha. * * @param vItemShelvingFk Identificador de itemShelving - * @param vShelvingFk Identificador de shelving + * @param vShelvingCode Código de shelving */ DECLARE vNewItemShelvingFk INT; + DECLARE vShelvingFk INT; + + SELECT id INTO vShelvingFk + FROM shelving + WHERE code COLLATE utf8_unicode_ci = vShelvingCode; SELECT MAX(ish.id) INTO vNewItemShelvingFk FROM itemShelving ish @@ -26,7 +31,7 @@ BEGIN 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; + WHERE ish.shelvingFk = vShelvingFk; IF vNewItemShelvingFk THEN UPDATE itemShelving ish @@ -38,9 +43,7 @@ BEGIN DELETE FROM itemShelving WHERE id = vItemShelvingFk; ELSE - IF (SELECT EXISTS(SELECT id FROM shelving - WHERE code = vShelvingFk COLLATE utf8_unicode_ci)) THEN - + IF (SELECT EXISTS(SELECT id FROM shelving WHERE id = vShelvingFk)) THEN UPDATE itemShelving SET shelvingFk = vShelvingFk WHERE id = vItemShelvingFk; diff --git a/db/routines/vn/procedures/item_devalueA2.sql b/db/routines/vn/procedures/item_devalueA2.sql index d0178f6a7..3264165a6 100644 --- a/db/routines/vn/procedures/item_devalueA2.sql +++ b/db/routines/vn/procedures/item_devalueA2.sql @@ -1,7 +1,7 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`item_devalueA2`( vSelf INT, - vShelvingFK VARCHAR(10), + vShelvingCode VARCHAR(10) COLLATE utf8mb3_general_ci, vBuyingValue DECIMAL(10,4), vQuantity INT ) @@ -12,7 +12,7 @@ BEGIN * de almacén y shelvings correspondientes * * @param vSelf Id de artículo a devaluar - * @param vShelvingFK Ubicación actual del artículo + * @param vShelvingCode Código de shelving / ubicación * @param vBuyingValue Nuevo precio de coste * @param vQuantity Cantidad del ítem a pasar a A2 */ @@ -109,10 +109,11 @@ BEGIN CALL util.throw ('The item has not a buy'); END IF; - SELECT id,visible INTO vTargetItemShelvingFk, vCurrentVisible - FROM itemShelving - WHERE shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci - AND itemFk = vSelf + SELECT ish.id, ish.visible INTO vTargetItemShelvingFk, vCurrentVisible + FROM itemShelving ish + JOIN shelving sh ON sh.id = ish.shelvingFk + WHERE sh.code = vShelvingCode + AND ish.itemFk = vSelf LIMIT 1; IF vCurrentVisible IS NULL THEN @@ -388,16 +389,17 @@ BEGIN userFk, isChecked) SELECT vItemA2Fk, - shelvingFk, + ish.shelvingFk, vQuantity , - `grouping`, - packing, - packagingFk, + ish.`grouping`, + ish.packing, + ish.packagingFk, account.myUser_getId(), - isChecked - FROM itemShelving - WHERE itemFK = vSelf - AND shelvingFk = vShelvingFK COLLATE utf8mb3_general_ci + ish.isChecked + FROM itemShelving ish + JOIN shelving sh ON sh.id = ish.shelvingFk + WHERE ish.itemFK = vSelf + AND sh.code = vShelvingCode ON DUPLICATE KEY UPDATE visible = vQuantity + VALUES(visible); diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql index 260f0a527..c4974491c 100644 --- a/db/routines/vn/procedures/item_getBalance.sql +++ b/db/routines/vn/procedures/item_getBalance.sql @@ -59,7 +59,7 @@ BEGIN AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable - AND NOT tr.daysInForward + AND NOT tr.isRaid ), entriesOut AS ( SELECT 'entry', @@ -95,7 +95,7 @@ BEGIN AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT w.isFeedStock - AND NOT tr.daysInForward + AND NOT tr.isRaid ), sales AS ( WITH itemSales AS ( diff --git a/db/routines/vn/procedures/item_getMinacum.sql b/db/routines/vn/procedures/item_getMinacum.sql index 8a42bd737..e3c915820 100644 --- a/db/routines/vn/procedures/item_getMinacum.sql +++ b/db/routines/vn/procedures/item_getMinacum.sql @@ -63,7 +63,7 @@ BEGIN AND NOT e.isExcludedFromAvailable AND b.quantity <> 0 AND (vItemFk IS NULL OR b.itemFk = vItemFk) - AND NOT t.daysInForward + AND NOT t.isRaid UNION ALL SELECT r.itemFk, r.shipment, diff --git a/db/routines/vn/procedures/item_multipleBuyByDate.sql b/db/routines/vn/procedures/item_multipleBuyByDate.sql index 7bd809312..04d3f1855 100644 --- a/db/routines/vn/procedures/item_multipleBuyByDate.sql +++ b/db/routines/vn/procedures/item_multipleBuyByDate.sql @@ -30,7 +30,7 @@ BEGIN AND NOT s.name = 'INVENTARIO' AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND w.isComparative - AND NOT t.daysInForward + AND NOT t.isRaid GROUP BY i.id; UPDATE tmp.itemInventory y diff --git a/db/routines/vn/procedures/item_valuateInventory.sql b/db/routines/vn/procedures/item_valuateInventory.sql index b6d687960..7e420be27 100644 --- a/db/routines/vn/procedures/item_valuateInventory.sql +++ b/db/routines/vn/procedures/item_valuateInventory.sql @@ -109,7 +109,7 @@ BEGIN 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 tr.daysInForward + AND NOT tr.isRaid AND w.valuatedInventory AND t.isInventory AND e.supplierFk <> vInventorySupplierFk @@ -131,7 +131,7 @@ BEGIN JOIN itemCategory ic ON ic.id = t.categoryFk JOIN warehouse w ON w.id = tr.warehouseOutFk WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd - AND NOT tr.daysInForward + AND NOT tr.isRaid AND w.valuatedInventory AND t.isInventory AND (t.id = vItemTypeFk OR vItemTypeFk IS NULL) @@ -196,7 +196,7 @@ BEGIN 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 tr.daysInForward + AND NOT tr.isRaid AND wIn.valuatedInventory AND t.isInventory AND e.isConfirmed diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 6b26e456f..ee18bbe96 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -60,7 +60,7 @@ proc: BEGIN AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk AND w.isComparative AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid UNION ALL SELECT b.itemFk, - b.quantity FROM buy b @@ -71,7 +71,7 @@ proc: BEGIN AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk AND w.isComparative AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid ) sub GROUP BY itemFk; @@ -121,7 +121,7 @@ proc: BEGIN AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk AND w.isComparative AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid UNION ALL SELECT b.itemFk, t.shipped, - b.quantity FROM buy b @@ -132,7 +132,7 @@ proc: BEGIN AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk AND w.isComparative AND NOT e.isExcludedFromAvailable - AND NOT t.daysInForward + AND NOT t.isRaid ) sub GROUP BY sub.itemFk, sub.dated; diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index 1d206e20d..813c65ab2 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -217,7 +217,7 @@ proc: BEGIN st.code = 'previousPrepared' isPreviousPrepared, sc.itemPackingTypeFk FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector sc ON sc.id = p.sectorFk JOIN sectorType st ON st.id = sc.typeFk diff --git a/db/routines/vn/procedures/sale_boxPickingPrint.sql b/db/routines/vn/procedures/sale_boxPickingPrint.sql index 6bb954a78..f156ff8f8 100644 --- a/db/routines/vn/procedures/sale_boxPickingPrint.sql +++ b/db/routines/vn/procedures/sale_boxPickingPrint.sql @@ -27,7 +27,7 @@ BEGIN DECLARE vQuantity INT; DECLARE vRemainder INT DEFAULT 0; DECLARE vRemainderSaleFk INT; - DECLARE vShelving VARCHAR(10); + DECLARE vShelvingFk VARCHAR(10); DECLARE vTicketFk INT; SELECT s.quantity, @@ -74,7 +74,7 @@ w1: WHILE vQuantity >= vPacking DO p.pickingOrder, ish.created FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk LEFT JOIN itemShelvingSale iss ON iss.itemShelvingFk = ish.id @@ -262,9 +262,9 @@ w1: WHILE vQuantity >= vPacking DO CALL dipole.expedition_Add(vExpeditionFk,vPrinterFk, TRUE); SELECT shelvingFk, p.code - INTO vShelving, vParkingCode + INTO vShelvingFk, vParkingCode FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk WHERE ish.id = vItemShelvingFk; @@ -273,7 +273,7 @@ w1: WHILE vQuantity >= vPacking DO itemFk = vItemFk, quantity = vPacking, longName = vConcept, - shelvingFk = vShelving, + shelvingFk = vShelvingFk, parkingCode = vParkingCode, phone = RIGHT(phone,vMaxPhoneLength), street = RIGHT(street, vMAxStreetLength) diff --git a/db/routines/vn/procedures/sale_getBoxPickingList.sql b/db/routines/vn/procedures/sale_getBoxPickingList.sql index f343ab375..4f6a08083 100644 --- a/db/routines/vn/procedures/sale_getBoxPickingList.sql +++ b/db/routines/vn/procedures/sale_getBoxPickingList.sql @@ -41,7 +41,7 @@ BEGIN AND iss.created >= vDated GROUP BY iss.itemShelvingFk, s.itemFk) tISS ON tISS.itemFk = ish.itemFk AND tISS.itemShelvingFk = ish.id - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN tmp.productionBuffer pb ON pb.ticketFk = s.ticketFk JOIN agencyMode am ON am.id = pb.agencyModeFk diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index cd65bb81c..e016f3ab4 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -87,7 +87,7 @@ BEGIN SUM(ish.visible) visible, s.warehouseFk warehouseFk FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk GROUP BY ish.itemFk, s.warehouseFk; diff --git a/db/routines/vn/procedures/shelvingChange.sql b/db/routines/vn/procedures/shelvingChange.sql index 2e7e92082..901b1cf95 100644 --- a/db/routines/vn/procedures/shelvingChange.sql +++ b/db/routines/vn/procedures/shelvingChange.sql @@ -1,11 +1,13 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingChange`(IN `vShelvingO` VARCHAR(8), IN `vShelvingD` VARCHAR(8)) +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingChange`( + `vShelvingO` VARCHAR(10), + `vShelvingD` VARCHAR(10) +) BEGIN - - UPDATE vn.itemShelving - SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci - WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; - - + UPDATE itemShelving ish + JOIN shelving sh1 ON sh1.code = vShelvingD COLLATE utf8_unicode_ci + JOIN shelving sh2 ON sh2.code = vShelvingO COLLATE utf8_unicode_ci + SET ish.shelvingFk = sh1.id + WHERE ish.shelvingFk = sh2.id; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/shelvingParking_get.sql b/db/routines/vn/procedures/shelvingParking_get.sql index a9ed9f74a..c05e8afc3 100644 --- a/db/routines/vn/procedures/shelvingParking_get.sql +++ b/db/routines/vn/procedures/shelvingParking_get.sql @@ -1,8 +1,10 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT) -BEGIN - - +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`shelvingParking_get`( + vShelvingCode VARCHAR(10), + vWarehouseFk INT, + vDayRange INT +) +BEGIN SELECT s.itemFk, s.concept, CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, @@ -10,14 +12,15 @@ SELECT s.itemFk, FROM vn.sale s LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id JOIN vn.ticket t ON t.id = s.ticketFk - LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk - JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk + AND ist.warehouseFk = vWarehouseFk + JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk + JOIN shelving sh ON sh.id = ish.shelvingFk + AND sh.code = vShelvingCode COLLATE utf8_general_ci WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) AND iss.saleFk IS NULL AND t.warehouseFk = vWarehouseFk GROUP BY s.itemFk HAVING sinServir > aparcado; - - END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/shelving_clean.sql b/db/routines/vn/procedures/shelving_clean.sql index 0b29968bc..155338827 100644 --- a/db/routines/vn/procedures/shelving_clean.sql +++ b/db/routines/vn/procedures/shelving_clean.sql @@ -12,12 +12,12 @@ BEGIN DELETE ish.* FROM itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk WHERE sh.parkingFk IS NULL AND ish.created < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); UPDATE shelving sh - LEFT JOIN itemShelving its ON its.shelvingFk = sh.`code` + LEFT JOIN itemShelving its ON its.shelvingFk = sh.id SET isPrinted = 0, parkingFk = NULL WHERE its.id IS NULL @@ -27,11 +27,11 @@ UPDATE shelving sh OR sh.parked < util.VN_CURDATE() - INTERVAL 2 WEEK ) - AND IF(code REGEXP '^[A-Za-z]{2}[0-9]', LEFT (code, 2) NOT IN ( - SELECT DISTINCT LEFT(its.shelvingFk, 2) + SELECT DISTINCT LEFT(sh.code, 2) FROM itemShelving its - WHERE its.shelvingFk REGEXP '^[A-Za-z]{2}[0-9]' + JOIN shelving sh ON sh.id = its.shelvingFk + WHERE sh.code REGEXP '^[A-Za-z]{2}[0-9]' ), TRUE); END$$ diff --git a/db/routines/vn/procedures/shelving_getSpam.sql b/db/routines/vn/procedures/shelving_getSpam.sql index cef407285..a80021cdf 100644 --- a/db/routines/vn/procedures/shelving_getSpam.sql +++ b/db/routines/vn/procedures/shelving_getSpam.sql @@ -25,7 +25,7 @@ BEGIN LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva FROM vn.itemShelving ish - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'FUENTES_PICASSE' @@ -68,7 +68,7 @@ BEGIN sh.isSpam FROM vn.itemShelving ish JOIN vn.item i ON i.id = ish.itemFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk JOIN vn.warehouse w ON w.id = s.warehouseFk diff --git a/db/routines/vn/procedures/stockBought_calculate.sql b/db/routines/vn/procedures/stockBought_calculate.sql index ba044604a..c248d0deb 100644 --- a/db/routines/vn/procedures/stockBought_calculate.sql +++ b/db/routines/vn/procedures/stockBought_calculate.sql @@ -59,7 +59,7 @@ proc: BEGIN INSERT INTO stockBought(workerFk, bought, dated) SELECT tb.workerFk, - ROUND(GREATEST(tb.bought - IFNULL(ts.sold, 0), 0), 1), + ROUND(GREATEST(tb.bought - IFNULL(ts.sold, 0), 0), 2), vDated FROM tStockBought tb LEFT JOIN tStockSold ts ON ts.workerFk = tb.workerFk; @@ -80,7 +80,7 @@ proc: BEGIN UPDATE stockBought s JOIN tStockSold ts ON ts.workerFk = s.workerFk - SET s.bought = IF(s.bought < ts.sold, ROUND(s.bought - ts.sold, 1), 0) + SET s.bought = IF(s.bought < ABS(ts.sold), 0, ROUND(s.bought - ABS(ts.sold), 1)) WHERE s.dated = vDated; DROP TEMPORARY TABLE tCurrentData, tmp.item, tmp.buyUltimate, tStockSold; diff --git a/db/routines/vn/procedures/ticketDown_PrintableSelection.sql b/db/routines/vn/procedures/ticketDown_PrintableSelection.sql index 082a890a6..8f448d647 100644 --- a/db/routines/vn/procedures/ticketDown_PrintableSelection.sql +++ b/db/routines/vn/procedures/ticketDown_PrintableSelection.sql @@ -9,7 +9,7 @@ BEGIN JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id JOIN vn.itemShelving ish ON ish.id = iss.itemShelvingFk - JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.shelving sh ON sh.id = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE p.sectorFk = vSectorFk ) sub ON sub.id = td.ticketFk diff --git a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql index 1dc45d065..3d22207f3 100644 --- a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql +++ b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql @@ -27,7 +27,7 @@ BEGIN SUM(ish.visible) visible, s.warehouseFk warehouseFk FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk GROUP BY ish.itemFk, diff --git a/db/routines/vn/procedures/ticket_getSplitList.sql b/db/routines/vn/procedures/ticket_getSplitList.sql index 988bc2931..66e9bdb57 100644 --- a/db/routines/vn/procedures/ticket_getSplitList.sql +++ b/db/routines/vn/procedures/ticket_getSplitList.sql @@ -28,7 +28,7 @@ BEGIN SUM(ish.visible) visible, s.warehouseFk warehouseFk FROM itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN shelving sh ON sh.id = ish.shelvingFk JOIN parking p ON p.id = sh.parkingFk JOIN sector s ON s.id = p.sectorFk GROUP BY ish.itemFk, diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index 0ee865af5..31e0c24e7 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -5,122 +5,122 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`ticket_splitItemPacki ) BEGIN /** - * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. - * Respeta el id inicial para el tipo propuesto. + * Separa en diferentes tickets según el tipo de empaquetado + * El ticket original conserva las líneas del tipo de empaquetado especificado + * Las líneas sin tipo de empaquetado se asignan al ticket del tipo por defecto. * - * @param vSelf Id ticket - * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original + * @param vSelf Id del ticket original + * @param vOriginalItemPackingTypeFk Tipo de empaquetado a mantener en el ticket original * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ - DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; + DECLARE vIsDone BOOLEAN DEFAULT FALSE; + DECLARE vCurrentPackingType VARCHAR(1); + DECLARE vDefaultPackingType VARCHAR(1); + DECLARE vHasOriginalPackingType BOOLEAN; DECLARE vNewTicketFk INT; - DECLARE vPackingTypesToSplit INT; - DECLARE vDone INT DEFAULT FALSE; + DECLARE vTicketFk INT; - DECLARE vSaleGroup CURSOR FOR - SELECT itemPackingTypeFk - FROM tSaleGroup - WHERE itemPackingTypeFk IS NOT NULL - ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC; + DECLARE vItemPackingTypes CURSOR FOR + SELECT DISTINCT itemPackingTypeFk FROM tSalesToMove; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CREATE OR REPLACE TEMPORARY TABLE tSalesToMove ( + ticketFk INT, + saleFk INT, + itemPackingTypeFk VARCHAR(1) + ) ENGINE=MEMORY; + + SELECT COALESCE(MAX(ic.defaultPackingTypeFk), MAX(i.itemPackingTypeFk)) INTO vDefaultPackingType + FROM vn.sale s + JOIN item i ON i.id = s.itemFk + LEFT JOIN itemConfig ic ON ic.defaultPackingTypeFk = i.itemPackingTypeFk + WHERE s.ticketFk = vSelf + GROUP BY s.ticketFk; + + SELECT EXISTS ( + SELECT TRUE + FROM sale s + JOIN item i ON i.id = s.itemFk + WHERE s.ticketFk = vSelf + AND i.itemPackingTypeFk = vOriginalItemPackingTypeFk + ) INTO vHasOriginalPackingType; + + IF vOriginalItemPackingTypeFk IS NULL OR NOT vHasOriginalPackingType THEN + SET vOriginalItemPackingTypeFk = vDefaultPackingType; + END IF; START TRANSACTION; - SELECT id - FROM sale - WHERE ticketFk = vSelf - AND NOT quantity + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN sale s ON s.id = t.id + WHERE t.id = vSelf 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 + INSERT INTO tSalesToMove (saleFk, itemPackingTypeFk) + SELECT s.id, i.itemPackingTypeFk FROM sale s JOIN item i ON i.id = s.itemFk - LEFT JOIN saleVolume sv ON sv.saleFk = s.id - WHERE s.ticketFk = vSelf; + WHERE s.ticketFk = vSelf + AND i.itemPackingTypeFk <> vOriginalItemPackingTypeFk; - CREATE OR REPLACE TEMPORARY TABLE tSaleGroup - ENGINE = MEMORY - SELECT itemPackingTypeFk, SUM(litros) totalLitros - FROM tSale - GROUP BY itemPackingTypeFk; + OPEN vItemPackingTypes; + l: LOOP + SET vIsDone = FALSE; + FETCH vItemPackingTypes INTO vCurrentPackingType; - SELECT COUNT(*) INTO vPackingTypesToSplit - FROM tSaleGroup - WHERE itemPackingTypeFk IS NOT NULL; + IF vIsDone THEN + LEAVE l; + END IF; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( - ticketFk INT, - itemPackingTypeFk VARCHAR(1) - ) ENGINE = MEMORY; + CALL ticket_Clone(vSelf, vNewTicketFk); - CASE vPackingTypesToSplit - WHEN 0 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vSelf, vItemPackingTypeFk); - WHEN 1 THEN - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - SELECT vSelf, itemPackingTypeFk - FROM tSaleGroup - WHERE itemPackingTypeFk IS NOT NULL; - ELSE - OPEN vSaleGroup; - FETCH vSaleGroup INTO vItemPackingTypeFk; + SELECT id INTO vTicketFk + FROM ticket t + WHERE t.id = vNewTicketFk + FOR UPDATE; - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vSelf, vItemPackingTypeFk); + UPDATE tSalesToMove + SET ticketFk = vNewTicketFk + WHERE itemPackingTypeFk = vCurrentPackingType; - l: LOOP - SET vDone = FALSE; - FETCH vSaleGroup INTO vItemPackingTypeFk; + IF vCurrentPackingType = vDefaultPackingType THEN + INSERT INTO tSalesToMove (ticketFk, saleFk, itemPackingTypeFk) + SELECT vNewTicketFk, s.id, i.itemPackingTypeFk + FROM sale s + JOIN item i ON i.id = s.itemFk + WHERE s.ticketFk = vSelf + AND i.itemPackingTypeFk IS NULL; + END IF; - IF vDone THEN - LEAVE l; - END IF; + END LOOP; + CLOSE vItemPackingTypes; - CALL ticket_Clone(vSelf, vNewTicketFk); + UPDATE sale s + JOIN tSalesToMove t ON t.saleFk = s.id + SET s.ticketFk = t.ticketFk; - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vNewTicketFk, vItemPackingTypeFk); - END LOOP; - - CLOSE vSaleGroup; - - SELECT s.id - FROM sale s - JOIN tSale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk - 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 tSaleGroup sg - WHERE sg.itemPackingTypeFk IS NOT NULL - ORDER BY sg.itemPackingTypeFk - LIMIT 1; - - 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; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT + ENGINE=MEMORY + SELECT s.ticketFk, MAX(i.itemPackingTypeFk) itemPackingTypeFk + FROM sale s + JOIN item i ON i.id = s.itemFk + WHERE s.ticketFk = vSelf + GROUP BY s.ticketFk + UNION + SELECT ticketFk, MAX(itemPackingTypeFk) + FROM tSalesToMove + GROUP BY ticketFk; COMMIT; - DROP TEMPORARY TABLE - tSale, - tSaleGroup; + DROP TEMPORARY TABLE tSalesToMove; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/travelVolume_get.sql b/db/routines/vn/procedures/travelVolume_get.sql index bb98cacdf..ab24a6395 100644 --- a/db/routines/vn/procedures/travelVolume_get.sql +++ b/db/routines/vn/procedures/travelVolume_get.sql @@ -10,7 +10,7 @@ BEGIN JOIN vn.entry e ON e.travelFk = tr.id JOIN vn.buy b ON b.entryFk = e.id WHERE tr.landed BETWEEN vFromDated AND vToDated - AND NOT tr.daysInForward + AND NOT tr.isRaid AND tr.warehouseInFk = vWarehouseFk GROUP BY tr.landed , a.name ; END$$ diff --git a/db/routines/vn/procedures/travel_checkRaid.sql b/db/routines/vn/procedures/travel_checkRaid.sql new file mode 100644 index 000000000..64f3355e2 --- /dev/null +++ b/db/routines/vn/procedures/travel_checkRaid.sql @@ -0,0 +1,17 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`travel_checkRaid`( + vIsRaid BOOL, + vDaysInForward INT +) +BEGIN +/** + * Check if the values of isRaid and daysInforward are correct + * + * @param vIsRaid idRaid value + * @param vDaysInForward daysInForward value + */ + IF (NOT vIsRaid AND vDaysInForward IS NOT NULL) OR (vIsRaid AND vDaysInForward IS NULL) THEN + CALL util.throw('The raid information is not correct'); + END IF; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/travel_moveRaids.sql b/db/routines/vn/procedures/travel_moveRaids.sql index aa554a1a0..cf0fce23c 100644 --- a/db/routines/vn/procedures/travel_moveRaids.sql +++ b/db/routines/vn/procedures/travel_moveRaids.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`travel_moveRaids`() BEGIN /** * Desplaza los travels en el futuro y avisa a los compradores - * + * */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vBuyerEmail VARCHAR(40); @@ -11,21 +11,21 @@ BEGIN DECLARE vMailBody TEXT DEFAULT ''; DECLARE vCur CURSOR FOR - SELECT GROUP_CONCAT(DISTINCT - CONCAT('https://salix.verdnatura.es/#!/travel/', - ttm.travelFk, + SELECT GROUP_CONCAT(DISTINCT + CONCAT('https://salix.verdnatura.es/#!/travel/', + ttm.travelFk, '/summary ') ORDER BY ttm.travelFk SEPARATOR '\n\r') travelLink, CONCAT(u.name, '@verdnatura.es') buyerEmail FROM tTravelToMove ttm - JOIN entry e ON e.travelFk = ttm.travelFk + JOIN entry e ON e.travelFk = ttm.travelFk JOIN buy b ON b.entryFk = e.id JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk JOIN account.user u ON u.id = it.workerFk GROUP BY u.name; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN @@ -34,10 +34,11 @@ BEGIN END; CREATE OR REPLACE TEMPORARY TABLE tTravelToMove - SELECT id travelFk, + SELECT id travelFk, util.VN_CURDATE() + INTERVAL daysInForward DAY newLanded FROM travel - WHERE daysInForward; + WHERE isRaid + AND daysInForward; START TRANSACTION; diff --git a/db/routines/vn/procedures/workerTimeControl_check.sql b/db/routines/vn/procedures/workerTimeControl_check.sql deleted file mode 100644 index 30cf5c639..000000000 --- a/db/routines/vn/procedures/workerTimeControl_check.sql +++ /dev/null @@ -1,168 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`workerTimeControl_check`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100)) -proc: BEGIN -/** - * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a workerTimeControlAdd - * - * @param vUserFk Identificador del trabajador - * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ; - * En caso de tener algun problema retorna el primero que encuentra - */ - DECLARE vLastIn DATETIME ; - DECLARE vLastOut DATETIME ; - DECLARE vDayWorkMax INT; - DECLARE vDayBreak INT; - DECLARE vWeekBreak INT ; - DECLARE vWeekScope INT; - DECLARE vDayStayMax INT; - DECLARE vProblem VARCHAR(20) DEFAULT NULL; - DECLARE vTimedWorked INT; - DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL; - DECLARE vDepartmentFk INT; - DECLARE vTo VARCHAR(50) DEFAULT NULL; - DECLARE vUserName VARCHAR(50) DEFAULT NULL; - DECLARE vBody VARCHAR(255) DEFAULT NULL; - - SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax - INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax - FROM workerTimeControlParams; - - SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'in'; - - SELECT MAX(timed) INTO vLastOut - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'out'; - - SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo - FROM account.user u - WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); - - SELECT CONCAT(firstName,' ',lastName) INTO vUserName - FROM worker w - WHERE w.id = vUserFk; - - - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA - - -- VERIFICAR DESCANSO DIARIO - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN - SELECT "Descansos 12 h" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ - IF (SELECT MOD(COUNT(*),2) -- <>0 - FROM workerTimeControl - WHERE userFk = vUserFk - AND timed >= vLastIn - ) THEN - SELECT "Dias con fichadas impares" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - -- VERIFICAR VACACIONES - SELECT at2.name INTO vCalendarStateType - FROM calendar c - JOIN business b ON b.id = c.businessFk - JOIN absenceType at2 ON at2.id = c.dayOffTypeFk - WHERE c.dated = util.VN_CURDATE() - AND at2.isAllowedToWork = FALSE - AND b.workerFk = vUserFk - LIMIT 1; - - IF(LENGTH(vCalendarStateType)) THEN - SELECT vCalendarStateType AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - - END IF; - - -- VERIFICAR CONTRATO EN VIGOR - IF (SELECT COUNT(*) - FROM business b - WHERE b.workerFk = vUserFk - AND b.started <= vDated - AND IFNULL(b.ended, vDated) >= vDated - ) = 0 THEN - SELECT "No hay un contrato en vigor" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - - END IF; - - -- VERIFICAR DESCANSO SEMANAL - SET @vHasBreakWeek:= FALSE; - SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); - - DROP TEMPORARY TABLE IF EXISTS tmp.trash; - CREATE TEMPORARY TABLE tmp.trash - SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, - @vLastTimed:= UNIX_TIMESTAMP(timed) - FROM workerTimeControl - WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND) - AND userFk= vUserFk - AND direction IN ('in','out') - ORDER BY timed ASC; - - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA - SELECT "Descansos 36 h" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - DROP TEMPORARY TABLE tmp.trash; - - ELSE -- DIA ACTUAL - - -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO - SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked - FROM workerTimeControl wtc - WHERE userFk = vUserFk - AND timed >= vLastIn - ORDER BY timed; - - IF vTimedWorked > vDayWorkMax THEN - SELECT "Jornadas" AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - - END IF; - - -- VERIFICAR DEPARTAMENTO - /* IF vTabletFk IS NOT NULL THEN - SELECT wtcu.departmentFk INTO vDepartmentFk - FROM workerTimeControlUserInfo wtcu - WHERE wtcu.userFk = vUserFk; - IF (SELECT COUNT(td.tabletFk) - FROM tabletDepartment td - WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk - ) = 0 THEN - SELECT "No perteneces a este departamento." AS problem; - -- ENVIAMOS CORREO AL BOSSFK - SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; - CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - END IF; - END IF;*/ - -END$$ -DELIMITER ; diff --git a/db/routines/vn/triggers/address_beforeInsert.sql b/db/routines/vn/triggers/address_beforeInsert.sql index 56ef7aa51..a4f384f14 100644 --- a/db/routines/vn/triggers/address_beforeInsert.sql +++ b/db/routines/vn/triggers/address_beforeInsert.sql @@ -6,6 +6,7 @@ BEGIN DECLARE vIsEqualizated BOOL; SET NEW.editorFk = account.myUser_getId(); + SET NEW.geoFk = address_getGeo(NEW.id); IF (NEW.phone <> '') THEN CALL pbx.phone_isValid(NEW.phone); diff --git a/db/routines/vn/triggers/address_beforeUpdate.sql b/db/routines/vn/triggers/address_beforeUpdate.sql index 35887912c..0b19a6266 100644 --- a/db/routines/vn/triggers/address_beforeUpdate.sql +++ b/db/routines/vn/triggers/address_beforeUpdate.sql @@ -3,7 +3,6 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`address_beforeUpdate` BEFORE UPDATE ON `address` FOR EACH ROW BEGIN - SET NEW.editorFk = account.myUser_getId(); IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN @@ -14,5 +13,10 @@ BEGIN CALL pbx.phone_isValid(NEW.mobile); END IF; + IF NOT (NEW.provinceFk <=> OLD.provinceFk) + OR (NEW.postalCode <=> OLD.postalCode) THEN + + SET NEW.geoFk = address_getGeo(NEW.id); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/client_beforeInsert.sql b/db/routines/vn/triggers/client_beforeInsert.sql index 45de107f1..b4038a2ba 100644 --- a/db/routines/vn/triggers/client_beforeInsert.sql +++ b/db/routines/vn/triggers/client_beforeInsert.sql @@ -3,8 +3,10 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`client_beforeInsert` BEFORE INSERT ON `client` FOR EACH ROW BEGIN - SET NEW.editorFk = account.myUser_getId(); + SET NEW.accountingAccount = 4300000000 + NEW.id; + SET NEW.lastSalesPersonFk = NEW.salesPersonFk; + SET NEW.geoFk = client_getGeo(NEW.id); IF (NEW.phone <> '') THEN CALL pbx.phone_isValid(NEW.phone); @@ -13,9 +15,5 @@ BEGIN IF (NEW.mobile <> '') THEN CALL pbx.phone_isValid(NEW.mobile); END IF; - - SET NEW.accountingAccount = 4300000000 + NEW.id; - - SET NEW.lastSalesPersonFk = NEW.salesPersonFk; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/client_beforeUpdate.sql b/db/routines/vn/triggers/client_beforeUpdate.sql index 7142d6604..00418a9e7 100644 --- a/db/routines/vn/triggers/client_beforeUpdate.sql +++ b/db/routines/vn/triggers/client_beforeUpdate.sql @@ -72,5 +72,11 @@ BEGIN IF NOT (NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN SET NEW.isTaxDataChecked = 0; END IF; + + IF NOT (NEW.provinceFk <=> OLD.provinceFk) + OR (NEW.postcode <=> OLD.postcode) THEN + + SET NEW.geoFk = client_getGeo(NEW.id); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 3b999012f..4f2c5ed4a 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -3,7 +3,7 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`entry_beforeUpdate` BEFORE UPDATE ON `entry` FOR EACH ROW BEGIN - DECLARE vDaysInForward INT; + DECLARE vIsRaid BOOL; DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; DECLARE vTotalBuy INT; @@ -38,10 +38,10 @@ BEGIN CALL travel_throwAwb(NEW.travelFk); END IF; - SELECT daysInForward INTO vDaysInForward + SELECT t.isRaid INTO vIsRaid FROM travel t JOIN entry e ON e.travelFk = t.id - WHERE entryFk = NEW.id; + WHERE e.id = NEW.id; SELECT NOT (o.warehouseInFk <=> n.warehouseInFk) OR NOT (o.warehouseOutFk <=> n.warehouseOutFk) @@ -50,7 +50,7 @@ BEGIN WHERE o.id = OLD.travelFk AND n.id = NEW.travelFk; - IF vDaysInForward AND vHasDistinctWarehouses THEN + IF vIsRaid AND vHasDistinctWarehouses THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; END IF; diff --git a/db/routines/vn/triggers/route_afterUpdate.sql b/db/routines/vn/triggers/route_afterUpdate.sql index ec205090e..447608acc 100644 --- a/db/routines/vn/triggers/route_afterUpdate.sql +++ b/db/routines/vn/triggers/route_afterUpdate.sql @@ -2,18 +2,18 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`route_afterUpdate` AFTER UPDATE ON `route` FOR EACH ROW -BEGIN +BEGIN IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN -- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets - + -- Inserta el gestdoc en todos los tickets de la ruta INSERT INTO ticketDms(ticketFk,dmsFk) SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk; - -- Update del firmado - UPDATE ticket t - JOIN ticketDms tg ON t.id = tg.ticketFk + -- Update del firmado + UPDATE ticket t + JOIN ticketDms tg ON t.id = tg.ticketFk SET isSigned = 1 WHERE t.routeFk = NEW.id; END IF; @@ -21,7 +21,8 @@ BEGIN OR !(NEW.kmEnd <=> OLD.kmEnd) OR !(NEW.workerFk <=> OLD.workerFk) OR !(NEW.m3 <=> OLD.m3) - OR !(NEW.agencyModeFk <=> OLD.agencyModeFk)THEN + OR !(NEW.agencyModeFk <=> OLD.agencyModeFk) + OR !(NEW.vehicleFk <=> OLD.vehicleFk)THEN CALL route_calcCommission(NEW.id); END IF; diff --git a/db/routines/vn/triggers/supplier_beforeInsert.sql b/db/routines/vn/triggers/supplier_beforeInsert.sql index b141ec8fb..5bbfc79a1 100644 --- a/db/routines/vn/triggers/supplier_beforeInsert.sql +++ b/db/routines/vn/triggers/supplier_beforeInsert.sql @@ -4,5 +4,6 @@ CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`supplier_beforeInsert` FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); + SET NEW.geoFk = supplier_getGeo(NEW.id); END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/supplier_beforeUpdate.sql b/db/routines/vn/triggers/supplier_beforeUpdate.sql index af730b49d..b502340a3 100644 --- a/db/routines/vn/triggers/supplier_beforeUpdate.sql +++ b/db/routines/vn/triggers/supplier_beforeUpdate.sql @@ -40,5 +40,10 @@ BEGIN SET NEW.isPayMethodChecked = FALSE; END IF; + IF NOT (NEW.provinceFk <=> OLD.provinceFk) + OR (NEW.postCode <=> OLD.postCode) THEN + + SET NEW.geoFk = supplier_getGeo(NEW.id); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/town_beforeUpdate.sql b/db/routines/vn/triggers/town_beforeUpdate.sql deleted file mode 100644 index fc1410d5c..000000000 --- a/db/routines/vn/triggers/town_beforeUpdate.sql +++ /dev/null @@ -1,10 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`vn`@`localhost` TRIGGER `vn`.`town_beforeUpdate` - BEFORE UPDATE ON `town` - FOR EACH ROW -BEGIN - -- IF !(OLD.geoFk <=> NEW.geoFk) THEN - -- CALL zoneGeo_throwNotEditable; - -- END IF; -END$$ -DELIMITER ; diff --git a/db/routines/vn/triggers/travel_beforeInsert.sql b/db/routines/vn/triggers/travel_beforeInsert.sql index 4563c9a81..5356ed537 100644 --- a/db/routines/vn/triggers/travel_beforeInsert.sql +++ b/db/routines/vn/triggers/travel_beforeInsert.sql @@ -8,7 +8,11 @@ BEGIN CALL travel_checkDates(NEW.shipped, NEW.landed); CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); - + + IF NEW.isRaid IS NOT NULL OR NEW.daysInForward IS NOT NULL THEN + CALL travel_checkRaid(NEW.isRaid, NEW.daysInForward); + END IF; + IF NEW.awbFk IS NOT NULL THEN CALL travel_throwAwb(NEW.id); END IF; diff --git a/db/routines/vn/triggers/travel_beforeUpdate.sql b/db/routines/vn/triggers/travel_beforeUpdate.sql index 33578fea1..5a27b43b4 100644 --- a/db/routines/vn/triggers/travel_beforeUpdate.sql +++ b/db/routines/vn/triggers/travel_beforeUpdate.sql @@ -7,7 +7,7 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); - IF NOT (NEW.landed <=> OLD.landed) + IF NOT (NEW.landed <=> OLD.landed) OR NOT (NEW.shipped <=> OLD.shipped) THEN CALL travel_checkDates(NEW.shipped, NEW.landed); END IF; @@ -20,19 +20,23 @@ BEGIN CALL travel_checkWarehouseIsFeedStock(NEW.warehouseInFk); END IF; + IF NOT (NEW.isRaid <=> OLD.isRaid) OR NOT (NEW.daysInForward <=> OLD.daysInForward) THEN + CALL travel_checkRaid(NEW.isRaid, NEW.daysInForward); + END IF; + IF NOT (NEW.awbFk <=> OLD.awbFk)THEN - SELECT COUNT(*) INTO vHasAnyInvoiceBooked + SELECT COUNT(*) INTO vHasAnyInvoiceBooked FROM travel t - JOIN entry e ON e.travelFk = t.id - JOIN invoiceIn ii ON ii.id = e.invoiceInFk + JOIN entry e ON e.travelFk = t.id + JOIN invoiceIn ii ON ii.id = e.invoiceInFk WHERE t.id = NEW.id - AND ii.isBooked; - + AND ii.isBooked; + IF vHasAnyInvoiceBooked THEN CALL util.throw('The travel has entries with booked invoices'); END IF; - END IF; - + END IF; + IF (NOT(NEW.awbFk <=> OLD.awbFk)) AND NEW.awbFk IS NOT NULL THEN CALL travel_throwAwb(NEW.id); END IF; diff --git a/db/routines/vn/views/itemEntryIn.sql b/db/routines/vn/views/itemEntryIn.sql index 6196e9396..60af585f2 100644 --- a/db/routines/vn/views/itemEntryIn.sql +++ b/db/routines/vn/views/itemEntryIn.sql @@ -6,7 +6,7 @@ AS SELECT `t`.`warehouseInFk` AS `warehouseInFk`, `b`.`itemFk` AS `itemFk`, `b`.`quantity` AS `quantity`, `t`.`isReceived` AS `isReceived`, - `t`.`daysInForward` AS `isVirtualStock`, + `t`.`isRaid` AS `isVirtualStock`, `e`.`id` AS `entryFk` FROM ( ( diff --git a/db/routines/vn/views/itemEntryOut.sql b/db/routines/vn/views/itemEntryOut.sql index f18116e61..4793ddbb8 100644 --- a/db/routines/vn/views/itemEntryOut.sql +++ b/db/routines/vn/views/itemEntryOut.sql @@ -15,5 +15,5 @@ FROM ( JOIN `vn`.`travel` `t` ON(`e`.`travelFk` = `t`.`id`) ) WHERE `e`.`isExcludedFromAvailable` = 0 - AND NOT `t`.`daysInForward` + AND NOT `t`.`isRaid` AND `b`.`quantity` <> 0 diff --git a/db/routines/vn/views/itemShelvingList.sql b/db/routines/vn/views/itemShelvingList.sql index 457d6f28a..f2cfeda58 100644 --- a/db/routines/vn/views/itemShelvingList.sql +++ b/db/routines/vn/views/itemShelvingList.sql @@ -15,7 +15,7 @@ FROM ( ( ( `vn`.`itemShelving` `ish` - JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) JOIN `vn`.`item` `i` ON(`i`.`id` = `ish`.`itemFk`) ) diff --git a/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql b/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql index fa1c11314..1ebb6410c 100644 --- a/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql +++ b/db/routines/vn/views/itemShelvingPlacementSupplyStock.sql @@ -18,7 +18,7 @@ FROM ( ( ( `vn`.`itemShelving` `ish` - JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) LEFT JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`) ) diff --git a/db/routines/vn/views/itemShelvingSaleSum.sql b/db/routines/vn/views/itemShelvingSaleSum.sql index 9a402d6f4..60581faa9 100644 --- a/db/routines/vn/views/itemShelvingSaleSum.sql +++ b/db/routines/vn/views/itemShelvingSaleSum.sql @@ -13,7 +13,7 @@ FROM ( `vn`.`itemShelvingSale` `iss` JOIN `vn`.`itemShelving` `ish` ON(`ish`.`id` = `iss`.`itemShelvingFk`) ) - JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`) ) diff --git a/db/routines/vn/views/itemShelvingStock.sql b/db/routines/vn/views/itemShelvingStock.sql index 41777eaec..725a06f88 100644 --- a/db/routines/vn/views/itemShelvingStock.sql +++ b/db/routines/vn/views/itemShelvingStock.sql @@ -21,7 +21,7 @@ FROM ( ( ( `vn`.`itemShelving` `ish` - LEFT JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + LEFT JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) LEFT JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`) ) diff --git a/db/routines/vn/views/itemShelvingStockFull.sql b/db/routines/vn/views/itemShelvingStockFull.sql index c767823d6..c8a82685c 100644 --- a/db/routines/vn/views/itemShelvingStockFull.sql +++ b/db/routines/vn/views/itemShelvingStockFull.sql @@ -19,7 +19,7 @@ FROM ( ( ( `vn`.`itemShelving` `ish` - JOIN `vn`.`shelving` `sh` ON(`sh`.`code` = `ish`.`shelvingFk`) + JOIN `vn`.`shelving` `sh` ON(`sh`.`id` = `ish`.`shelvingFk`) ) JOIN `vn`.`parking` `p` ON(`p`.`id` = `sh`.`parkingFk`) ) diff --git a/db/routines/vn/views/lastPurchases.sql b/db/routines/vn/views/lastPurchases.sql index 9dc5ec898..3dcaf8c1d 100644 --- a/db/routines/vn/views/lastPurchases.sql +++ b/db/routines/vn/views/lastPurchases.sql @@ -31,5 +31,5 @@ FROM ( LEFT JOIN `edi`.`ekt` `ek` ON(`ek`.`id` = `b`.`ektFk`) ) WHERE `tr`.`landed` BETWEEN `util`.`yesterday`() AND `util`.`tomorrow`() - AND NOT `tr`.`daysInForward` + AND NOT `tr`.`isRaid` AND `b`.`stickers` > 0 diff --git a/db/routines/vn2008/views/entrySource.sql b/db/routines/vn2008/views/entrySource.sql index 9c0c0f6ed..732603617 100644 --- a/db/routines/vn2008/views/entrySource.sql +++ b/db/routines/vn2008/views/entrySource.sql @@ -8,6 +8,7 @@ AS SELECT `e`.`gestDocFk` AS `gestdoc_id`, `e`.`isExcludedFromAvailable` AS `Inventario`, `e`.`isConfirmed` AS `Confirmada`, `e`.`isOrdered` AS `Pedida`, + `tr`.`isRaid` AS `isRaid`, `tr`.`daysInForward` AS `daysInForward`, `e`.`evaNotes` AS `notas`, `e`.`supplierFk` AS `Id_Proveedor`, diff --git a/db/routines/vn2008/views/travel.sql b/db/routines/vn2008/views/travel.sql index 0e1f5acb2..38dfd40ea 100644 --- a/db/routines/vn2008/views/travel.sql +++ b/db/routines/vn2008/views/travel.sql @@ -18,5 +18,6 @@ AS SELECT `t`.`id` AS `id`, `t`.`totalEntries` AS `totalEntries`, `t`.`appointment` AS `appointment`, `t`.`awbFk` AS `awbFk`, + `t`.`isRaid` AS `isRaid`, `t`.`daysInForward` AS `daysInForward` FROM `vn`.`travel` `t` diff --git a/db/routines/vn2008/views/v_compres.sql b/db/routines/vn2008/views/v_compres.sql index 324e459f6..633feb471 100644 --- a/db/routines/vn2008/views/v_compres.sql +++ b/db/routines/vn2008/views/v_compres.sql @@ -86,4 +86,4 @@ FROM ( ) WHERE NOT `W_IN`.`isFeedStock` AND NOT `E`.`Inventario` - AND NOT `TR`.`daysInForward` + AND NOT `TR`.`isRaid` diff --git a/db/versions/11251-navyChrysanthemum/00-firstScript.sql b/db/versions/11251-navyChrysanthemum/00-firstScript.sql index 801405e59..7c2c69839 100644 --- a/db/versions/11251-navyChrysanthemum/00-firstScript.sql +++ b/db/versions/11251-navyChrysanthemum/00-firstScript.sql @@ -1,3 +1,2 @@ -UPDATE vn.sale - SET originalQuantity = quantity - WHERE originalQuantity IS NULL +-- Debido a que tardaba mucho en la subida a master, se ha creado una nueva versión para que el proceso no se vea afectado y se ejecute por la noche. +-- Se crea de nuevo en la versión 11344-grayBamboo diff --git a/db/versions/11312-navyAralia/00-firstScript.sql b/db/versions/11312-navyAralia/00-firstScript.sql new file mode 100644 index 000000000..452b1feed --- /dev/null +++ b/db/versions/11312-navyAralia/00-firstScript.sql @@ -0,0 +1,23 @@ +ALTER TABLE vn.workerRelatives DROP FOREIGN KEY workerRelatives_disabilityGradeFk; +ALTER TABLE vn.workerRelatives DROP FOREIGN KEY workerRelatives_workerFk; + +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES + ('WorkerRelative','updateAttributes','*','ALLOW','ROLE','hr'), + ('WorkerRelative','crud','WRITE','ALLOW','ROLE','hr'), + ('WorkerRelative','findById','*','ALLOW','ROLE','hr'), + ('WorkerRelative','find','*','ALLOW','ROLE','hr'), + ('WorkerRelative','upsert','*','ALLOW','ROLE','hr'), + ('WorkerRelative','filter','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','updateAttributes','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','crud','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','findById','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','find','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','upsert','*','ALLOW','ROLE','hr'), + ('WorkerIrpf','filter','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','updateAttributes','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','crud','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','findById','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','find','*','ALLOW','ROLE','hr'), + ('DisabilityGrade','upsert','*','ALLOW','ROLE','hr'); + diff --git a/db/versions/11322-azureAspidistra/00-entryAcl.sql b/db/versions/11322-azureAspidistra/00-entryAcl.sql new file mode 100644 index 000000000..836737d4b --- /dev/null +++ b/db/versions/11322-azureAspidistra/00-entryAcl.sql @@ -0,0 +1,40 @@ +-- Eliminar registros existentes donde property = '*' +DELETE FROM `salix`.ACL WHERE model = 'entry' AND property = '*'; + +-- Insertar permisos para los métodos solicitados en el modelo Entry +INSERT INTO `salix`.ACL (model, property, accessType, permission, principalType, principalId) +VALUES + -- Permisos para administrative + ('Entry', 'upsert', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'updateAttributes', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'isBooked', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'findById', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'find', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'filter', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'count', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'getEntry', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'getBuys', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'findOne', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'deleteBuys', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'editLatestBuys', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'importBuys', 'WRITE', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'importBuysPreview', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'lastItemBuys', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('Entry', 'latestBuysFilter', 'READ', 'ALLOW', 'ROLE', 'administrative'), + + -- Permisos para buyer (excluyendo isBooked) + ('Entry', 'upsert', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'updateAttributes', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'findById', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'find', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'filter', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'count', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'getEntry', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'getBuys', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'findOne', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'deleteBuys', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'editLatestBuys', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'importBuys', 'WRITE', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'importBuysPreview', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'lastItemBuys', 'READ', 'ALLOW', 'ROLE', 'buyer'), + ('Entry', 'latestBuysFilter', 'READ', 'ALLOW', 'ROLE', 'buyer'); diff --git a/db/versions/11332-tealErica/00-firstScript.sql b/db/versions/11332-tealErica/00-firstScript.sql new file mode 100644 index 000000000..6358695b2 --- /dev/null +++ b/db/versions/11332-tealErica/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.travel ADD isRaid tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Redada'; + +ALTER TABLE vn.travel MODIFY COLUMN daysInForward int(10) unsigned DEFAULT NULL + COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada'; diff --git a/db/versions/11336-chocolateRaphis/00-firstScript.sql b/db/versions/11336-chocolateRaphis/00-firstScript.sql new file mode 100644 index 000000000..c86dc39e9 --- /dev/null +++ b/db/versions/11336-chocolateRaphis/00-firstScript.sql @@ -0,0 +1,8 @@ +DELETE FROM salix.ACL + WHERE property IN ('cmrs', 'cmr', 'downloadCmrsZip') + AND model = 'Route'; + +INSERT INTO salix.ACL (model,property,principalId) + VALUES ('Cmr','filter','production'), + ('Cmr','downloadZip','production'), + ('Cmr','print','production') \ No newline at end of file diff --git a/db/versions/11341-pinkSalal/00-firstScript.sql b/db/versions/11341-pinkSalal/00-firstScript.sql new file mode 100644 index 000000000..2c9e912d9 --- /dev/null +++ b/db/versions/11341-pinkSalal/00-firstScript.sql @@ -0,0 +1,5 @@ + +ALTER TABLE vn.travel ADD IF NOT EXISTS isRaid tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Redada'; + +ALTER TABLE vn.travel MODIFY COLUMN daysInForward int(10) unsigned DEFAULT NULL + COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada'; diff --git a/db/versions/11342-crimsonDendro/00-itemShelving.sql b/db/versions/11342-crimsonDendro/00-itemShelving.sql new file mode 100644 index 000000000..4d083bf97 --- /dev/null +++ b/db/versions/11342-crimsonDendro/00-itemShelving.sql @@ -0,0 +1,6 @@ +CREATE OR REPLACE TEMPORARY TABLE tmp.tItemShelving + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT ish.id, s.id shelvingFk + FROM vn.itemShelving ish + JOIN vn.shelving s ON s.code = ish.shelvingFk COLLATE utf8mb3_unicode_ci; diff --git a/db/versions/11342-crimsonDendro/01-itemShelving.sql b/db/versions/11342-crimsonDendro/01-itemShelving.sql new file mode 100644 index 000000000..23099ac6b --- /dev/null +++ b/db/versions/11342-crimsonDendro/01-itemShelving.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.itemShelving DROP FOREIGN KEY itemShelving_fk2, + MODIFY COLUMN shelvingFk int(11) NOT NULL; diff --git a/db/versions/11342-crimsonDendro/02-itemShelving.sql b/db/versions/11342-crimsonDendro/02-itemShelving.sql new file mode 100644 index 000000000..9d0e65d0b --- /dev/null +++ b/db/versions/11342-crimsonDendro/02-itemShelving.sql @@ -0,0 +1,3 @@ +UPDATE vn.itemShelving ish + JOIN tmp.tItemShelving tish ON tish.id = ish.id + SET ish.shelvingFk = tish.shelvingFk; \ No newline at end of file diff --git a/db/versions/11342-crimsonDendro/03-itemShelving.sql b/db/versions/11342-crimsonDendro/03-itemShelving.sql new file mode 100644 index 000000000..cb9825bfc --- /dev/null +++ b/db/versions/11342-crimsonDendro/03-itemShelving.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.itemShelving + ADD CONSTRAINT itemShelving_shelving_FK FOREIGN KEY (shelvingFk) REFERENCES vn.shelving(id) + ON DELETE RESTRICT + ON UPDATE CASCADE; diff --git a/db/versions/11342-crimsonDendro/04-itemShelvingLog.sql b/db/versions/11342-crimsonDendro/04-itemShelvingLog.sql new file mode 100644 index 000000000..1135b9d09 --- /dev/null +++ b/db/versions/11342-crimsonDendro/04-itemShelvingLog.sql @@ -0,0 +1,8 @@ +/* +CREATE OR REPLACE TEMPORARY TABLE tmp.tItemShelvingLog + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT ishl.id, s.id shelvingFk + FROM vn.itemShelvingLog ishl + JOIN vn.shelving s ON s.code = ishl.shelvingFk COLLATE utf8mb3_unicode_ci; +*/ diff --git a/db/versions/11342-crimsonDendro/05-itemShelvingLog.sql b/db/versions/11342-crimsonDendro/05-itemShelvingLog.sql new file mode 100644 index 000000000..b0e3b55cc --- /dev/null +++ b/db/versions/11342-crimsonDendro/05-itemShelvingLog.sql @@ -0,0 +1 @@ +-- ALTER TABLE vn.itemShelvingLog MODIFY COLUMN shelvingFk int(11) NOT NULL; diff --git a/db/versions/11342-crimsonDendro/06-itemShelvingLog.sql b/db/versions/11342-crimsonDendro/06-itemShelvingLog.sql new file mode 100644 index 000000000..f97f61e42 --- /dev/null +++ b/db/versions/11342-crimsonDendro/06-itemShelvingLog.sql @@ -0,0 +1,7 @@ +/* +UPDATE vn.itemShelvingLog ishl + JOIN tmp.tItemShelvingLog tishl ON tishl.id = ishl.id + SET ishl.shelvingFk = tishl.shelvingFk; + +DROP TEMPORARY TABLE tmp.tItemShelvingLog; +*/ \ No newline at end of file diff --git a/db/versions/11343-silverAsparagus/00-firstScript.sql b/db/versions/11343-silverAsparagus/00-firstScript.sql new file mode 100644 index 000000000..bcee42eea --- /dev/null +++ b/db/versions/11343-silverAsparagus/00-firstScript.sql @@ -0,0 +1,9 @@ +INSERT INTO salix.ACL (model, property, accessType, principalId) + VALUES ('Collection', 'create', 'WRITE', 'productionBoss'), + ('Collection', 'upsert', 'WRITE', 'productionBoss'), + ('Collection', 'replaceById', 'WRITE', 'productionBoss'), + ('Collection', 'updateAll', 'WRITE', 'productionBoss'), + ('Collection', 'updateAttributes', 'WRITE', 'productionBoss'), + ('Collection', 'deleteById', 'WRITE', 'productionBoss'), + ('Collection', 'destroyAll', 'WRITE', 'productionBoss'), + ('Collection', 'destroyById', 'WRITE', 'productionBoss'); diff --git a/db/versions/11344-grayBamboo/00-firstScript.sql b/db/versions/11344-grayBamboo/00-firstScript.sql new file mode 100644 index 000000000..1fbd2a0d8 --- /dev/null +++ b/db/versions/11344-grayBamboo/00-firstScript.sql @@ -0,0 +1,3 @@ +UPDATE vn.sale + SET originalQuantity = quantity + WHERE originalQuantity IS NULL \ No newline at end of file diff --git a/db/versions/11251-navyChrysanthemum/01-firstScript.sql b/db/versions/11344-grayBamboo/01-firstScript.sql similarity index 100% rename from db/versions/11251-navyChrysanthemum/01-firstScript.sql rename to db/versions/11344-grayBamboo/01-firstScript.sql diff --git a/db/versions/11345-salmonEucalyptus/00-firstScript.sql b/db/versions/11345-salmonEucalyptus/00-firstScript.sql new file mode 100644 index 000000000..ecbc36c40 --- /dev/null +++ b/db/versions/11345-salmonEucalyptus/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE account.user CHANGE recoverPass recoverPass__ tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT '@deprecated 2024-11-13'; +ALTER TABLE account.user CHANGE sync sync__ tinyint(4) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-11-13'; \ No newline at end of file diff --git a/db/versions/11346-yellowPhormium/00-address.sql b/db/versions/11346-yellowPhormium/00-address.sql new file mode 100644 index 000000000..f91d0ae9f --- /dev/null +++ b/db/versions/11346-yellowPhormium/00-address.sql @@ -0,0 +1,23 @@ +ALTER TABLE vn.address + ADD geoFk int(11) DEFAULT NULL NULL AFTER isLogifloraAllowed, + ADD CONSTRAINT address_zoneGeo_FK FOREIGN KEY (geoFk) + REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE OR REPLACE TEMPORARY TABLE tmp.tAddressGeo + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT a.id, p.geoFk + FROM vn.address a + JOIN vn.town t ON t.provinceFk = a.provinceFk + JOIN vn.postCode p ON p.townFk = t.id + AND (p.code = a.postalCode OR a.postalCode IS NULL) + JOIN vn.zoneGeo zg ON zg.id = p.geoFk + GROUP BY a.id + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC, + (p.code = a.postalCode) DESC; + +UPDATE vn.address a + JOIN tmp.tAddressGeo tag ON tag.id = a.id + SET a.geoFk = tag.geoFk; + +DROP TEMPORARY TABLE tmp.tAddressGeo; diff --git a/db/versions/11346-yellowPhormium/01-client.sql b/db/versions/11346-yellowPhormium/01-client.sql new file mode 100644 index 000000000..cb6fe41e8 --- /dev/null +++ b/db/versions/11346-yellowPhormium/01-client.sql @@ -0,0 +1,26 @@ +ALTER TABLE vn.client + CHANGE hasDailyInvoice hasDailyInvoice tinyint(1) DEFAULT 0 NOT NULL + COMMENT 'Indica si el cliente requiere facturación diaria por defecto se copiará lo que tenga country.hasDailyInvoice' + AFTER recommendedCredit, + ADD geoFk int(11) DEFAULT NULL NULL AFTER hasDailyInvoice, + ADD CONSTRAINT client_zoneGeo_FK FOREIGN KEY (geoFk) + REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE OR REPLACE TEMPORARY TABLE tmp.tClientGeo + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT c.id, p.geoFk + FROM vn.client c + JOIN vn.town t ON t.provinceFk = c.provinceFk + JOIN vn.postCode p ON p.townFk = t.id + AND (p.code = c.postcode OR c.postcode IS NULL) + JOIN vn.zoneGeo zg ON zg.id = p.geoFk + GROUP BY c.id + ORDER BY (c.city SOUNDS LIKE t.`name`) DESC, + (p.code = c.postcode) DESC; + +UPDATE vn.client c + JOIN tmp.tClientGeo tcg ON tcg.id = c.id + SET c.geoFk = tcg.geoFk; + +DROP TEMPORARY TABLE tmp.tClientGeo; diff --git a/db/versions/11346-yellowPhormium/02-supplier.sql b/db/versions/11346-yellowPhormium/02-supplier.sql new file mode 100644 index 000000000..4e866525e --- /dev/null +++ b/db/versions/11346-yellowPhormium/02-supplier.sql @@ -0,0 +1,27 @@ +ALTER TABLE vn.supplier + CHANGE companySize companySize enum('small','medium','big') CHARACTER SET utf8mb3 + COLLATE utf8mb3_general_ci DEFAULT NULL NULL AFTER stamp, + ADD geoFk int(11) DEFAULT NULL NULL AFTER companySize, + ADD CONSTRAINT supplier_zoneGeo_FK FOREIGN KEY (geoFk) + REFERENCES vn.zoneGeo(id) ON DELETE RESTRICT ON UPDATE CASCADE; + +CREATE OR REPLACE TEMPORARY TABLE tmp.tSupplierGeo + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT s.id, p.geoFk + FROM vn.supplier s + JOIN vn.town t ON t.provinceFk = s.provinceFk + JOIN vn.postCode p ON p.townFk = t.id + AND (p.code = s.postCode OR s.postCode IS NULL) + LEFT JOIN vn.supplierAddress sad ON sad.supplierFk = s.id + JOIN vn.zoneGeo zg ON zg.id = p.geoFk + GROUP BY s.id + ORDER BY (s.city SOUNDS LIKE t.`name`) DESC, + (p.code = s.postCode) DESC, + (p.code = sad.postalCode) DESC; + +UPDATE vn.supplier s + JOIN tmp.tSupplierGeo tsg ON tsg.id = s.id + SET s.geoFk = tsg.geoFk; + +DROP TEMPORARY TABLE tmp.tSupplierGeo; diff --git a/db/versions/11347-redErica/00-firstScript.sql b/db/versions/11347-redErica/00-firstScript.sql new file mode 100644 index 000000000..5da1d6096 --- /dev/null +++ b/db/versions/11347-redErica/00-firstScript.sql @@ -0,0 +1,9 @@ +DROP TABLE IF EXISTS vn.saySimpleConfig; + +CREATE TABLE vn.saySimpleConfig( + id INT AUTO_INCREMENT PRIMARY KEY, + url VARCHAR(255) NOT NULL, + defaultChannel VARCHAR(128) +); + +ALTER TABLE vn.saySimpleCountry MODIFY COLUMN channel VARCHAR(128); \ No newline at end of file diff --git a/db/versions/11348-bronzeCamellia/00-firstScript.sql b/db/versions/11348-bronzeCamellia/00-firstScript.sql new file mode 100644 index 000000000..fa466f1a4 --- /dev/null +++ b/db/versions/11348-bronzeCamellia/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.clientObservation MODIFY COLUMN observationTypeFk tinyint(3) unsigned DEFAULT 4 NOT NULL; +UPDATE vn.clientObservation SET observationTypeFk=4 WHERE observationTypeFk=0; diff --git a/db/versions/11349-azureBamboo/00-firstScript.sql b/db/versions/11349-azureBamboo/00-firstScript.sql new file mode 100644 index 000000000..09c919b79 --- /dev/null +++ b/db/versions/11349-azureBamboo/00-firstScript.sql @@ -0,0 +1,7 @@ + + +UPDATE salix.ACL + SET principalId = 'deliveryAssistant' +WHERE model = 'Ticket' + AND property = 'updateAttributes' + AND principalId = "delivery"; diff --git a/db/versions/11350-silverArborvitae/00-firstScript.sql b/db/versions/11350-silverArborvitae/00-firstScript.sql new file mode 100644 index 000000000..b5e87133e --- /dev/null +++ b/db/versions/11350-silverArborvitae/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.shelvingLog + MODIFY COLUMN changedModel enum('Shelving', 'ItemShelving') CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT 'Shelving' NOT NULL; diff --git a/db/versions/11351-bronzeMedeola/00-firstScript.sql b/db/versions/11351-bronzeMedeola/00-firstScript.sql new file mode 100644 index 000000000..c94447a89 --- /dev/null +++ b/db/versions/11351-bronzeMedeola/00-firstScript.sql @@ -0,0 +1,2 @@ + +ALTER TABLE vn.itemConfig ADD defaultPackingTypeFk VARCHAR(1) DEFAULT 'H' NULL; diff --git a/db/versions/11353-wheatCymbidium/00-firstScript.sql b/db/versions/11353-wheatCymbidium/00-firstScript.sql new file mode 100644 index 000000000..557ffab9e --- /dev/null +++ b/db/versions/11353-wheatCymbidium/00-firstScript.sql @@ -0,0 +1,15 @@ + + +USE vn; + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES('RouteAction', 'find', 'READ', 'ALLOW', 'ROLE', 'delivery'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES('RouteComplement', 'find', 'READ', 'ALLOW', 'ROLE', 'delivery'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES('RouteComplement', 'create', 'WRITE', 'ALLOW', 'ROLE', 'delivery'); + +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) +VALUES('RouteComplement', 'deleteById', 'WRITE', 'ALLOW', 'ROLE', 'delivery'); \ No newline at end of file diff --git a/db/versions/11354-aquaMastic/00-firstScript.sql b/db/versions/11354-aquaMastic/00-firstScript.sql new file mode 100644 index 000000000..dda3f4752 --- /dev/null +++ b/db/versions/11354-aquaMastic/00-firstScript.sql @@ -0,0 +1,2 @@ +RENAME TABLE vn.workerTimeControlParams TO vn.workerTimeControlParams__; +ALTER TABLE vn.workerTimeControlParams__ COMMENT='@deprecated 2024-11-19'; \ No newline at end of file diff --git a/db/versions/11355-pinkMedeola/00-firstScript.sql b/db/versions/11355-pinkMedeola/00-firstScript.sql new file mode 100644 index 000000000..fc89b386c --- /dev/null +++ b/db/versions/11355-pinkMedeola/00-firstScript.sql @@ -0,0 +1,3 @@ +-- Place your SQL code here +INSERT IGNORE INTO vn.saySimpleConfig (url, defaultChannel) + VALUES ('https://verdnatura.saysimple.io/start-conversation', 1320); \ No newline at end of file diff --git a/db/versions/11357-whiteGerbera/00-firstScript.sql b/db/versions/11357-whiteGerbera/00-firstScript.sql new file mode 100644 index 000000000..c10ec4d26 --- /dev/null +++ b/db/versions/11357-whiteGerbera/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.travel ADD IF NOT EXISTS isRaid tinyint(1) DEFAULT 0 NOT NULL COMMENT 'Redada'; + +ALTER TABLE vn.travel MODIFY COLUMN daysInForward int(10) unsigned DEFAULT NULL + COMMENT 'Cuando es una redada, indica el número de días que se añadirán a la fecha de hoy para establecer el landed. NULL si no es una redada'; diff --git a/loopback/common/methods/vn-model/printService.js b/loopback/common/methods/vn-model/printService.js index 12a6a67cc..ed784229b 100644 --- a/loopback/common/methods/vn-model/printService.js +++ b/loopback/common/methods/vn-model/printService.js @@ -2,7 +2,7 @@ const {Report, Email} = require('vn-print'); module.exports = Self => { Self.printReport = async function(ctx, id, reportName) { - const args = Object.assign({}, ctx.args); + const args = Object.assign({id}, ctx.args); const params = {lang: ctx.req.getLocale()}; delete args.ctx; diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 4ad3f76e2..6756db37d 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -223,7 +223,6 @@ "Shelving not valid": "Shelving not valid", "printerNotExists": "The printer does not exist", "There are not picking tickets": "There are not picking tickets", - "ticketCommercial": "The ticket {{ ticket }} for the salesperson {{ salesMan }} is in preparation. (automatically generated message)", "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", @@ -242,8 +241,10 @@ "The maximum height of the wagon is 200cm": "The maximum height of the wagon is 200cm", "The quantity claimed cannot be greater than the quantity of the line": "The quantity claimed cannot be greater than the quantity of the line", "There are tickets for this area, delete them first": "There are tickets for this area, delete them first", - "ticketLostExpedition": "The ticket [{{ticketId}}]({{{ticketUrl}}}) has the following lost expedition:{{ expeditionId }}", - "null": "null", + "You do not have permission to modify the booked field": "You do not have permission to modify the booked field", "Invalid or expired verification code": "Invalid or expired verification code", - "Payment method is required": "Payment method is required" -} \ No newline at end of file + "ticketLostExpedition": "The ticket [{{ticketId}}]({{{ticketUrl}}}) has the following lost expedition:{{ expeditionId }}", + "The raid information is not correct": "The raid information is not correct", + "Payment method is required": "Payment method is required", + "Sales already moved": "Sales already moved" +} diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 37976c0ea..0b10d4702 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -359,7 +359,6 @@ "This workCenter is already assigned to this agency": "Este centro de trabajo ya está asignado a esta agencia", "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", "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", @@ -386,6 +385,10 @@ "type cannot be blank": "Se debe rellenar el tipo", "There are tickets for this area, delete them first": "Hay tickets para esta sección, borralos primero", "There is no company associated with that warehouse": "No hay ninguna empresa asociada a ese almacén", + "You do not have permission to modify the booked field": "No tienes permisos para modificar el campo contabilizada", "ticketLostExpedition": "El ticket [{{ticketId}}]({{{ticketUrl}}}) tiene la siguiente expedición perdida:{{ expeditionId }}", - "The web user's email already exists": "El correo del usuario web ya existe" -} \ No newline at end of file + "The web user's email already exists": "El correo del usuario web ya existe", + "Sales already moved": "Ya han sido transferidas", + "The raid information is not correct": "La información de la redada no es correcta" +} + diff --git a/loopback/locale/fr.json b/loopback/locale/fr.json index 0e876f89c..9941358be 100644 --- a/loopback/locale/fr.json +++ b/loopback/locale/fr.json @@ -362,8 +362,9 @@ "The invoices have been created but the PDFs 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é", "Cannot send mail": "Impossible d'envoyer le mail", - "Original invoice not found": "Facture originale introuvable", - "The quantity claimed cannot be greater than the quantity of the line": "Le montant réclamé ne peut pas être supérieur au montant de la ligne", + "Original invoice not found": "Facture originale introuvable", + "The quantity claimed cannot be greater than the quantity of the line": "Le montant réclamé ne peut pas être supérieur au montant de la ligne", + "You do not have permission to modify the booked field": "Vous n'avez pas la permission de modifier le champ comptabilisé", "ticketLostExpedition": "Le ticket [{{ticketId}}]({{{ticketUrl}}}) a l'expédition perdue suivante : {{expeditionId}}", "The web user's email already exists": "L'email de l'internaute existe déjà" -} \ No newline at end of file +} diff --git a/loopback/locale/pt.json b/loopback/locale/pt.json index e08336273..e84b30f3d 100644 --- a/loopback/locale/pt.json +++ b/loopback/locale/pt.json @@ -366,4 +366,4 @@ "The quantity claimed cannot be greater than the quantity of the line": "O valor reclamado não pode ser superior ao valor da linha", "ticketLostExpedition": "O ticket [{{ticketId}}]({{{ticketUrl}}}) tem a seguinte expedição perdida: {{expeditionId}}", "The web user's email already exists": "O e-mail do utilizador da web já existe." -} \ No newline at end of file +} diff --git a/modules/account/back/locale/vn-user/en.yml b/modules/account/back/locale/vn-user/en.yml index 51de7c40d..f911ee1eb 100644 --- a/modules/account/back/locale/vn-user/en.yml +++ b/modules/account/back/locale/vn-user/en.yml @@ -15,7 +15,5 @@ columns: image: image hasGrant: has grant userFk: user - recoverPass: recover password role: role - sync: pending sync lastPassChange: password changed diff --git a/modules/account/back/locale/vn-user/es.yml b/modules/account/back/locale/vn-user/es.yml index 85e8bc0dc..c05dd872c 100644 --- a/modules/account/back/locale/vn-user/es.yml +++ b/modules/account/back/locale/vn-user/es.yml @@ -15,7 +15,5 @@ columns: image: imagen hasGrant: puede delegar userFk: usuario - recoverPass: recuperar contraseña role: rol - sync: Pendiente de sincronizar lastPassChange: contraseña modificada diff --git a/modules/client/back/models/client-observation.json b/modules/client/back/models/client-observation.json index 86351862d..1d906420a 100644 --- a/modules/client/back/models/client-observation.json +++ b/modules/client/back/models/client-observation.json @@ -55,7 +55,7 @@ "relation": "user", "scope": { "fields": [ - "nickname" + "name" ] } } diff --git a/modules/entry/back/locale/entry/en.yml b/modules/entry/back/locale/entry/en.yml index ab8c0fd1c..6bc2333e6 100644 --- a/modules/entry/back/locale/entry/en.yml +++ b/modules/entry/back/locale/entry/en.yml @@ -9,6 +9,7 @@ columns: notes: notes isConfirmed: confirmed isVirtual: virtual + isRaid: raid commission: commission isOrdered: price3 created: created diff --git a/modules/entry/back/locale/entry/es.yml b/modules/entry/back/locale/entry/es.yml index 18bf1ca33..a892b05d2 100644 --- a/modules/entry/back/locale/entry/es.yml +++ b/modules/entry/back/locale/entry/es.yml @@ -9,6 +9,7 @@ columns: notes: notas isConfirmed: confirmado isVirtual: virtual + isRaid: redada commission: comisión isOrdered: pedida created: creado diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index a5c236fe4..d7740dd4e 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -194,6 +194,7 @@ module.exports = Self => { e.evaNotes observation, e.isConfirmed, e.isOrdered, + t.isRaid, t.daysInForward, e.commission, e.created, diff --git a/modules/entry/back/methods/entry/getEntry.js b/modules/entry/back/methods/entry/getEntry.js index 4612de9a5..92be9a9dd 100644 --- a/modules/entry/back/methods/entry/getEntry.js +++ b/modules/entry/back/methods/entry/getEntry.js @@ -49,8 +49,8 @@ module.exports = Self => { 'isReceived', 'isDelivered', 'ref', - 'daysInForward', - ], + 'isRaid', + 'daysInForward'], include: [ { relation: 'agency', diff --git a/modules/entry/back/methods/stock-bought/getStockBought.js b/modules/entry/back/methods/stock-bought/getStockBought.js index c1f99c496..9768b58e7 100644 --- a/modules/entry/back/methods/stock-bought/getStockBought.js +++ b/modules/entry/back/methods/stock-bought/getStockBought.js @@ -6,6 +6,9 @@ module.exports = Self => { arg: 'workerFk', type: 'number', description: 'The id for a buyer', + }, { + arg: 'filter', + type: 'object', }, { arg: 'dated', @@ -23,7 +26,7 @@ module.exports = Self => { } }); - Self.getStockBought = async(workerFk, dated = Date.vnNew()) => { + Self.getStockBought = async(workerFk, filter, dated = Date.vnNew()) => { const models = Self.app.models; const today = Date.vnNew(); dated.setHours(0, 0, 0, 0); @@ -31,7 +34,7 @@ module.exports = Self => { await models.StockBought.rawSql(`CALL vn.stockBought_calculate(?)`, [dated]); - const filter = { + const defaultFilter = { where: {dated}, include: [ { @@ -53,6 +56,6 @@ module.exports = Self => { if (workerFk) filter.where.workerFk = workerFk; - return models.StockBought.find(filter); + return models.StockBought.find({...filter, ...defaultFilter}); }; }; diff --git a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js index d5f712edf..723e04cb9 100644 --- a/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js +++ b/modules/entry/back/methods/stock-bought/getStockBoughtDetail.js @@ -1,3 +1,4 @@ +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; module.exports = Self => { Self.remoteMethod('getStockBoughtDetail', { description: 'Returns the detail of stock bought for a given date and a worker', @@ -12,6 +13,9 @@ module.exports = Self => { type: 'string', description: 'The date to filter', required: true, + }, { + arg: 'filter', + type: 'object', } ], returns: { @@ -24,11 +28,10 @@ module.exports = Self => { } }); - Self.getStockBoughtDetail = async(workerFk, dated) => { - const models = Self.app.models; + Self.getStockBoughtDetail = async(workerFk, dated, filter, options) => { + const conn = Self.dataSource.connector; const myOptions = {}; let tx; - let result; if (typeof options == 'object') Object.assign(myOptions, options); @@ -39,14 +42,19 @@ module.exports = Self => { } try { - await models.StockBought.rawSql(`CALL vn.item_calculateStock(?)`, [dated], myOptions); - result = await Self.rawSql( + const stmts = []; + stmts.push(new ParameterizedSQL(`CALL vn.item_calculateStock(?)`, [dated])); + + const query = new ParameterizedSQL( `SELECT b.entryFk entryFk, i.id itemFk, i.name itemName, ti.quantity, - ROUND((ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) - / (vc.trolleyM3 * 1000000),1) volume, + ROUND((ac.conversionCoefficient * + (ti.quantity / b.packing) * + buy_getVolume(b.id) + ) / (vc.trolleyM3 * 1000000), + 2) volume, b.packagingFk packagingFk, b.packing FROM tmp.item ti @@ -61,11 +69,17 @@ module.exports = Self => { JOIN volumeConfig vc WHERE ic.display AND w.id = ?`, - [workerFk], myOptions + [workerFk] ); - await Self.rawSql(`DROP TEMPORARY TABLE tmp.item, tmp.buyUltimate;`, [], myOptions); + + stmts.push(query.merge(conn.makeSuffix(filter))); + + stmts.push(new ParameterizedSQL(`DROP TEMPORARY TABLE tmp.item, tmp.buyUltimate`)); + + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql, myOptions); if (tx) await tx.commit(); - return result; + return result[1]; } catch (e) { await tx.rollback(); throw e; diff --git a/modules/entry/back/models/entry.js b/modules/entry/back/models/entry.js index 8ca79f531..593f3fdcc 100644 --- a/modules/entry/back/models/entry.js +++ b/modules/entry/back/models/entry.js @@ -1,3 +1,4 @@ +const UserError = require('vn-loopback/util/user-error'); const LoopBackContext = require('loopback-context'); module.exports = Self => { require('../methods/entry/filter')(Self); @@ -18,11 +19,20 @@ module.exports = Self => { const changes = ctx.data || ctx.instance; const orgData = ctx.currentInstance; + const loopBackContext = LoopBackContext.getCurrentContext(); + const accessToken = {req: loopBackContext.active}; + const hasChanges = orgData && changes; + + const isBookedChanged = changes.isBooked !== undefined && orgData.isBooked !== changes.isBooked; + + if (isBookedChanged) { + const canEditIsBooked = await Self.app.models.ACL.checkAccessAcl(accessToken, 'Entry', 'isBooked', 'READ'); + if (!canEditIsBooked) + throw new UserError('You do not have permission to modify the booked field'); + } const observation = changes.observation || orgData.observation; - const hasChanges = orgData && changes; - const observationChanged = hasChanges - && orgData.observation != observation; + const observationChanged = hasChanges && orgData.observation != observation; if (observationChanged) { let tx; @@ -37,8 +47,7 @@ module.exports = Self => { } try { - const loopbackContext = LoopBackContext.getCurrentContext(); - const userId = loopbackContext.active.accessToken.userId; + const userId = loopBackContext.active.accessToken.userId; const id = changes.id || orgData.id; const entry = await Self.app.models.Entry.findById(id, null, myOptions); await entry.updateAttribute('observationEditorFk', userId, myOptions); diff --git a/modules/entry/back/models/specs/entry.spec.js b/modules/entry/back/models/specs/entry.spec.js new file mode 100644 index 000000000..15a8202c4 --- /dev/null +++ b/modules/entry/back/models/specs/entry.spec.js @@ -0,0 +1,97 @@ +const {models} = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); + +describe('entry_isEditable trigger', () => { + const activeCtx = { + accessToken: {userId: 5}, + http: { + req: { + headers: {origin: 'http://localhost'} + } + } + }; + const ctx = {req: activeCtx}; + const entryId = 1; + let tx; + let options; + let entry; + + beforeEach(async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({active: ctx.req}); + tx = await models.Entry.beginTransaction({}); + options = {transaction: tx}; + + entry = await models.Entry.findById(entryId, null, options); + }); + + afterEach(async() => { + await tx.rollback(); + }); + + async function prepareEntry(isBooked, typeFk) { + let newCreated = Date.vnNew(); + await entry.updateAttributes({isBooked, typeFk}, options); + await entry.updateAttributes({dated: newCreated}, options); + } + + it('should throw an error when entry is booked and typeFk is null', async() => { + let error; + try { + await prepareEntry(true, null); + } catch (e) { + error = e; + } + + expect(error.message).toContain(`Entry ${entryId} is not editable`); + }); + + it('should throw an error when entry is booked and typeFk is not informal', async() => { + let error; + try { + const type = await models.EntryType.findOne({where: {isInformal: false}}, options); + await prepareEntry(true, type.code); + } catch (e) { + error = e; + } + + expect(error.message).toContain(`Entry ${entryId} is not editable`); + }); + + it('should not throw an error when entry is booked and typeFk is informal', async() => { + let error; + try { + const type = await models.EntryType.findOne({where: {isInformal: true}}, options); + await prepareEntry(true, type.code); + } catch (e) { + error = e; + } + + expect(error).toBeUndefined(); + }); + + it('should not throw an error when entry is not booked', async() => { + let error; + try { + const type = await models.EntryType.findOne({}, options); + await prepareEntry(false, type.code); + } catch (e) { + error = e; + } + + expect(error).toBeUndefined(); + }); + + it('should not throw an error when @isModeInventory is true', async() => { + let error; + try { + await models.Application.rawSql('SET @isModeInventory = TRUE;', null, options); + await prepareEntry(true, null); + } catch (e) { + error = e; + } finally { + await models.Application.rawSql('SET @isModeInventory = FALSE;', null, options); + } + + expect(error).toBeUndefined(); + }); +}); diff --git a/modules/entry/front/descriptor/index.html b/modules/entry/front/descriptor/index.html index 40625a4d5..957bcafb5 100644 --- a/modules/entry/front/descriptor/index.html +++ b/modules/entry/front/descriptor/index.html @@ -30,7 +30,7 @@ + ng-if="$ctrl.entryData.travel.isRaid">