diff --git a/db/changes/10080-september/00-catalog_calculate.sql b/db/changes/10080-september/00-catalog_calculate.sql deleted file mode 100644 index 4ddb79274..000000000 --- a/db/changes/10080-september/00-catalog_calculate.sql +++ /dev/null @@ -1,117 +0,0 @@ -DROP procedure IF EXISTS `vn`.`catalog_calculate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`catalog_calculate`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN -/** - * Calcula los articulos disponibles y sus precios - * - * @table tmp.item(itemFk) Listado de artículos a calcular - * @param vLanded Fecha de recepcion de mercancia - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, - * item, size, stems, category, inkFk, image, origin, price) - * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) - * @return tmp.ticketComponent - * @return tmp.ticketComponentPrice - * @return tmp.zoneGetShipped - - **/ - - DECLARE vAvailableCalc INT; - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouseFk SMALLINT; - DECLARE vZoneFk INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establece los almacenes y las fechas que van a entrar al disponible - - SELECT clientFk INTO vClient - FROM address WHERE id = vAddressFk; - - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buyFk` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT '0', - KEY `itemFk` (`itemFk`), - KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH - ) ENGINE=MEMORY DEFAULT CHARSET=utf8; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL buyUltimate (vWarehouseFk, vShipped); - - INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) - SELECT vWarehouseFk, - i.item_id, - IFNULL(i.available, 0), - bu.buyFk - FROM `cache`.available i - JOIN tmp.item br ON br.itemFk = i.item_id - LEFT JOIN item it ON it.id = i.item_id - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id - WHERE i.calc_id = vAvailableCalc - AND it.id != 100 - AND i.available > 0; - - DROP TEMPORARY TABLE tmp.buyUltimate; - END LOOP; - - CLOSE cTravelTree; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem - ENGINE = MEMORY - SELECT - b.itemFk, - SUM(b.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, - i.image, - o.code origin, - bl.price, - bl.priceKg - FROM tmp.ticketLot b - JOIN item i ON b.itemFk = i.id - LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible - JOIN origin o ON o.id = i.originFk - JOIN ( - SELECT MIN(price) price, itemFk, priceKg - FROM tmp.ticketComponentPrice - GROUP BY itemFk - ) bl ON bl.itemFk = b.itemFk - GROUP BY b.itemFk; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/00-address_getGeo.sql b/db/changes/10081-agency/00-address_getGeo.sql deleted file mode 100644 index fca55dfd2..000000000 --- a/db/changes/10081-agency/00-address_getGeo.sql +++ /dev/null @@ -1,27 +0,0 @@ - -DROP FUNCTION IF EXISTS `vn`.`address_getGeo`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`address_getGeo` (vSelf INT) - RETURNS INT - DETERMINISTIC -BEGIN -/** - * Returns the geo for the passed address. - * - * @param vSelf The address id - * @return The geo id - */ - DECLARE vGeoFk INT; - - 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 - WHERE a.id = vSelf - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - RETURN vGeoFk; -END$$ -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone.sql b/db/changes/10081-agency/00-zone.sql deleted file mode 100644 index 74e482c4c..000000000 --- a/db/changes/10081-agency/00-zone.sql +++ /dev/null @@ -1,56 +0,0 @@ -USE `vn`; - -CREATE TABLE `vn`.`zoneWarehouse` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `zoneFk` int(11) NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`), - KEY `warehouseFk` (`warehouseFk`), - CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE/*, -CONSTRAINT `zoneWarehouse_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE*/ -) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; - -CREATE TABLE `vn`.`zoneEvent` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `zoneFk` int(11) NOT NULL, - `from` date DEFAULT NULL, - `to` date DEFAULT NULL, - `weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL, - `hour` datetime DEFAULT NULL, - `travelingDays` int(11) DEFAULT NULL, - `price` decimal(10,2) DEFAULT NULL, - `bonus` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `zoneFk` (`zoneFk`), - CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8; - -ALTER TABLE `vn`.`zoneEvent` - ADD COLUMN `type` ENUM('day', 'indefinitely', 'range') NOT NULL AFTER `zoneFk`, - ADD COLUMN `dated` DATE NULL DEFAULT NULL AFTER `type`, - CHANGE COLUMN `from` `started` DATE NULL DEFAULT NULL , - CHANGE COLUMN `to` `ended` DATE NULL DEFAULT NULL ; - -CREATE TABLE `vn`.`zoneExclusion` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `zoneFk` int(11) NOT NULL, - `day` date NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `zoneFk_2` (`zoneFk`,`day`), - KEY `zoneFk` (`zoneFk`), - CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -ALTER TABLE `vn`.`zone` -DROP FOREIGN KEY `fk_zone_1`; -ALTER TABLE `vn`.`zone` -CHANGE COLUMN `warehouseFk` `warehouseFk` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ; -ALTER TABLE `vn`.`zone` -ADD CONSTRAINT `fk_zone_1` - FOREIGN KEY (`warehouseFk`) - REFERENCES `vn`.`warehouse` (`id`) - ON DELETE NO ACTION - ON UPDATE CASCADE; - -ALTER TABLE `vn`.`zoneExclusion` - CHANGE COLUMN `day` `dated` DATE NOT NULL ; diff --git a/db/changes/10081-agency/00-zone_getAvailable.sql b/db/changes/10081-agency/00-zone_getAvailable.sql deleted file mode 100644 index d24816e6e..000000000 --- a/db/changes/10081-agency/00-zone_getAvailable.sql +++ /dev/null @@ -1,16 +0,0 @@ - -DROP PROCEDURE IF EXISTS `vn`.`zone_getAvailable`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getAvailable`(vAddress INT, vLanded DATE) -BEGIN - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded); - - SELECT * FROM tmp.zoneOption; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone_getEvents.sql b/db/changes/10081-agency/00-zone_getEvents.sql deleted file mode 100644 index be50f602d..000000000 --- a/db/changes/10081-agency/00-zone_getEvents.sql +++ /dev/null @@ -1,52 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getEvents`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`( - vProvinceFk INT, - vPostCode VARCHAR(255), - vAgencyModeFk INT) -BEGIN -/** - * Returns available events for the passed province/postcode and agency. - * - * @param vAgencyModeFk The agency mode id - * @param vProvinceFk The province id - * @param vPostCode The postcode or %NULL to use the province - */ - DECLARE vGeoFk INT; - - IF vPostCode IS NOT NULL THEN - SELECT p.geoFk INTO vGeoFk - FROM postCode p - JOIN town t ON t.id = p.townFk - WHERE p.`code` = vPostCode - AND t.provinceFk = vProvinceFk; - ELSE - SELECT geoFk INTO vGeoFk - FROM province - WHERE id = vProvinceFk; - END IF; - - CALL zone_getFromGeo(vGeoFk); - - IF vAgencyModeFk IS NOT NULL THEN - DELETE t FROM tmp.zone t - JOIN zone z ON z.id = t.id - WHERE z.agencyModeFk != vAgencyModeFk; - END IF; - - SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays - FROM tmp.zone t - JOIN zoneEvent e ON e.zoneFk = t.id; - - SELECT e.zoneFk, e.dated - FROM tmp.zone t - JOIN zoneExclusion e ON e.zoneFk = t.id; - - DROP TEMPORARY TABLE tmp.zone; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone_getFromGeo.sql b/db/changes/10081-agency/00-zone_getFromGeo.sql deleted file mode 100644 index 244c73556..000000000 --- a/db/changes/10081-agency/00-zone_getFromGeo.sql +++ /dev/null @@ -1,58 +0,0 @@ - -DROP PROCEDURE IF EXISTS `vn`.`zone_getFromGeo`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getFromGeo`(vGeoFk INT) -BEGIN -/** - * Returns all zones which have the passed geo included. - * - * @param vGeoFk The geo id - * @return tmp.zone(id) The list of zones - */ - DECLARE vChildFk INT DEFAULT vGeoFk; - DECLARE vParentFk INT; - DECLARE vLevel INT DEFAULT 1; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT vGeoFk id, vLevel `level`; - - myLoop: LOOP - SELECT parentFk INTO vParentFk - FROM zoneGeo - WHERE id = vChildFk; - - SET vChildFk = vParentFk; - SET vLevel = vLevel + 1; - - INSERT IGNORE INTO tNodes - SELECT vChildFk, vLevel - FROM DUAL - WHERE vChildFk IS NOT NULL; - - IF ROW_COUNT() = 0 THEN - LEAVE myLoop; - END IF; - END LOOP; - - DROP TEMPORARY TABLE IF EXISTS tmp.zone; - CREATE TEMPORARY TABLE tmp.zone - (INDEX (id)) - ENGINE = MEMORY - SELECT id FROM ( - SELECT zoneFk id, isIncluded - FROM ( - SELECT i.zoneFk, i.isIncluded - FROM tNodes n - JOIN zoneIncluded i ON i.geoFk = n.id - ORDER BY zoneFk, n.`level` - ) t - GROUP BY id HAVING isIncluded - ) t; - - DROP TEMPORARY TABLE tNodes; -END$$ -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone_getLeaves.sql b/db/changes/10081-agency/00-zone_getLeaves.sql deleted file mode 100755 index ee95b3315..000000000 --- a/db/changes/10081-agency/00-zone_getLeaves.sql +++ /dev/null @@ -1,88 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`zone_getLeaves`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255) -) -BEGIN - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE 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 - DROP TEMPORARY TABLE IF EXISTS tChilds; - CREATE TEMPORARY TABLE tChilds - ENGINE = MEMORY - SELECT id FROM tNodes; - - DROP TEMPORARY TABLE IF EXISTS tParents; - CREATE TEMPORARY TABLE tParents - 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 ROW_COUNT() = 0 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 !vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - SELECT g.id, - g.`name`, - g.parentFk, - g.sons, - isIncluded selected - 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 depth, selected DESC, `name`; - - DROP TEMPORARY TABLE tNodes; -END$$ -DELIMITER ; diff --git a/db/changes/10081-agency/01-zone_getAgency.sql b/db/changes/10081-agency/01-zone_getAgency.sql deleted file mode 100644 index 3d0c86866..000000000 --- a/db/changes/10081-agency/01-zone_getAgency.sql +++ /dev/null @@ -1,42 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getAgency`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(vAddress INT, vLanded DATE) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha - * y dirección pasadas. - * - * @param vAddress Id de dirección de envío, %NULL si es recogida - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; - CREATE TEMPORARY TABLE tmp.zoneGetAgency - (INDEX (agencyModeFk)) ENGINE = MEMORY - SELECT am.name agencyMode, - am.description, - z.agencyModeFk, - am.deliveryMethodFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - TRUE isIncluded, - zo.zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - GROUP BY agencyModeFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/01-zone_getFirstShipped.sql b/db/changes/10081-agency/01-zone_getFirstShipped.sql deleted file mode 100644 index 64e853a81..000000000 --- a/db/changes/10081-agency/01-zone_getFirstShipped.sql +++ /dev/null @@ -1,2 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getFirstShipped`; diff --git a/db/changes/10081-agency/01-zone_getLanded.sql b/db/changes/10081-agency/01-zone_getLanded.sql deleted file mode 100644 index a2bbe46a5..000000000 --- a/db/changes/10081-agency/01-zone_getLanded.sql +++ /dev/null @@ -1,40 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getLanded`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) -BEGIN -/** -* Devuelve una tabla temporal con el dia de recepcion para vShipped. -* -* @param vShipped Fecha de preparacion de mercancia -* @param vAddressFk Id de consignatario, %NULL para recogida -* @param vAgencyModeFk Id agencia -* @param vWarehouseFk vWarehouseFk -* @table tmp.zoneGetLanded Datos de recepción -*/ - - CALL zone_getFromGeo(address_getGeo(vAddressFk)); - CALL zone_getOptionsForLanding(vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - CREATE TEMPORARY TABLE tmp.zoneGetLanded - ENGINE = MEMORY - SELECT vWarehouseFk warehouseFk, - TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed, - zo.zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN zoneWarehouse zw ON zw.zoneFk = z.id - WHERE agencyModeFk = vAgencyModeFk - AND zw.warehouseFk = vWarehouseFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/01-zone_getShippedWarehouse.sql b/db/changes/10081-agency/01-zone_getShippedWarehouse.sql deleted file mode 100644 index 017b7d17c..000000000 --- a/db/changes/10081-agency/01-zone_getShippedWarehouse.sql +++ /dev/null @@ -1,41 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getShippedWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN -/** - * Devuelve la mínima fecha de envío para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - - CALL zone_getFromGeo(address_getGeo(vAddressFk)); - CALL zone_getOptionsForLanding(vLanded); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CREATE TEMPORARY TABLE tmp.zoneGetShipped - ENGINE = MEMORY - SELECT * FROM ( - SELECT zo.zoneFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - zw.warehouseFk, - z.agencyModeFk - FROM tmp.zoneOption zo - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - JOIN zone z ON z.id = zo.zoneFk - WHERE z.agencyModeFk = vAgencyModeFk - ORDER BY shipped) t - GROUP BY warehouseFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/01-zone_getWarehouse.sql b/db/changes/10081-agency/01-zone_getWarehouse.sql deleted file mode 100644 index 28478e2cc..000000000 --- a/db/changes/10081-agency/01-zone_getWarehouse.sql +++ /dev/null @@ -1,42 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha, - * dirección y almacén pasados. - * - * @param vAddress - * @param vWarehouse warehouse - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded); - - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, - am.deliveryMethodFk, - TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, - zw.warehouseFk, - z.id zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - WHERE zw.warehouseFk - GROUP BY z.agencyModeFk - ORDER BY agencyMode; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/02-zoneGetAgency.sql b/db/changes/10081-agency/02-zoneGetAgency.sql deleted file mode 100644 index 3a627ba5b..000000000 --- a/db/changes/10081-agency/02-zoneGetAgency.sql +++ /dev/null @@ -1,22 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`zoneGetAgency`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetAgency`(vAddress INT, vLanded DATE) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha - * y dirección pasadas. - * - * @param vAddress Id de dirección de envío, %NULL si es recogida - * @param vDate Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getAgency(vAddress,vLanded); -END$$ - -DELIMITER ; -; diff --git a/db/changes/10081-agency/02-zoneGetFirstShipped__.sql b/db/changes/10081-agency/02-zoneGetFirstShipped__.sql deleted file mode 100644 index 9483f309c..000000000 --- a/db/changes/10081-agency/02-zoneGetFirstShipped__.sql +++ /dev/null @@ -1,3 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`zoneGetFirstShipped`; diff --git a/db/changes/10081-agency/02-zoneGetLanded.sql b/db/changes/10081-agency/02-zoneGetLanded.sql deleted file mode 100644 index da8d8a9dd..000000000 --- a/db/changes/10081-agency/02-zoneGetLanded.sql +++ /dev/null @@ -1,20 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneGetLanded`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddress INT, vAgencyMode INT, vWarehouse INT) -BEGIN -/** -* Devuelve una tabla temporal con el dia de recepcion para vShipped. -* -* @param vShipped Fecha de preparacion de mercancia -* @param vAddress Id de consignatario, %NULL para recogida -* @param vAgencyMode Id agencia -* @table tmp.zoneGetLanded Datos de recepción -*/ - CALL zone_getLanded(vShipped,vAddress,vAgencyMode,vWarehouse); -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/02-zoneGetShipped.sql b/db/changes/10081-agency/02-zoneGetShipped.sql deleted file mode 100644 index 212eb94df..000000000 --- a/db/changes/10081-agency/02-zoneGetShipped.sql +++ /dev/null @@ -1,24 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneGetShipped`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) -BEGIN -/** - * OBSOLETO usar zone_getShippedWarehouse - * Devuelve la mínima fecha de envía para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql b/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql deleted file mode 100644 index 55f443054..000000000 --- a/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql +++ /dev/null @@ -1,20 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneGetShippedWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN -/** - * Devuelve la mínima fecha de envío para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/04-zone_getOptionsForLanding.sql b/db/changes/10081-agency/04-zone_getOptionsForLanding.sql deleted file mode 100644 index ae081f14b..000000000 --- a/db/changes/10081-agency/04-zone_getOptionsForLanding.sql +++ /dev/null @@ -1,67 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getOptionsForLanding`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE) -BEGIN -/** - * Gets computed options for the passed zones and delivery date. - * - * @table tmp.zones(id) The zones ids - * @param vLanded The delivery date - * @return tmp.zoneOption The computed options - */ - DECLARE vHour TIME DEFAULT TIME(NOW()); - - DROP TEMPORARY TABLE IF EXISTS tTemp; - CREATE TEMPORARY TABLE tTemp - ENGINE = MEMORY - SELECT t.id zoneFk, - IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, - IFNULL(e.travelingDays, z.travelingDays) travelingDays, - IFNULL(e.price, z.price) price, - IFNULL(e.bonus, z.bonus) bonus, - CASE - WHEN e.`type` = 'day' - THEN 1 - WHEN e.`type` = 'range' - THEN 2 - ELSE 3 - END specificity - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id - WHERE ( - e.`type` = 'day' - AND e.dated = vLanded - ) OR ( - e.`type` != 'day' - AND e.weekDays & (1 << WEEKDAY(vLanded)) - AND (e.`started` IS NULL OR vLanded >= e.`started`) - AND (e.`ended` IS NULL OR vLanded <= e.`ended`) - ); - - DELETE t FROM tTemp t - JOIN zoneExclusion e - ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded; - - DELETE FROM tTemp - WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE() - OR @shipped = CURDATE() AND vHour > `hour`; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; - CREATE TEMPORARY TABLE tmp.zoneOption - ENGINE = MEMORY - SELECT * - FROM ( - SELECT * FROM tTemp - ORDER BY zoneFk, specificity - ) t - GROUP BY zoneFk; - - DROP TEMPORARY TABLE tTemp; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/04-zone_getOptionsForShipment.sql b/db/changes/10081-agency/04-zone_getOptionsForShipment.sql deleted file mode 100644 index c631f8809..000000000 --- a/db/changes/10081-agency/04-zone_getOptionsForShipment.sql +++ /dev/null @@ -1,76 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getOptionsForShipment`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE) -BEGIN -/** - * Gets computed options for the passed zones and shipping date. - * - * @table tmp.zones(id) The zones ids - * @param vShipped The shipping date - * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options - */ - DROP TEMPORARY TABLE IF EXISTS tLandings; - CREATE TEMPORARY TABLE tLandings - (INDEX (eventFk)) - ENGINE = MEMORY - SELECT e.id eventFk, - @travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays, - TIMESTAMPADD(DAY, @travelingDays, vShipped) landed - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id; - - DROP TEMPORARY TABLE IF EXISTS tTemp; - CREATE TEMPORARY TABLE tTemp - ENGINE = MEMORY - SELECT t.id zoneFk, - IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, - IFNULL(e.price, z.price) price, - IFNULL(e.bonus, z.bonus) bonus, - CASE - WHEN e.`type` = 'day' - THEN 1 - WHEN e.`type` = 'range' - THEN 2 - ELSE 3 - END specificity, - l.travelingDays, - l.landed - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id - JOIN tLandings l ON l.eventFk = e.id - WHERE ( - e.`type` = 'day' - AND e.`dated` = l.landed - ) OR ( - e.`type` != 'day' - AND e.weekDays & (1 << WEEKDAY(l.landed)) - AND (e.`started` IS NULL OR l.landed >= e.`started`) - AND (e.`ended` IS NULL OR l.landed <= e.`ended`) - ); - - DELETE t FROM tTemp t - JOIN zoneExclusion e - ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; - CREATE TEMPORARY TABLE tmp.zoneOption - ENGINE = MEMORY - SELECT * - FROM ( - SELECT * FROM tTemp - ORDER BY zoneFk, specificity - ) t - GROUP BY zoneFk; - - DROP TEMPORARY TABLE - tTemp, - tLandings; -END$$ - -DELIMITER ; - diff --git a/db/changes/10090-iberflora/00-ACL.sql b/db/changes/10090-iberflora/00-ACL.sql deleted file mode 100644 index 3a20e3ecb..000000000 --- a/db/changes/10090-iberflora/00-ACL.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Claim', 'updateClaimAction', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'); diff --git a/db/changes/10090-iberflora/00-claimState.sql b/db/changes/10090-iberflora/00-claimState.sql deleted file mode 100644 index 7a964979b..000000000 --- a/db/changes/10090-iberflora/00-claimState.sql +++ /dev/null @@ -1,2 +0,0 @@ -UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '3'); -UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '5'); diff --git a/db/changes/10090-iberflora/00-component.sql b/db/changes/10090-iberflora/00-component.sql deleted file mode 100644 index fe5de47fc..000000000 --- a/db/changes/10090-iberflora/00-component.sql +++ /dev/null @@ -1,15 +0,0 @@ -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn`.`component` AS - SELECT - `t`.`Id_Componente` AS `id`, - `t`.`Componente` AS `name`, - `t`.`tarifa_componentes_series_id` AS `typeFk`, - `t`.`tarifa_class` AS `classRate`, - `t`.`tax` AS `tax`, - `t`.`is_renewable` AS `isRenewable`, - `t`.`code` AS `code` - FROM - `bi`.`tarifa_componentes` `t`; diff --git a/db/changes/10091-iberflora/00-department.sql b/db/changes/10091-iberflora/00-department.sql deleted file mode 100644 index 415879485..000000000 --- a/db/changes/10091-iberflora/00-department.sql +++ /dev/null @@ -1,2 +0,0 @@ - -UPDATE vn.department SET lft = NULL, rgt = NULL; diff --git a/db/changes/10091-iberflora/00-department_calcTree.sql b/db/changes/10091-iberflora/00-department_calcTree.sql deleted file mode 100644 index 5f518d2e2..000000000 --- a/db/changes/10091-iberflora/00-department_calcTree.sql +++ /dev/null @@ -1,37 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_calcTree`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTree`() -BEGIN -/** - * Calculates the #path, #lft, #rgt, #sons and #depth columns of - * the #department table. To build the tree, it uses the #parentFk - * column. - */ - DECLARE vIndex INT DEFAULT 0; - DECLARE vSons INT; - - DROP TEMPORARY TABLE IF EXISTS tNestedTree; - CREATE TEMPORARY TABLE tNestedTree - SELECT id, path, lft, rgt, depth, sons - FROM department LIMIT 0; - - SET max_sp_recursion_depth = 5; - CALL department_calcTreeRec(NULL, '/', 0, vIndex, vSons); - SET max_sp_recursion_depth = 0; - - UPDATE department z - JOIN tNestedTree t ON t.id = z.id - SET z.path = t.path, - z.lft = t.lft, - z.rgt = t.rgt, - z.depth = t.depth, - z.sons = t.sons; - - DROP TEMPORARY TABLE tNestedTree; -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-department_calcTreeRec.sql b/db/changes/10091-iberflora/00-department_calcTreeRec.sql deleted file mode 100644 index 1f24270e2..000000000 --- a/db/changes/10091-iberflora/00-department_calcTreeRec.sql +++ /dev/null @@ -1,75 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_calcTreeRec`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTreeRec`( - vSelf INT, - vPath VARCHAR(255), - vDepth INT, - INOUT vIndex INT, - OUT vSons INT -) -BEGIN -/** - * Calculates and sets the #path, #lft, #rgt, #sons and #depth - * columns for all children of the passed node. Once calculated - * the last node rgt index and the number of sons are returned. - * To update it's children, this procedure calls itself recursively - * for each one. - * - * @vSelf The node identifier - * @vPath The initial path - * @vDepth The initial depth - * @vIndex The initial lft index - * @vSons The number of direct sons - */ - DECLARE vChildFk INT; - DECLARE vLft INT; - DECLARE vMySons INT; - DECLARE vDone BOOL; - DECLARE vChildren CURSOR FOR - SELECT id FROM department - WHERE (vSelf IS NULL AND parentFk IS NULL) - OR (vSelf IS NOT NULL AND parentFk = vSelf); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - SET vSons = 0; - - OPEN vChildren; - myLoop: LOOP - SET vDone = FALSE; - FETCH vChildren INTO vChildFk; - - IF vDone THEN - LEAVE myLoop; - END IF; - - SET vIndex = vIndex + 1; - SET vLft = vIndex; - SET vSons = vSons + 1; - - CALL department_calcTreeRec( - vChildFk, - CONCAT(vPath, vChildFk, '/'), - vDepth + 1, - vIndex, - vMySons - ); - - SET vIndex = vIndex + 1; - - INSERT INTO tNestedTree - SET id = vChildFk, - path = vPath, - lft = vLft, - rgt = vIndex, - depth = vDepth, - sons = vMySons; - END LOOP; - CLOSE vChildren; -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-department_doCalc.sql b/db/changes/10091-iberflora/00-department_doCalc.sql deleted file mode 100644 index ba5c16c48..000000000 --- a/db/changes/10091-iberflora/00-department_doCalc.sql +++ /dev/null @@ -1,35 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_doCalc`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`() -proc: BEGIN -/** - * Recalculates the department tree. - */ - DECLARE vIsChanged BOOL; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('vn.department_doCalc'); - RESIGNAL; - END; - - IF !GET_LOCK('vn.department_doCalc', 0) THEN - LEAVE proc; - END IF; - - SELECT isChanged INTO vIsChanged - FROM department_recalc; - - IF vIsChanged THEN - UPDATE department_recalc SET isChanged = FALSE; - CALL vn.department_calcTree; - END IF; - - DO RELEASE_LOCK('vn.department_doCalc'); -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-department_getLeaves.sql b/db/changes/10091-iberflora/00-department_getLeaves.sql deleted file mode 100644 index 436f67dbf..000000000 --- a/db/changes/10091-iberflora/00-department_getLeaves.sql +++ /dev/null @@ -1,84 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_getLeaves`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_getLeaves`( - vParentFk INT, - vSearch VARCHAR(255) -) -BEGIN - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id FROM department LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id FROM department - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - END IF; - - IF vParentFk IS NULL THEN - DROP TEMPORARY TABLE IF EXISTS tChilds; - CREATE TEMPORARY TABLE tChilds - ENGINE = MEMORY - SELECT id FROM tNodes; - - DROP TEMPORARY TABLE IF EXISTS tParents; - CREATE TEMPORARY TABLE tParents - ENGINE = MEMORY - SELECT id FROM department LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM department g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF ROW_COUNT() = 0 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 !vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id FROM department - WHERE parentFk <=> vParentFk; - END IF; - - SELECT d.id, - d.`name`, - d.parentFk, - d.sons - FROM department d - JOIN tNodes n ON n.id = d.id - ORDER BY depth, `name`; - - DROP TEMPORARY TABLE tNodes; -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-route.sql b/db/changes/10091-iberflora/00-route.sql deleted file mode 100644 index 5d8b8de62..000000000 --- a/db/changes/10091-iberflora/00-route.sql +++ /dev/null @@ -1,10 +0,0 @@ -ALTER TABLE `vn`.`route` -ADD COLUMN `zoneFk` INT NULL AFTER `description`, -ADD INDEX `fk_route_1_idx` (`zoneFk` ASC); -; -ALTER TABLE `vn`.`route` -ADD CONSTRAINT `fk_route_1` - FOREIGN KEY (`zoneFk`) - REFERENCES `vn`.`zone` (`id`) - ON DELETE RESTRICT - ON UPDATE CASCADE; diff --git a/db/changes/10100-allSaints/00-ACL.sql b/db/changes/10100-allSaints/00-ACL.sql deleted file mode 100644 index 39b52df5d..000000000 --- a/db/changes/10100-allSaints/00-ACL.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('UserPhone', '*', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/10100-allSaints/00-travelLog.sql b/db/changes/10100-allSaints/00-travelLog.sql deleted file mode 100644 index fe9d03274..000000000 --- a/db/changes/10100-allSaints/00-travelLog.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE `vn`.`travelLog` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `originFk` int(10) unsigned NOT NULL, - `userFk` int(10) unsigned DEFAULT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text CHARACTER SET utf8, - `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `oldInstance` text COLLATE utf8_unicode_ci, - `newInstance` text COLLATE utf8_unicode_ci, - `changedModelId` int(11) DEFAULT NULL, - `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `originFk` (`originFk`), - KEY `userFk` (`userFk`), - CONSTRAINT `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn`.`travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/db/changes/10100-allSaints/00-upperGap.sql b/db/changes/10100-allSaints/00-upperGap.sql deleted file mode 100644 index 6554c47b4..000000000 --- a/db/changes/10100-allSaints/00-upperGap.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE `vn`.`packagingConfig` ( - `id` INT NOT NULL AUTO_INCREMENT, - `upperGap` INT NOT NULL, - PRIMARY KEY (`id`)); - -INSERT INTO `vn`.`packagingConfig` (`upperGap`) VALUES ('10'); diff --git a/db/changes/10100-allSaints/00-userLog.sql b/db/changes/10100-allSaints/00-userLog.sql deleted file mode 100644 index f6972796d..000000000 --- a/db/changes/10100-allSaints/00-userLog.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE `vn`.`userLog` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `originFk` int(10) unsigned NOT NULL, - `userFk` int(10) unsigned DEFAULT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text CHARACTER SET utf8, - `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `oldInstance` text COLLATE utf8_unicode_ci, - `newInstance` text COLLATE utf8_unicode_ci, - `changedModelId` int(11) DEFAULT NULL, - `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `originFk` (`originFk`), - KEY `userFk` (`userFk`), - CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/db/changes/10100-allSaints/00-userPhoneType.sql b/db/changes/10100-allSaints/00-userPhoneType.sql deleted file mode 100644 index 6bfedcc71..000000000 --- a/db/changes/10100-allSaints/00-userPhoneType.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE `vn`.`userPhoneType` ( - `code` VARCHAR(45) NOT NULL, - `description` VARCHAR(255) NULL, - PRIMARY KEY (`code`)); - - - -INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('businessPhone', 'Telefono de empresa del usuario'); -INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('personalPhone', 'Telefono personal del usuario'); diff --git a/db/changes/10100-allSaints/01-userPhone.sql b/db/changes/10100-allSaints/01-userPhone.sql deleted file mode 100644 index 54dfbeb26..000000000 --- a/db/changes/10100-allSaints/01-userPhone.sql +++ /dev/null @@ -1,23 +0,0 @@ -CREATE TABLE `vn`.`userPhone` ( - `id` INT NOT NULL AUTO_INCREMENT, - `userFk` INT(10) UNSIGNED NOT NULL, - `typeFk` VARCHAR(45) NOT NULL, - `phone` VARCHAR(25) NOT NULL, - PRIMARY KEY (`id`), - UNIQUE INDEX `UserFk_Phone` (`userFk` ASC, `typeFk` ASC, `phone` ASC)); - - -ALTER TABLE `vn`.`userPhone` -ADD CONSTRAINT `fgnTypeFk` - FOREIGN KEY (typeFk) - REFERENCES `vn`.`userPhoneType` (code) - ON DELETE RESTRICT - ON UPDATE CASCADE; - -ALTER TABLE `vn`.`userPhone` -ADD CONSTRAINT `fgnUserFk` - FOREIGN KEY (userFk) - REFERENCES `account`.`user` (id) - ON DELETE CASCADE - ON UPDATE CASCADE; - diff --git a/db/changes/10100-allSaints/02-catalog_componentCalculate.sql b/db/changes/10100-allSaints/02-catalog_componentCalculate.sql deleted file mode 100644 index 9d4df64c9..000000000 --- a/db/changes/10100-allSaints/02-catalog_componentCalculate.sql +++ /dev/null @@ -1,259 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `catalog_componentCalculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`( - vZoneFk INT, - vAddressFk INT, - vShipped DATE) -proc: BEGIN -/** - * Calcula los componentes de los articulos de tmp.ticketLot - * - * @param vZoneFk para calcular el transporte - * @param vAgencyModeFk Id del modo de agencia - * @param tmp.ticketLot (warehouseFk,available,itemFk,buyFk) - * - * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, - * packing, grouping, groupingMode, buyFk, typeFk) - * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) - */ - - DECLARE vClientFk INT; - DECLARE vGeneralInflationCoefficient INT DEFAULT 1; - DECLARE vMinimumDensityWeight INT DEFAULT 167; - DECLARE vBoxFreightItem INT DEFAULT 71; - DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; - DECLARE vSpecialPriceComponent INT DEFAULT 10; - DECLARE vDeliveryComponent INT DEFAULT 15; - DECLARE vRecoveryComponent INT DEFAULT 17; - DECLARE vSellByPacketComponent INT DEFAULT 22; - DECLARE vBuyValueComponent INT DEFAULT 28; - DECLARE vMarginComponent INT DEFAULT 29; - DECLARE vDiscountLastItemComponent INT DEFAULT 32; - DECLARE vExtraBaggedComponent INT DEFAULT 38; - DECLARE vManaAutoComponent INT DEFAULT 39; - - SELECT volume INTO vBoxVolume - FROM vn.packaging - WHERE id = '94'; - - SELECT clientFk INTO vClientFK - FROM address - WHERE id = vAddressFk; - - SET @rate2 := 0; - SET @rate3 := 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; - CREATE TEMPORARY TABLE tmp.ticketComponentCalculate - (PRIMARY KEY (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT - tl.itemFk, tl.warehouseFk, tl.available, - IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, - IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, - IFNULL(pf.rate3, 0) AS minPrice, - IFNULL(pf.packing, b.packing) packing, - IFNULL(pf.`grouping`, b.`grouping`) `grouping`, - ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, - i.typeFk, - IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping - FROM tmp.ticketLot tl - JOIN buy b ON b.id = tl.buyFk - JOIN item i ON i.id = tl.itemFk - JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk - LEFT JOIN ( - SELECT * FROM ( - SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk - FROM priceFixed pf - JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) - WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC - ) tpf - GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk - WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; - CREATE TEMPORARY TABLE tmp.ticketComponent ( - `warehouseFk` INT UNSIGNED NOT NULL, - `itemFk` INT NOT NULL, - `componentFk` INT UNSIGNED NOT NULL, - `cost` DECIMAL(10,4) NOT NULL, - INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), - UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vBuyValueComponent, - b.buyingValue + b.freightValue + b.packageValue + b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vMarginComponent, - tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; - CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY - SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk - FROM tmp.ticketComponent tc - GROUP BY tc.itemFk, warehouseFk; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) - FROM tmp.ticketComponentBase tcb - JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk - WHERE cr.recobro > 0.009; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto - FROM tmp.ticketComponentBase tcb - JOIN `client` c on c.id = vClientFk - JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador - WHERE ms.prices_modifier_activated - HAVING manaAuto <> 0; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, - tcb.itemFk, - cr.id, - GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) - FROM tmp.ticketComponentBase tcb - JOIN componentRate cr - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFK, - tcc.itemFk, - vDeliveryComponent, - vGeneralInflationCoefficient - * ROUND(( - i.compression - * r.cm3 - * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) - * IFNULL((z.price - z.bonus) - * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 - ) cost - FROM tmp.ticketComponentCalculate tcc - JOIN item i ON i.id = tcc.itemFk - JOIN zone z ON z.id = vZoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk - AND r.Id_Article = tcc.itemFk - HAVING cost <> 0; - - IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost - FROM tmp.ticketComponentCalculate tcc - JOIN vn.addressForPackaging ap - WHERE ap.addressFk = vAddressFk; - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; - CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY - SELECT * FROM tmp.ticketComponent; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - vSpecialPriceComponent, - sp.value - SUM(tcc.cost) sumCost - FROM tmp.ticketComponentCopy tcc - JOIN componentRate cr ON cr.id = tcc.componentFk - JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk - WHERE cr.classRate IS NULL - GROUP BY tcc.itemFk, tcc.warehouseFk - HAVING ABS(sumCost) > 0.001; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; - CREATE TEMPORARY TABLE tmp.ticketComponentSum - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate - FROM tmp.ticketComponent tc - JOIN componentRate cr ON cr.id = tc.componentFk - GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; - CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY - SELECT tcc.warehouseFk, - tcc.itemFk, - 1 rate, - IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 - AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 2 rate, - tcc.packing `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 - AND tcc.packing > 0 AND tcc.available >= tcc.packing) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 3 rate, - tcc.available `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 3) = 3 - GROUP BY tcs.warehouseFk, tcs.itemFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; - CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM tmp.ticketComponentRate ORDER BY price - ) t - GROUP BY itemFk, warehouseFk, `grouping`; - - DROP TEMPORARY TABLE - tmp.ticketComponentCalculate, - tmp.ticketComponentSum, - tmp.ticketComponentBase, - tmp.ticketComponentRate, - tmp.ticketComponentCopy; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/02-ticketCalculate__.sql b/db/changes/10100-allSaints/02-ticketCalculate__.sql deleted file mode 100644 index 37903f7c3..000000000 --- a/db/changes/10100-allSaints/02-ticketCalculate__.sql +++ /dev/null @@ -1,17 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`ticketCalculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculate__`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN --- OBSOLETO utilizar catalog_calculate - CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); -END$$ - -DELIMITER ; -; diff --git a/db/changes/10100-allSaints/03-available_calc.sql b/db/changes/10100-allSaints/03-available_calc.sql deleted file mode 100644 index 70416f5df..000000000 --- a/db/changes/10100-allSaints/03-available_calc.sql +++ /dev/null @@ -1,63 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `available_calc`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `available_calc`( - vDate DATE, - vAddress INT, - vAgencyMode INT) -BEGIN -/** - * Calculates the available for all available stores - * according to the given parameters. - * - * @param vDate The delivery date - * @param vAddress The delivery address id - * @param vAgencyMode The shipping agency - * @return tmp.availableCalc(calcFk) The available cache ids - */ - DECLARE vCalcFk INT; - DECLARE vShipment DATE; - DECLARE vWarehouse INT; - DECLARE vDone BOOL; - - DECLARE cWarehouses CURSOR FOR - SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - -- Establecemos los almacenes y las fechas que van a entrar al disponible - - CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode); - - DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; - CREATE TEMPORARY TABLE tmp.availableCalc( - calcFk INT UNSIGNED, - PRIMARY KEY (calcFk) - ) - ENGINE = MEMORY; - - OPEN cWarehouses; - - l: LOOP - SET vDone = FALSE; - FETCH cWarehouses INTO vWarehouse, vShipment; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment); - - INSERT IGNORE INTO tmp.availableCalc - SET calcFk = vCalcFk; - END LOOP; - - CLOSE cWarehouses; - DROP TEMPORARY TABLE tmp.zoneGetShipped; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/03-catalog_calculate.sql b/db/changes/10100-allSaints/03-catalog_calculate.sql deleted file mode 100644 index e6f4f7375..000000000 --- a/db/changes/10100-allSaints/03-catalog_calculate.sql +++ /dev/null @@ -1,119 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `catalog_calculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN -/** - * Calcula los articulos disponibles y sus precios - * - * @table tmp.item(itemFk) Listado de artículos a calcular - * @param vLanded Fecha de recepcion de mercancia - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, - * item, size, stems, category, inkFk, image, origin, price) - * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) - * @return tmp.ticketComponent - * @return tmp.ticketComponentPrice - * @return tmp.zoneGetShipped - - **/ - - DECLARE vAvailableCalc INT; - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouseFk SMALLINT; - DECLARE vZoneFk INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establece los almacenes y las fechas que van a entrar al disponible - - SELECT clientFk INTO vClient - FROM address WHERE id = vAddressFk; - - CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buyFk` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT '0', - KEY `itemFk` (`itemFk`), - KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH - ) ENGINE=MEMORY DEFAULT CHARSET=utf8; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL buyUltimate (vWarehouseFk, vShipped); - - INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) - SELECT vWarehouseFk, - i.item_id, - IFNULL(i.available, 0), - bu.buyFk - FROM `cache`.available i - JOIN tmp.item br ON br.itemFk = i.item_id - LEFT JOIN item it ON it.id = i.item_id - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id - WHERE i.calc_id = vAvailableCalc - AND it.id != 100 - AND i.available > 0; - - DROP TEMPORARY TABLE tmp.buyUltimate; - END LOOP; - - CLOSE cTravelTree; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem - ENGINE = MEMORY - SELECT - b.itemFk, - SUM(b.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, - i.image, - o.code origin, - bl.price, - bl.priceKg - FROM tmp.ticketLot b - JOIN item i ON b.itemFk = i.id - LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible - JOIN origin o ON o.id = i.originFk - JOIN ( - SELECT MIN(price) price, itemFk, priceKg - FROM tmp.ticketComponentPrice - GROUP BY itemFk - ) bl ON bl.itemFk = b.itemFk - GROUP BY b.itemFk; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/03-order_confirmWithUser.sql b/db/changes/10100-allSaints/03-order_confirmWithUser.sql deleted file mode 100644 index e7b4b2edb..000000000 --- a/db/changes/10100-allSaints/03-order_confirmWithUser.sql +++ /dev/null @@ -1,244 +0,0 @@ -USE `hedera`; -DROP procedure IF EXISTS `order_confirmWithUser`; - -DELIMITER $$ -USE `hedera`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `order_confirmWithUser`(IN `vOrder` INT, IN `vUserId` INT) -BEGIN -/** - * Confirms an order, creating each of its tickets on the corresponding - * date, store and user. - * - * @param vOrder The order identifier - * @param vUser The user identifier - */ - DECLARE vOk BOOL; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vWarehouse INT; - DECLARE vShipment DATETIME; - DECLARE vTicket INT; - DECLARE vNotes VARCHAR(255); - DECLARE vItem INT; - DECLARE vConcept VARCHAR(30); - DECLARE vAmount INT; - DECLARE vPrice DECIMAL(10,2); - DECLARE vSale INT; - DECLARE vRate INT; - DECLARE vRowId INT; - DECLARE vDelivery DATE; - DECLARE vAddress INT; - DECLARE vIsConfirmed BOOL; - DECLARE vClientId INT; - DECLARE vCompanyId INT; - DECLARE vAgencyModeId INT; - - DECLARE TICKET_FREE INT DEFAULT 2; - - DECLARE cDates CURSOR FOR - SELECT zgs.shipped, r.warehouse_id - FROM `order` o - JOIN order_row r ON r.order_id = o.id - LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id - WHERE o.id = vOrder AND r.amount != 0 - GROUP BY r.warehouse_id; - - DECLARE cRows CURSOR FOR - SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate - FROM order_row r - JOIN vn.item i ON i.id = r.item_id - WHERE r.amount != 0 - AND r.warehouse_id = vWarehouse - AND r.order_id = vOrder - ORDER BY r.rate DESC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - -- Carga los datos del pedido - - SELECT o.date_send, o.address_id, o.note, - o.confirmed, a.clientFk, o.company_id, o.agency_id - INTO vDelivery, vAddress, vNotes, - vIsConfirmed, vClientId, vCompanyId, vAgencyModeId - FROM hedera.`order` o - JOIN vn.address a ON a.id = o.address_id - WHERE o.id = vOrder; - - -- Comprueba que el pedido no está confirmado - - IF vIsConfirmed THEN - CALL util.throw ('ORDER_ALREADY_CONFIRMED'); - END IF; - - -- Comprueba que el pedido no está vacío - - SELECT COUNT(*) > 0 INTO vOk - FROM order_row WHERE order_id = vOrder AND amount > 0; - - IF !vOk THEN - CALL util.throw ('ORDER_EMPTY'); - END IF; - - -- Carga las fechas de salida de cada almacén - - CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); - - -- Trabajador que realiza la acción - - IF vUserId IS NULL THEN - SELECT employeeFk INTO vUserId FROM orderConfig; - END IF; - - -- Crea los tickets del pedido - - START TRANSACTION; - - OPEN cDates; - - lDates: - LOOP - SET vTicket = NULL; - SET vDone = FALSE; - FETCH cDates INTO vShipment, vWarehouse; - - IF vDone THEN - LEAVE lDates; - END IF; - - -- Busca un ticket existente que coincida con los parametros - - SELECT t.id INTO vTicket - FROM vn.ticket t - LEFT JOIN vn.ticketState tls on tls.ticket = t.id - JOIN `order` o - ON o.address_id = t.addressFk - AND vWarehouse = t.warehouseFk - AND o.agency_id = t.agencyModeFk - AND o.date_send = t.landed - AND vShipment = DATE(t.shipped) - WHERE o.id = vOrder - AND t.invoiceOutFk IS NULL - AND IFNULL(tls.alertLevel,0) = 0 - LIMIT 1; - - -- Crea el ticket en el caso de no existir uno adecuado - - IF vTicket IS NULL - THEN - CALL vn.ticketCreateWithUser( - vClientId, - IFNULL(vShipment, CURDATE()), - vWarehouse, - vCompanyId, - vAddress, - vAgencyModeId, - NULL, - vDelivery, - vUserId, - vTicket - ); - ELSE - INSERT INTO vncontrol.inter - SET Id_Ticket = vTicket, - Id_Trabajador = vUserId, - state_id = TICKET_FREE; - END IF; - - INSERT IGNORE INTO vn.orderTicket - SET orderFk = vOrder, - ticketFk = vTicket; - - -- Añade las notas - - IF vNotes IS NOT NULL AND vNotes != '' - THEN - INSERT INTO vn.ticketObservation SET - ticketFk = vTicket, - observationTypeFk = 4 /* salesperson */ , - `description` = vNotes - ON DUPLICATE KEY UPDATE - `description` = CONCAT(VALUES(`description`),'. ', `description`); - END IF; - - -- Añade los movimientos y sus componentes - - OPEN cRows; - - lRows: - LOOP - SET vDone = FALSE; - FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate; - - IF vDone THEN - LEAVE lRows; - END IF; - - INSERT INTO vn.sale - SET - itemFk = vItem, - ticketFk = vTicket, - concept = vConcept, - quantity = vAmount, - price = vPrice, - priceFixed = 0, - isPriceFixed = TRUE; - - SET vSale = LAST_INSERT_ID(); - - INSERT INTO vn.saleComponent - (saleFk, componentFk, `value`) - SELECT vSale, cm.component_id, cm.price - FROM order_component cm - JOIN bi.tarifa_componentes tc - ON tc.Id_Componente = cm.component_id - WHERE cm.order_row_id = vRowId - GROUP BY vSale, cm.component_id; - - UPDATE order_row SET Id_Movimiento = vSale - WHERE id = vRowId; - - END LOOP; - - CLOSE cRows; - - -- Fija el coste - - DROP TEMPORARY TABLE IF EXISTS tComponents; - CREATE TEMPORARY TABLE tComponents - (INDEX (saleFk)) - ENGINE = MEMORY - SELECT SUM(sc.`value`) valueSum, sc.saleFk - FROM vn.saleComponent sc - JOIN bi.tarifa_componentes tc ON tc.Id_Componente = sc.componentFk - JOIN bi.tarifa_componentes_series tcs - ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id - AND tcs.base - JOIN vn.sale s - ON s.id = sc.saleFk - WHERE s.ticketFk = vTicket - GROUP BY sc.saleFk; - - UPDATE vn.sale s - JOIN tComponents mc ON mc.saleFk = s.id - SET s.priceFixed = valueSum; - - DROP TEMPORARY TABLE tComponents; - END LOOP; - - CLOSE cDates; - - DELETE FROM basketOrder WHERE orderFk = vOrder; - UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() - WHERE id = vOrder; - - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/03-ticketCalculateClon.sql b/db/changes/10100-allSaints/03-ticketCalculateClon.sql deleted file mode 100644 index 86d1c6033..000000000 --- a/db/changes/10100-allSaints/03-ticketCalculateClon.sql +++ /dev/null @@ -1,88 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCalculateClon`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT) -BEGIN - /* - * @vTicketNew id del nuevo ticket clonado - * @vTicketOld id ticket original, a partir del qual se clonara el nuevo - * Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo - */ - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouse SMALLINT; - DECLARE vAgencyMode INT; - DECLARE vAddress INT; - DECLARE vLanded DATE; - DECLARE vAgency INT; - DECLARE vZoneFk INT; - - REPLACE INTO orderTicket(orderFk,ticketFk) - SELECT orderFk, vTicketNew - FROM orderTicket - WHERE ticketFk = vTicketOld; - - SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk - INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk - FROM vn.agencyMode a - JOIN vn.ticket t ON t.agencyModeFk = a.id - WHERE t.id = vTicketNew; - - IF vLanded IS NULL THEN - CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); - UPDATE ticket t - JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk - SET t.landed = zgl.landed, - t.zone = zgl.zoneFk - WHERE t.id = vTicketNew; - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - END IF; - - -- rellena la tabla tmp.buyUltimate con la ultima compra - CALL buyUltimate(vWarehouse, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; - - CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode); - - -- Bionizamos lineas con Preu = 0 - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT s.id saleFk, vWarehouse warehouseFk - FROM sale s - JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew AND s.price = 0; - - CALL ticketComponentUpdateSale(1); - - -- Bionizamos lineas con Preu > 0 - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT s.id saleFk, vWarehouse warehouseFk - FROM sale s - JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew - AND s.price > 0; - - CALL ticketComponentUpdateSale(6); - - -- Log - CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); - - -- Limpieza - DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; -END$$ - -DELIMITER ; diff --git a/db/changes/10100-allSaints/03-ticketComponentCalculate.sql b/db/changes/10100-allSaints/03-ticketComponentCalculate.sql deleted file mode 100644 index 4547c4c64..000000000 --- a/db/changes/10100-allSaints/03-ticketComponentCalculate.sql +++ /dev/null @@ -1,262 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`ticketComponentCalculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate__`( - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN --- OBSOLETO usar catalog_componentCalculate -/** - * Calcula los componentes de un ticket - * - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id del modo de agencia - * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, - * packing, grouping, groupingMode, buyFk, typeFk) - * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) - */ - - DECLARE vClientFk INT; - DECLARE vGeneralInflationCoefficient INT DEFAULT 1; - DECLARE vMinimumDensityWeight INT DEFAULT 167; - DECLARE vBoxFreightItem INT DEFAULT 71; - DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; - DECLARE vSpecialPriceComponent INT DEFAULT 10; - DECLARE vDeliveryComponent INT DEFAULT 15; - DECLARE vRecoveryComponent INT DEFAULT 17; - DECLARE vSellByPacketComponent INT DEFAULT 22; - DECLARE vBuyValueComponent INT DEFAULT 28; - DECLARE vMarginComponent INT DEFAULT 29; - DECLARE vDiscountLastItemComponent INT DEFAULT 32; - DECLARE vExtraBaggedComponent INT DEFAULT 38; - DECLARE vManaAutoComponent INT DEFAULT 39; - - - - SELECT volume INTO vBoxVolume - FROM vn.packaging - WHERE id = '94'; - - SELECT clientFk INTO vClientFK - FROM address - WHERE id = vAddressFk; - - SET @rate2 := 0; - SET @rate3 := 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; - CREATE TEMPORARY TABLE tmp.ticketComponentCalculate - (PRIMARY KEY (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT - tl.itemFk, tl.warehouseFk, tl.available, - IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, - IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, - IFNULL(pf.rate3, 0) AS minPrice, - IFNULL(pf.packing, b.packing) packing, - IFNULL(pf.`grouping`, b.`grouping`) `grouping`, - ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, - i.typeFk, - IF(i.hasKgPrice,b.weight / b.packing, NULL) weightGrouping - FROM tmp.ticketLot tl - JOIN buy b ON b.id = tl.buyFk - JOIN item i ON i.id = tl.itemFk - JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk - LEFT JOIN ( - SELECT * FROM ( - SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, aho.warehouseFk - FROM priceFixed pf - JOIN tmp.zoneGetShipped aho ON pf.warehouseFk = aho.warehouseFk OR pf.warehouseFk = 0 - WHERE aho.shipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC - ) tpf - GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk - WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; - CREATE TEMPORARY TABLE tmp.ticketComponent ( - `warehouseFk` INT UNSIGNED NOT NULL, - `itemFk` INT NOT NULL, - `componentFk` INT UNSIGNED NOT NULL, - `cost` DECIMAL(10,4) NOT NULL, - INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), - UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vBuyValueComponent, - b.buyingValue + b.freightValue + b.packageValue + b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vMarginComponent, - tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; - CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY - SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk - FROM tmp.ticketComponent tc - GROUP BY tc.itemFk, warehouseFk; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) - FROM tmp.ticketComponentBase tcb - JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk - WHERE cr.recobro > 0.009; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto - FROM tmp.ticketComponentBase tcb - JOIN `client` c on c.id = vClientFk - JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador - WHERE ms.prices_modifier_activated - HAVING manaAuto <> 0; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, - tcb.itemFk, - cr.id, - GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) - FROM tmp.ticketComponentBase tcb - JOIN componentRate cr - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFK, - tcc.itemFk, - vDeliveryComponent, - vGeneralInflationCoefficient - * ROUND(( - i.compression - * r.cm3 - * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) - * IFNULL((z.price - z.bonus) - * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 - ) cost - FROM tmp.ticketComponentCalculate tcc - JOIN item i ON i.id = tcc.itemFk - JOIN agencyMode am ON am.id = vAgencyModeFk - JOIN `address` a ON a.id = vAddressFk - JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = tcc.warehouseFk - JOIN zone z ON z.id = zgs.id - LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk - AND r.Id_Article = tcc.itemFk - HAVING cost <> 0; - - IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost - FROM tmp.ticketComponentCalculate tcc - JOIN vn.addressForPackaging ap - WHERE ap.addressFk = vAddressFk; - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; - CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY - SELECT * FROM tmp.ticketComponent; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - vSpecialPriceComponent, - sp.value - SUM(tcc.cost) sumCost - FROM tmp.ticketComponentCopy tcc - JOIN componentRate cr ON cr.id = tcc.componentFk - JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk - WHERE cr.classRate IS NULL - GROUP BY tcc.itemFk, tcc.warehouseFk - HAVING ABS(sumCost) > 0.001; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; - CREATE TEMPORARY TABLE tmp.ticketComponentSum - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate - FROM tmp.ticketComponent tc - JOIN componentRate cr ON cr.id = tc.componentFk - GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; - CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY - SELECT tcc.warehouseFk, - tcc.itemFk, - 1 rate, - IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, - CAST(SUM(tcs.sumCost) / weightGrouping AS DECIMAL(10,2)) priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 - AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 2 rate, - tcc.packing `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 - AND tcc.packing > 0 AND tcc.available >= tcc.packing) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 3 rate, - tcc.available `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 3) = 3 - GROUP BY tcs.warehouseFk, tcs.itemFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; - CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM tmp.ticketComponentRate ORDER BY price - ) t - GROUP BY itemFk, warehouseFk, `grouping`; - - DROP TEMPORARY TABLE - tmp.ticketComponentCalculate, - tmp.ticketComponentSum, - tmp.ticketComponentBase, - tmp.ticketComponentRate, - tmp.ticketComponentCopy; -END$$ - -DELIMITER ; -; diff --git a/db/changes/10100-allSaints/03-ticketCreateWithUser.sql b/db/changes/10100-allSaints/03-ticketCreateWithUser.sql deleted file mode 100644 index 8135c72bf..000000000 --- a/db/changes/10100-allSaints/03-ticketCreateWithUser.sql +++ /dev/null @@ -1,88 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCreateWithUser`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF vAgencyModeFk IS NOT NULL THEN - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - IF vZoneFk IS NULL OR vZoneFk = 0 THEN - CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); - END IF; - END IF; - INSERT INTO ticket ( - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - warehouseFk, - routeFk, - companyFk, - landed, - zoneFk - ) - SELECT - vClientId, - vShipped, - a.id, - vAgencyModeFk, - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, getWorker() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END$$ - -DELIMITER ; diff --git a/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql b/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql deleted file mode 100644 index b4840e31d..000000000 --- a/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql +++ /dev/null @@ -1,90 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCreateWithoutZone`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN - SELECT agencyModeFk INTO vAgencyModeFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - INSERT INTO vn2008.Tickets ( - Id_Cliente, - Fecha, - Id_Consigna, - Id_Agencia, - Alias, - warehouse_id, - Id_Ruta, - empresa_id, - landing, - zoneFk - ) - SELECT - vClientId, - vShipped, - a.id, - IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - -- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket)); - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, getWorker() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/05-catalog_calcFromItem.sql b/db/changes/10100-allSaints/05-catalog_calcFromItem.sql deleted file mode 100644 index 40b2c2eb8..000000000 --- a/db/changes/10100-allSaints/05-catalog_calcFromItem.sql +++ /dev/null @@ -1,31 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `catalog_calcFromItem`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calcFromItem`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT, - vItemFk INT) -BEGIN -/** - * Calculates available and price for a single item. - * - * @param vItemFk The item id - * @return tmp.ticketCalculateItem - * @return tmp.ticketComponentPrice - * @return tmp.ticketComponent - * @return tmp.ticketLot - * @return tmp.zoneGetShipped - */ - DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY - SELECT vItemFk itemFk; - - CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); - DROP TEMPORARY TABLE tmp.item; -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-chatConfig.sql b/db/changes/10110-postCampaign/00-chatConfig.sql deleted file mode 100644 index e0423bb86..000000000 --- a/db/changes/10110-postCampaign/00-chatConfig.sql +++ /dev/null @@ -1,11 +0,0 @@ -USE `vn`; - -CREATE TABLE `vn`.`chatConfig` ( - `id` INT NOT NULL AUTO_INCREMENT, - `uri` VARCHAR(255) NOT NULL, - `user` VARCHAR(50) NOT NULL, - `password` VARCHAR(50) NOT NULL, - PRIMARY KEY (`id`)); - - -INSERT INTO `vn`.`chatConfig` (`uri`, `user`, `password`) VALUES ('https://chat.verdnatura.es/api/v1', 'VnBot', 'Ub606cux7op.'); diff --git a/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql b/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql deleted file mode 100644 index 5e69e28ad..000000000 --- a/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql +++ /dev/null @@ -1,51 +0,0 @@ -DROP TRIGGER IF EXISTS `vn`.`client_beforeUpdate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`client_beforeUpdate` - BEFORE UPDATE ON `client` - FOR EACH ROW -BEGIN - DECLARE vText VARCHAR(255) DEFAULT NULL; - -- Comprueba que el formato de los teléfonos es válido - - IF !(NEW.phone <=> OLD.phone) THEN - CALL pbx.phone_isValid(NEW.phone); - END IF; - - IF !(NEW.mobile <=> OLD.mobile) THEN - CALL pbx.phone_isValid(NEW.mobile); - END IF; - - IF !(NEW.fax <=> OLD.fax) THEN - CALL pbx.phone_isValid(NEW.fax); - END IF; - - IF NEW.payMethodFk = 4 AND NEW.dueDay = 0 THEN - SET NEW.dueDay = 5; - END IF; - - -- Avisar al comercial si ha llegado la documentación sepa/core - - IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN - SET vText = 'Sepa de VNL'; - END IF; - - IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN - SET vText = 'Core de VNL'; - END IF; - - IF vText IS NOT NULL - THEN - INSERT INTO mail(sender, replyTo, `subject`, body) - SELECT - CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), - 'administracion@verdnatura.es', - CONCAT('Cliente ', NEW.id), - CONCAT('Recibida la documentación: ', vText) - FROM worker w - LEFT JOIN account.user u ON w.userFk = u.id AND u.active - LEFT JOIN account.account ac ON ac.id = u.id - WHERE w.id = NEW.salesPersonFk; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-clientGetMana.sql b/db/changes/10110-postCampaign/00-clientGetMana.sql deleted file mode 100644 index dcf9171b2..000000000 --- a/db/changes/10110-postCampaign/00-clientGetMana.sql +++ /dev/null @@ -1,75 +0,0 @@ -DROP function IF EXISTS `vn`.`clientGetMana`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`clientGetMana`(vClient INT) RETURNS decimal(10,2) - DETERMINISTIC -BEGIN -/** - * Devuelve el mana del cliente. - * - * @param vClient Id del cliente - * @return Mana del cliente - */ - DECLARE vMana DECIMAL(10,2); - DECLARE vFromDated DATE; - DECLARE vHasMana BOOLEAN; - DECLARE vManaComponent INT; - DECLARE vAutoManaComponent INT; - DECLARE vManaBank INT; - DECLARE vManaGreugeType INT; - - SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; - SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; - SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; - SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; - - SELECT COUNT(*) INTO vHasMana - FROM `client` c - WHERE c.id = vClient AND c.typeFk = 'normal'; - - IF NOT vHasMana THEN - RETURN 0; - END IF; - - SELECT max(dated) INTO vFromDated - FROM clientManaCache; - - SELECT sum(mana) INTO vMana - FROM - ( - SELECT mana - FROM clientManaCache - WHERE clientFk = vClient - AND dated = vFromDated - UNION ALL - SELECT s.quantity * value - FROM ticket t - JOIN address a ON a.id = t.addressFk - JOIN sale s on s.ticketFk = t.id - JOIN saleComponent sc on sc.saleFk = s.id - WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) - AND t.shipped > vFromDated - AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE()) - AND a.clientFk = vClient - UNION ALL - SELECT - amountPaid - FROM receipt r - JOIN `client` c ON c.id = r.clientFk - WHERE r.bankFk = vManaBank - AND r.payed > vFromDated - AND r.payed <= CURDATE() - AND c.id = vClient - UNION ALL - SELECT g.amount - FROM greuge g - JOIN `client` c ON c.id = g.clientFk - WHERE g.greugeTypeFk = vManaGreugeType - AND g.shipped > vFromDated - AND g.shipped <= CURDATE() - AND c.id = vClient - ) sub; - RETURN IFNULL(vMana,0); -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql b/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql deleted file mode 100644 index a981fd5cb..000000000 --- a/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql +++ /dev/null @@ -1,97 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`clientPackagingOverstock`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clientPackagingOverstock`(vClientFk INT, vGraceDays INT ) -BEGIN - DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock; - CREATE TEMPORARY TABLE tmp.clientPackagingOverstock - ENGINE = MEMORY - SELECT itemFk, - sum(GotfromClient) - sum(SenttoClient) as devueltos, - sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados, - LEAST( - sum(GotfromClient) - sum(SenttoClient), - sum(InvoicedtoClient) - sum(InvoicedfromClient) - ) as abonables - FROM - ( - SELECT t.*, - IF(@month = month, 0, 1) monthEnd, - @month := month - FROM - ( - SELECT x.id as ticketFk, - date(x.shipped) as shipped, - x.itemFk, - IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient, - IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient, - IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient, - IFNULL(cast(sum(x.GotfromClient) as DECIMAL(10,0)),0) GotfromClient, - i.name as concept, - x.refFk as invoice, - month(shipped) month, - x.companyFk - FROM - ( - SELECT t.id, - t.shipped, - IFNULL(pe.equivalentFk, s.itemFk) itemFk, - IF(s.quantity > 0, s.quantity, NULL) InvoicedtoClient, - IF(s.quantity < 0, -s.quantity, NULL) InvoicedfromClient, - NULL SenttoClient, - NULL GotfromClient, - t.refFk, - @month := 0 month, - t.companyFk - FROM sale s - JOIN ticket t on t.id = s.ticketFk - JOIN packaging p ON p.itemFk = s.itemFk - LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk - WHERE t.clientFk = vClientFk - AND t.shipped > '2017-11-30' - AND p.isPackageReturnable - UNION ALL - SELECT NULL, - '2017-11-30', - IFNULL(pe.equivalentFk, tps.itemFk) itemFk, - tps.sent InvoicedtoClient, - tps.returned InvoicedfromClient, - NULL SenttoClient, - NULL GotfromClient, - 'Histórico', - NULL, - NULL - - FROM ticketPackagingStartingStock tps - LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk - WHERE tps.clientFk = vClientFk - AND tps.isForgetable = FALSE - UNION ALL - SELECT t.id, - t.shipped, - IFNULL(pe.equivalentFk, p.itemFk) itemFk, - NULL, - NULL, - IF(tp.quantity > 0 AND t.shipped <= TIMESTAMPADD(DAY, - vGraceDays, CURDATE()), tp.quantity, NULL) SenttoClient, - IF(tp.quantity < 0, -tp.quantity, NULL) GotfromClient, - NULL AS refFk, - NULL, - t.companyFk - FROM ticketPackaging tp - JOIN ticket t on t.id = tp.ticketFk - JOIN packaging p ON p.id = tp.packagingFk - LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk - WHERE t.clientFk = vClientFk - AND t.shipped > '2017-11-21' ) x - - JOIN item i ON x.itemFk = i.id - GROUP BY x.id, x.itemFk - ) t - ORDER BY itemFk, shipped DESC - ) t2 - GROUP BY itemFk; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-clonTravelComplete.sql b/db/changes/10110-postCampaign/00-clonTravelComplete.sql deleted file mode 100644 index 9817613f4..000000000 --- a/db/changes/10110-postCampaign/00-clonTravelComplete.sql +++ /dev/null @@ -1,132 +0,0 @@ -DROP procedure IF EXISTS `vn`.`clonTravelComplete`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) -BEGIN - - DECLARE vTravelNew INT; - DECLARE vEntryNew INT; - DECLARE vDone BIT DEFAULT 0; - DECLARE vAuxEntryFk INT; - DECLARE vRsEntry CURSOR FOR - SELECT e.id - FROM entry e - JOIN travel t - ON t.id = e.travelFk - WHERE e.travelFk = vTravelFk; - - DECLARE vRsBuy CURSOR FOR - SELECT b.* - FROM buy b - JOIN entry e - ON b.entryFk = e.id - WHERE e.travelFk = vTravelNew and b.entryFk=entryNew - ORDER BY e.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - INSERT INTO travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) - SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg - FROM travel - WHERE id = vTravelFk; - - SET vTravelNew = LAST_INSERT_ID(); - SET vDone = 0; - OPEN vRsEntry ; - FETCH vRsEntry INTO vAuxEntryFk; - - WHILE NOT vDone DO - INSERT INTO entry (supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - travelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk) - SELECT supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - vTravelNew, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk - FROM entry - WHERE id = vAuxEntryFk; - - SET vEntryNew = LAST_INSERT_ID(); - - - INSERT INTO buy (entryFk, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isChecked) - SELECT vEntryNew, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isChecked - FROM buy - WHERE entryFk = vAuxEntryFk; - - - FETCH vRsEntry INTO vAuxEntryFk; - END WHILE; - CLOSE vRsEntry; - COMMIT; - END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-country.sql b/db/changes/10110-postCampaign/00-country.sql deleted file mode 100644 index dcc883ab8..000000000 --- a/db/changes/10110-postCampaign/00-country.sql +++ /dev/null @@ -1,10 +0,0 @@ -USE `vn`; - -UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 1); -UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 2); -UPDATE `vn`.`country` SET `ibanLength` = '22' WHERE (`id` = 3); -UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 4); -UPDATE `vn`.`country` SET `ibanLength` = '18' WHERE (`id` = 5); -UPDATE `vn`.`country` SET `ibanLength` = '25' WHERE (`id` = 8); -UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 19); -UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 30); diff --git a/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql b/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql deleted file mode 100644 index 5ca0fd131..000000000 --- a/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql +++ /dev/null @@ -1,16 +0,0 @@ - -DELIMITER $$ -DROP TRIGGER IF EXISTS `vn`.`creditClassification_BEFORE_UPDATE` $$ - - -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditClassification_beforeUpdate` BEFORE UPDATE ON `creditClassification` FOR EACH ROW -BEGIN - IF NEW.client <> OLD.client THEN - CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT'); - END IF; - IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN - UPDATE `client` c - SET creditInsurance = 0 WHERE c.id = NEW.client; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql b/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql deleted file mode 100644 index 4429b1e97..000000000 --- a/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql +++ /dev/null @@ -1,13 +0,0 @@ - -DELIMITER $$ - -DROP TRIGGER IF EXISTS `vn`.`creditInsurance_AFTER_INSERT` $$ - -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditInsurance_afterInsert` AFTER INSERT ON `creditInsurance` FOR EACH ROW -BEGIN - UPDATE `client` c - JOIN vn.creditClassification cc ON cc.client = c.id - SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; - -END$$ -DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-department_doCalc.sql b/db/changes/10110-postCampaign/00-department_doCalc.sql deleted file mode 100644 index 7adeb30f0..000000000 --- a/db/changes/10110-postCampaign/00-department_doCalc.sql +++ /dev/null @@ -1,3 +0,0 @@ -USE `vn`; - -CREATE DEFINER=`root`@`%` EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql b/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql deleted file mode 100644 index 091acef43..000000000 --- a/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql +++ /dev/null @@ -1,74 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`duaInvoiceInBooking`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`duaInvoiceInBooking`(vDuaFk INT) -BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vInvoiceFk INT; - DECLARE vASIEN BIGINT DEFAULT 0; - DECLARE vCounter INT DEFAULT 0; - - DECLARE rs CURSOR FOR - SELECT e.invoiceInFk - FROM entry e - JOIN duaEntry de ON de.entryFk = e.id - JOIN invoiceIn ii ON ii.id = e.invoiceInFk - WHERE de.duaFk = vDuaFk - AND de.customsValue - AND ii.isBooked = FALSE; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - OPEN rs; - - UPDATE invoiceIn ii - JOIN entry e ON e.invoiceInFk = ii.id - JOIN duaEntry de ON de.entryFk = e.id - JOIN dua d ON d.id = de.duaFk - SET ii.isBooked = TRUE, - ii.booked = IFNULL(ii.booked,d.booked), - ii.operated = IFNULL(ii.operated,d.operated), - ii.issued = IFNULL(ii.issued,d.issued), - ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried), - e.isConfirmed = TRUE - WHERE d.id = vDuaFk; - - SELECT IFNULL(ASIEN,0) INTO vASIEN - FROM dua - WHERE id = vDuaFk; - - FETCH rs INTO vInvoiceFk; - - WHILE NOT done DO - - CALL invoiceInBookingMain(vInvoiceFk); - - IF vCounter > 0 OR vASIEN > 0 THEN - - UPDATE XDiario x - JOIN config c ON c.ASIEN = x.ASIEN - SET x.ASIEN = vASIEN; - - ELSE - - SELECT ASIEN INTO vASIEN FROM config; - - END IF; - - SET vCounter = vCounter + 1; - - FETCH rs INTO vInvoiceFk; - - END WHILE; - - CLOSE rs; - - UPDATE dua - SET ASIEN = vASIEN - WHERE id = vDuaFk; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql b/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql deleted file mode 100644 index 21b827a75..000000000 --- a/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql +++ /dev/null @@ -1,17 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `getItemVisibleAvailable`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`( - vItem INT, - vDate DATE, - vWarehouse TINYINT, - vRefresh BOOL) -BEGIN - -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 - CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql b/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql deleted file mode 100644 index 4701e7124..000000000 --- a/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql +++ /dev/null @@ -1,17 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `itemGetVisibleAvailable`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`( - vItem INT, - vDate DATE, - vWarehouse TINYINT, - vRefresh BOOL) -BEGIN - -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 - CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql b/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql deleted file mode 100644 index e6b6df2f9..000000000 --- a/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql +++ /dev/null @@ -1,71 +0,0 @@ - -USE `vn`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisibleAvailable`( - vItem INT, - vDate DATE, - vWarehouse TINYINT, - vRefresh BOOL) -BEGIN - DECLARE vVisibleCalc INT; - DECLARE vAvailableCalc INT; - DECLARE vVisibleAltillo INT; - - CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate); - CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); - - SELECT visible INTO vVisibleAltillo - FROM vn.itemShelvingStock - WHERE itemFk = vItem - AND warehouseFk = vWarehouse; - - IF vRefresh THEN - - DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; - CREATE TEMPORARY TABLE vn2008.tmp_item - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT vItem item_id, 0 stock, 0 visible; - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - vi.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN vn2008.tmp_item v - ON v.item_id = i.id - LEFT JOIN cache.available av - ON av.calc_id = vAvailableCalc AND av.item_id = i.id - LEFT JOIN cache.visible vi - ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id - LEFT JOIN cache.stock st - ON st.warehouse_id = vWarehouse AND st.item_id = i.id - WHERE (vItem IS NULL OR i.id = vItem); - - ELSE - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - v.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN cache.visible v - ON v.item_id = i.id AND v.calc_id = vVisibleCalc - LEFT JOIN cache.available av - ON av.item_id = i.id AND av.calc_id = vAvailableCalc - WHERE (vItem IS NULL OR i.id = vItem); - - END IF; - -END$$ - -DELIMITER ; -; diff --git a/db/changes/10110-postCampaign/00-payMethod.sql b/db/changes/10110-postCampaign/00-payMethod.sql deleted file mode 100644 index e2421ee53..000000000 --- a/db/changes/10110-postCampaign/00-payMethod.sql +++ /dev/null @@ -1,7 +0,0 @@ -USE `vn`; - -ALTER TABLE `vn`.`payMethod` -ADD COLUMN `code` VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL AFTER `id`; - -UPDATE `vn`.`payMethod` SET `code` = 'bankDraft' WHERE (`id` = '4'); -UPDATE `vn`.`payMethod` SET `code` = 'card' WHERE (`id` = '5'); diff --git a/db/changes/10110-postCampaign/00-rangeDateInfo.sql b/db/changes/10110-postCampaign/00-rangeDateInfo.sql deleted file mode 100644 index 816269ef9..000000000 --- a/db/changes/10110-postCampaign/00-rangeDateInfo.sql +++ /dev/null @@ -1,41 +0,0 @@ -DROP procedure IF EXISTS `vn`.`rangeDateInfo`; - -DELIMITER $$ -CREATE PROCEDURE `vn`.`rangeDateInfo` (vStarted DATE, vEnded DATE) -BEGIN -/** - * Crea una tabla temporal con las fechas - * desde una fecha inicial a una final - * @param vStarted fecha inicial - * @param vEnded fecha final - */ - DECLARE vDated DATE DEFAULT vStarted; - - DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; - CREATE TEMPORARY TABLE tmp.rangeDate( - `dated` DATE, - `period` INT, - `month` INT, - `year` INT, - `day` INT, - `week` INT, - `yearMonth` INT - ) - ENGINE = MEMORY; - - WHILE vDated <= vEnded DO - INSERT INTO tmp.rangeDate - SET `dated` = vDated, - `period` = YEAR(vDated) * 100 + WEEK(vDated, 1), - `month` = MONTH(vDated), - `year` = YEAR(vDated), - `day` = DAY(vDated), - `week` = WEEK(vDated, 1), - `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); - - SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); - END WHILE; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-sample.sql b/db/changes/10110-postCampaign/00-sample.sql deleted file mode 100644 index 68e9d1a0f..000000000 --- a/db/changes/10110-postCampaign/00-sample.sql +++ /dev/null @@ -1,8 +0,0 @@ -USE `vn`; - -UPDATE `vn`.`sample` SET `description` = 'Bienvenida como nuevo cliente' WHERE (`id` = '12'); -UPDATE `vn`.`sample` SET `description` = 'Instalación y configuración de impresora de coronas' WHERE (`id` = '13'); -UPDATE `vn`.`sample` SET `description` = 'Solicitud de domiciliación bancaria' WHERE (`id` = '14'); -UPDATE `vn`.`sample` SET `description` = 'Aviso inicial por saldo deudor' WHERE (`id` = '15'); -UPDATE `vn`.`sample` SET `description` = 'Aviso reiterado por saldo deudor' WHERE (`id` = '16'); -UPDATE `vn`.`sample` SET `isVisible` = '0' WHERE (`id` = '17'); diff --git a/db/changes/10110-postCampaign/00-ticketClosure.sql b/db/changes/10110-postCampaign/00-ticketClosure.sql deleted file mode 100644 index 07c7ef812..000000000 --- a/db/changes/10110-postCampaign/00-ticketClosure.sql +++ /dev/null @@ -1,116 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketClosure`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure`() -BEGIN -/** - * Realiza el cierre de todos los - * tickets de la table ticketClosure. - */ - DECLARE vDone BOOL; - DECLARE vClientFk INT; - DECLARE vTicketFk INT; - DECLARE vIsTaxDataChecked BOOL; - DECLARE vCompanyFk INT; - DECLARE vShipped DATE; - DECLARE vPriority INT DEFAULT 1; - DECLARE vReportDeliveryNote INT DEFAULT 1; - DECLARE vNewInvoiceId INT; - DECLARE vHasDailyInvoice BOOL; - DECLARE vWithPackage BOOL; - - DECLARE cur CURSOR FOR - SELECT ticketFk FROM tmp.ticketClosure; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - RESIGNAL; - END; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; - CREATE TEMPORARY TABLE tmp.ticketClosure2 - SELECT ticketFk FROM tmp.ticketClosure; - INSERT INTO tmp.ticketClosure - SELECT id FROM stowaway s - JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk; - OPEN cur; - - proc: LOOP - SET vDone = FALSE; - - FETCH cur INTO vTicketFk; - - IF vDone THEN - LEAVE proc; - END IF; - - -- ticketClosure start - SELECT - c.id, - c.isTaxDataChecked, - t.companyFk, - t.shipped, - co.hasDailyInvoice, - w.isManaged - INTO vClientFk, - vIsTaxDataChecked, - vCompanyFk, - vShipped, - vHasDailyInvoice, - vWithPackage - FROM ticket t - JOIN `client` c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.id = vTicketFk; - - INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) - (SELECT vTicketFk, p.id, COUNT(*) - FROM expedition e - JOIN packaging p ON p.itemFk = e.itemFk - WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable - AND vWithPackage - GROUP BY p.itemFk); - - -- No retornables o no catalogados - INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) - (SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 - FROM expedition e - JOIN item i ON i.id = e.itemFk - LEFT JOIN packaging p ON p.itemFk = i.id - WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 - AND getSpecialPrice(e.itemFk, vClientFk) > 0 - GROUP BY e.itemFk); - - IF(vHasDailyInvoice) THEN - - -- Facturacion rapida - CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL); - -- Facturar si está contabilizado - IF vIsTaxDataChecked THEN - CALL invoiceOut_newFromClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, - NULL, - vNewInvoiceId); - END IF; - ELSE - -- Albaran_print - CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); - END IF; - - -- ticketClosure end - END LOOP; - - CLOSE cur; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-ticketRequest.sql b/db/changes/10110-postCampaign/00-ticketRequest.sql deleted file mode 100644 index cae9e09ce..000000000 --- a/db/changes/10110-postCampaign/00-ticketRequest.sql +++ /dev/null @@ -1,54 +0,0 @@ - -ALTER TABLE `vn`.`ticketRequest` -DROP FOREIGN KEY `fgnAtender`; -ALTER TABLE `vn`.`ticketRequest` -CHANGE COLUMN `atenderFk` `attenderFk` INT(11) NULL DEFAULT NULL ; -ALTER TABLE `vn`.`ticketRequest` -ADD CONSTRAINT `fgnAtender` - FOREIGN KEY (`attenderFk`) - REFERENCES `vn`.`worker` (`id`) - ON UPDATE CASCADE; - - - - -DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeInsert`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW -BEGIN - IF NEW.ticketFk IS NULL THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.requesterFk IS NULL THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; - - IF NEW.attenderFk IS NULL THEN - SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; -END$$ -DELIMITER ; - - -DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeUpdate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW -BEGIN - IF NEW.saleFk <> OLD.saleFk THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.salesPersonCode <> OLD.salesPersonCode THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; - - IF NEW.buyerCode <> OLD.buyerCode THEN - SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; -END$$ -DELIMITER ; - - diff --git a/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql b/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql deleted file mode 100644 index 885e2998a..000000000 --- a/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql +++ /dev/null @@ -1,77 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticket_recalcComponents`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT ) -proc: BEGIN - -/** - * Este procedimiento trata de "rebionizar" un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @return tmp.buyUltimate - */ - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAgencyModeFk INT; - DECLARE vAddressFk INT; - DECLARE vLanded DATE; - DECLARE vIsTicketEditable BOOLEAN; - DECLARE vZoneFk INTEGER; - - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; - - CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios - - IF vLanded IS NULL THEN - - CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql b/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql deleted file mode 100644 index 90d65fcc1..000000000 --- a/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql +++ /dev/null @@ -1,77 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticket_recalcComponentsForcePrice`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN ) -proc: BEGIN - -/** - * Este procedimiento trata de "rebionizar" un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @return tmp.buyUltimate - */ - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAgencyModeFk INT; - DECLARE vAddressFk INT; - DECLARE vLanded DATE; - DECLARE vZoneFk INTEGER; - - IF vIsTicketEditable IS NULL THEN - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - END IF; - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; - - CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios - - IF vLanded IS NULL THEN - - CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql b/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql deleted file mode 100644 index c2091ff83..000000000 --- a/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql +++ /dev/null @@ -1,73 +0,0 @@ -DROP function IF EXISTS `vn`.`workerTimeControl_add`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`workerTimeControl_add`( vUserFk INT, vWarehouseFk INT, vTimed DATETIME, vIsManual BOOL) RETURNS int(11) - DETERMINISTIC -BEGIN - DECLARE vDirection VARCHAR(6); - DECLARE vLastIn DATETIME; - DECLARE vDayStayMax INT; - DECLARE vHasDirectionOut INT; - DECLARE vLastInsertedId INT; - - SELECT dayStayMax INTO vDayStayMax - FROM workerTimeControlParams; - - SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; - - IF vDirection = 'out' THEN - - SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'in' - AND timed < vTimed; - - UPDATE workerTimeControl wtc - SET wtc.direction = 'middle' - WHERE userFk = vUserFk - AND direction = 'out' - AND timed BETWEEN vLastIn AND vTimed; - - ELSE IF vDirection = 'in' THEN - - SELECT COUNT(*) INTO vHasDirectionOut - FROM workerTimeControl wtc - WHERE userFk = vUserFk - AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - - UPDATE workerTimeControl wtc - SET wtc.direction = IF (vHasDirectionOut,'middle','out') - WHERE userFk = vUserFk - AND direction = 'in' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - - END IF; - END IF; - - INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) - VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - - SET vLastInsertedId = LAST_INSERT_ID(); - - CALL workerTimeControlSOWP(vUserFk, vTimed); - - RETURN vLastInsertedId; -END$$ - -DELIMITER ; - - - -DROP procedure IF EXISTS `vn`.`workerTimeControl_add`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) -BEGIN - - - SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql b/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql deleted file mode 100644 index 8e8c7471b..000000000 --- a/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql +++ /dev/null @@ -1,41 +0,0 @@ -DROP procedure IF EXISTS `vn`.`timeControl_calculate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) -BEGIN - SET @vIsOdd := TRUE; - SET @vUser := NULL; - SET @vDated := NULL; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; - - CREATE TEMPORARY TABLE tmp.timeControlCalculate - SELECT userFk, - dated, - IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, - SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, - @timeWork / 3600 timeWorkDecimal - FROM (SELECT SUM(timeWork) timeWork, - userFk, - dated - FROM (SELECT IF(@vUser = wtc.userFk, @vUser :=@vUser, @vUser := wtc.userFk ), - IF(@vIsOdd, @vIsOdd := FALSE, @vIsOdd := TRUE ), - IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd ), - IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed:=@vLastTimed), - IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed)-@vLastTimed) timeWork, - IF(direction='in', @vDated := DATE(wtc.timed), @vDated :=@vDated) dated, - wtc.userFk, - wtc.timed timed, - direction - FROM workerTimeControl wtc - JOIN tmp.`user` w ON w.userFk = wtc.userFk - WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo - ORDER BY userFk, timed - ) sub - GROUP BY userFk, dated - ORDER BY userFk, dated - )sub2; - -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/01-Ordenes.sql b/db/changes/10110-postCampaign/01-Ordenes.sql deleted file mode 100644 index b2b2f7d35..000000000 --- a/db/changes/10110-postCampaign/01-Ordenes.sql +++ /dev/null @@ -1,53 +0,0 @@ - -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn2008`.`Ordenes` AS - SELECT - `tr`.`id` AS `Id_ORDEN`, - `tr`.`description` AS `ORDEN`, - `tr`.`requesterFk` AS `requesterFk`, - `tr`.`attenderFk` AS `attenderFk`, - `tr`.`quantity` AS `CANTIDAD`, - `tr`.`itemFk` AS `Id_ARTICLE`, - `tr`.`price` AS `PRECIOMAX`, - `tr`.`isOk` AS `isOk`, - `tr`.`saleFk` AS `Id_Movimiento`, - `tr`.`ticketFk` AS `ticketFk`, - `tr`.`response` AS `COMENTARIO`, - `tr`.`created` AS `odbc_date`, - `tr`.`ordered` AS `datORDEN`, - `tr`.`shipped` AS `datTICKET`, - `tr`.`salesPersonCode` AS `CodVENDEDOR`, - `tr`.`buyerCode` AS `CodCOMPRADOR`, - `tr`.`price__` AS `PREU`, - `tr`.`clientFk` AS `Id_CLIENTE`, - `tr`.`ok__` AS `OK`, - `tr`.`total` AS `TOTAL`, - `tr`.`buyed` AS `datCOMPRA`, - `tr`.`ko__` AS `KO` - FROM - `vn`.`ticketRequest` `tr`; - - -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn`.`ticketRequest__` AS - SELECT - `t`.`Id_ORDEN` AS `id`, - `t`.`ORDEN` AS `description`, - `t`.`requesterFk` AS `requesterFk`, - `t`.`attenderFk` AS `attenderFk`, - `t`.`CANTIDAD` AS `quantity`, - `t`.`Id_ARTICLE` AS `itemFk`, - `t`.`PRECIOMAX` AS `price`, - `t`.`isOk` AS `isOk`, - `t`.`Id_Movimiento` AS `saleFk`, - `t`.`ticketFk` AS `ticketFk`, - `t`.`COMENTARIO` AS `response`, - `t`.`odbc_date` AS `created` - FROM - `vn2008`.`Ordenes` `t`; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/01-bionicCalcReverse.sql b/db/changes/10110-postCampaign/01-bionicCalcReverse.sql deleted file mode 100644 index e3f6b1387..000000000 --- a/db/changes/10110-postCampaign/01-bionicCalcReverse.sql +++ /dev/null @@ -1,92 +0,0 @@ -DROP function IF EXISTS `vn`.`bionicCalcReverse`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`bionicCalcReverse`(vWarehouse INT, - vMargin DECIMAL(10,3), - vRetailedPrice DECIMAL(10,3), - vM3 DECIMAL(10,3), - vAddress INT, - vAgencyMode INT) RETURNS decimal(10,3) - DETERMINISTIC -BEGIN - DECLARE vGeneralInflationCoeficient INT; - DECLARE vVerdnaturaVolumeBox BIGINT; - DECLARE vClientFk INT; - DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection'; - DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana'; - DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery'; - DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin'; - DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue'; - DECLARE vComponentCostValue DECIMAL(10,2); - DECLARE vItem INT DEFAULT 98; - DECLARE vItemCarryBox INT; - - SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox - INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox - FROM bionicConfig; - - SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress; - - -- Creamos la tabla tmp.bionicComponent - DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent; - CREATE TEMPORARY TABLE tmp.bionicComponent( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `componentFk` int(10) unsigned NOT NULL, - `value` decimal(10,4) NOT NULL, - UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH, - KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE - ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - - -- Margin - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, id, vMargin - FROM component - WHERE code = vComponentMargin; - - -- Recobro - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) - FROM bi.claims_ratio cr - JOIN component c ON c.code = vComponentRecovery - WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009; - - -- Componente de maná automático, en función del maná acumulado por el comercial. - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3) - FROM client c - JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador - JOIN component co ON co.code = vComponentMana - WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1; - - -- Reparto - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient - * ROUND( - vM3 - * az.price - * az.inflation - / vVerdnaturaVolumeBox, 4 - ) - FROM agencyMode ag - JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode - JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk - AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk - JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode - AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse - JOIN component co ON co.code = vComponentPort; - - -- Coste - SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue - FROM tmp.bionicComponent; - - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, id,vComponentCostValue - FROM component - WHERE code = vComponentCost; - - RETURN vComponentCostValue; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql b/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql deleted file mode 100644 index 97249bd8a..000000000 --- a/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql +++ /dev/null @@ -1,96 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`timeBusiness_calculate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) -BEGIN - -/** - * Horas que debe trabajar un empleado según contrato y día. - * @param vDatedFrom workerTimeControl - * @param vDatedTo workerTimeControl - * @table tmp.user(userFk) - * @return tmp.timeBusinessCalculate - */ - DECLARE vHoursFullTime INT DEFAULT 40; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; - DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime; - - CALL rangeDateInfo(vDatedFrom, vDatedTo); - - CREATE TEMPORARY TABLE tmp.timeBusinessCalculate - SELECT dated, - businessFk, - userFk, - departmentFk, - hourStart, - hourEnd, - timeWorkSeconds, - SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, - timeWorkSeconds / 3600 timeWorkDecimal, - timeWorkSeconds timeBusinessSeconds, - SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal, - timeWorkSeconds / 3600 timeBusinessDecimal, - type, - permissionrate, - hoursWeek - FROM(SELECT rd.dated, - b.business_id businessFk, - w.userFk, - bl.department_id departmentFk, - IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,2) ORDER BY j.start ASC SEPARATOR '-')) hourStart , - IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,2) ORDER BY j.end ASC SEPARATOR '-')) hourEnd, - IF(cl.hours_week = vHoursFullTime, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)),0)) timeWorkSeconds, - cs.type, - cs.permissionRate, - cl.hours_week hoursWeek - FROM tmp.rangeDate rd - LEFT JOIN postgresql.business b ON rd.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) - LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id - LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id - LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id - JOIN tmp.`user` u ON u.userFK = w.userFK - JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id - LEFT JOIN postgresql.business_labour_payroll AS bp ON bl.business_id = bp.business_id - LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id - LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id - LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id - LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(rd.dated)+1 - LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = rd.dated - LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id - WHERE rd.dated BETWEEN vDatedFrom AND vDatedTo - GROUP BY w.userFk,dated - )sub; - - - UPDATE tmp.timeBusinessCalculate t - SET t.timeWorkSeconds = vHoursFullTime / 5 * 3600, - t.timeWorkSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), - t.timeWorkDecimal = vHoursFullTime / 5, - t.timeBusinessSeconds = vHoursFullTime / 5 * 3600, - t.timeBusinessSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), - t.timeBusinessDecimal = vHoursFullTime / 5 - WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND hoursWeek = vHoursFullTime ; - - UPDATE tmp.timeBusinessCalculate t - SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate) , - t.timeWorkSexagesimal = SEC_TO_TIME(t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate)), - t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionrate) - WHERE permissionrate <> 0; - - UPDATE tmp.timeBusinessCalculate t - JOIN postgresql.calendar_labour cl ON cl.day = t.dated - JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = cl.workcenter_id - SET t.timeWorkSeconds = 0, - t.timeWorkSexagesimal = 0, - t.timeWorkDecimal = 0, - t.permissionrate = 1, - t.type = 'Festivo' - WHERE t.type IS NULL; - -DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; -END$$ - -DELIMITER ; - diff --git a/db/changes/10120-december/00-entryBeforeUpdate.sql b/db/changes/10120-december/00-entryBeforeUpdate.sql deleted file mode 100644 index 088ea9328..000000000 --- a/db/changes/10120-december/00-entryBeforeUpdate.sql +++ /dev/null @@ -1,58 +0,0 @@ -DROP TRIGGER IF EXISTS `vn`.`entry_beforeUpdate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`entry_beforeUpdate` - BEFORE UPDATE ON `entry` - FOR EACH ROW -BEGIN - DECLARE vIsVirtual BOOL; - DECLARE vPrintedCount INT; - DECLARE vHasDistinctWarehouses BOOL; - - IF !(NEW.travelFk <=> OLD.travelFk) THEN - SELECT COUNT(*) > 0 INTO vIsVirtual - FROM entryVirtual WHERE entryFk = NEW.id; - - SELECT !(o.warehouseInFk <=> n.warehouseInFk) - OR !(o.warehouseOutFk <=> n.warehouseOutFk) - INTO vHasDistinctWarehouses - FROM travel o, travel n - WHERE o.id = OLD.travelFk - AND n.id = NEW.travelFk; - - IF vIsVirtual AND vHasDistinctWarehouses THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; - END IF; - - IF NEW.travelFk IS NULL THEN - SELECT COUNT(*) INTO vPrintedCount - FROM buy - WHERE entryFk = OLD.id - AND printedStickers > 0; - - IF vPrintedCount > 0 THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'An entry that contains lines with printed labels cannot be deleted'; - END IF; - END IF; - END IF; - - IF !(NEW.supplierFk <=> OLD.supplierFk) THEN - SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); - END IF; - - IF !(NEW.travelFk <=> OLD.travelFk) - OR !(NEW.currencyFk <=> OLD.currencyFk) THEN - SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); - END IF; - - IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN - INSERT INTO entryLog SET - action = 'update', - description = 'Cambia a Contabilizada', - userFk = myWorker_getId(), - originFk = NEW.id; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10120-december/00-expedition_beforeInsert.sql b/db/changes/10120-december/00-expedition_beforeInsert.sql deleted file mode 100644 index 819cd7a7f..000000000 --- a/db/changes/10120-december/00-expedition_beforeInsert.sql +++ /dev/null @@ -1,33 +0,0 @@ -DROP TRIGGER IF EXISTS `vn`.`expedition_beforeInsert`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`expedition_beforeInsert` - BEFORE INSERT ON `expedition` FOR EACH ROW -BEGIN - DECLARE intcounter INT; - DECLARE vShipFk INT; - - IF NEW.isBox > 0 THEN - - UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; - - SELECT IFNULL(MAX(counter),0) +1 INTO intcounter - FROM expedition e - INNER JOIN ticket t1 ON e.ticketFk = t1.id - LEFT JOIN ticketState ts ON ts.ticket = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) - AND t1.warehouseFk = t2.warehouseFk - WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk - AND t1.agencyModeFk = t2.agencyModeFk; - - SET NEW.`counter` = intcounter; - END IF; - - SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk; - - IF vShipFk THEN - CALL stowaway_unboarding(vShipFk, NEW.ticketFk); - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10120-december/00-stowaway_unboarding.sql b/db/changes/10120-december/00-stowaway_unboarding.sql deleted file mode 100644 index 271baba6c..000000000 --- a/db/changes/10120-december/00-stowaway_unboarding.sql +++ /dev/null @@ -1,31 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`stowawayUnBoarding`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `stowaway_unboarding`(vShipFk INT, vStowawayFk INT) -BEGIN - DECLARE vWorker VARCHAR(255); - - DELETE FROM stowaway - WHERE shipFk = vShipFk AND id = vStowawayFk; - - DELETE tt FROM ticketTracking tt - JOIN state s ON s.id = tt.stateFk - WHERE code = 'BOARDING' AND ticketFk = vShipFk; - - DELETE FROM sale - WHERE ticketFk = vShipFk - AND itemFk = 98 - AND concept = CONCAT('POLIZÓN! ',vStowawayFk); - - SELECT u.`name` INTO vWorker - FROM account.user u JOIN worker w ON w.userFk = u.id - WHERE w.id = client_getSalesPersonByTicket(vStowawayFk); - - SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a; -END$$ - -DELIMITER ; -; diff --git a/db/changes/10120-december/00-tpvTransaction.sql b/db/changes/10120-december/00-tpvTransaction.sql deleted file mode 100644 index 10ec8082c..000000000 --- a/db/changes/10120-december/00-tpvTransaction.sql +++ /dev/null @@ -1,120 +0,0 @@ - -DROP procedure IF EXISTS `hedera`.`tpvTransaction_confirm`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_confirm`( - vAmount INT - ,vOrder INT - ,vMerchant INT - ,vCurrency INT - ,vResponse INT - ,vErrorCode VARCHAR(10) -) -BEGIN -/** - * Confirma una transacción previamente iniciada, reescribiendo - * sus datos por los confirmados por el banco (solo si estos difieren). - * Genera el recibo y su correspondiente entrada en caja. - * - * @param vAmount Cantidad confirmada - * @param vOrder Identificador de transacción - * @param vMerchant Identificador de comercio - * @param vCurrency Identificador de moneda - * @param vResponse Identificador de respuesta del banco - * @param vErrorCode Código de error del banco, si lo hubiera - */ - DECLARE vReceipt INT; - DECLARE vStatus VARCHAR(10); - DECLARE vCustomer INT; - DECLARE vBank INT; - DECLARE vCompany INT; - DECLARE vEmployee INT; - DECLARE vIsDuplicated BOOLEAN; - DECLARE vDate DATE; - DECLARE vConcept VARCHAR(25) DEFAULT 'Cobro Web'; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT COUNT(*) > 0 INTO vIsDuplicated - FROM tpvTransaction - WHERE id = vOrder AND response IS NOT NULL - FOR UPDATE; - - IF vIsDuplicated - THEN - CALL util.throw ('TRANSACTION_DUPLICATED'); - END IF; - - IF vResponse BETWEEN 0 AND 99 - THEN - SELECT - t.clientFk - ,m.bankFk - ,m.companyFk - ,c.employeeFk - ,DATE(t.created) - INTO - vCustomer - ,vBank - ,vCompany - ,vEmployee - ,vDate - FROM tpvMerchant m - JOIN tpvConfig c - LEFT JOIN tpvTransaction t ON t.id = vOrder - WHERE m.id = vMerchant; - - INSERT INTO vn.receipt - SET - amountPaid = vAmount / 100 - ,payed = vDate - ,workerFk = vEmployee - ,bankFk = vBank - ,clientFk = vCustomer - ,companyFk = vCompany - ,invoiceFk = vConcept - ,isConciliate = TRUE; - - SET vReceipt = LAST_INSERT_ID(); - SET vStatus = 'ok'; - - -- Código redundante - - DO vn.till_new - ( - vCustomer - ,vBank - ,vAmount / 100 - ,vConcept - ,vDate - ,'A' - ,TRUE - ,vCustomer - ,vCompany - ,vEmployee - ); - ELSE - SET vReceipt = NULL; - SET vStatus = 'ko'; - END IF; - - UPDATE tpvTransaction - SET - merchantFk = vMerchant - ,receiptFk = vReceipt - ,amount = vAmount - ,response = vResponse - ,errorCode = vErrorCode - ,status = vStatus - WHERE id = vOrder; - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/changes/10120-december/00-tpvTransaction_undo.sql b/db/changes/10120-december/00-tpvTransaction_undo.sql deleted file mode 100644 index ee7bcc5d1..000000000 --- a/db/changes/10120-december/00-tpvTransaction_undo.sql +++ /dev/null @@ -1,86 +0,0 @@ - -DROP procedure IF EXISTS `hedera`.`tpvTransaction_undo`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_undo`(vSelf INT) -BEGIN - DECLARE vCustomer INT; - DECLARE vAmount DOUBLE; - DECLARE vReceipt INT; - DECLARE vDate DATE; - DECLARE vBank INT; - DECLARE vAccount VARCHAR(12); - DECLARE vSubaccount VARCHAR(12); - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT - t.clientFk - ,t.amount / 100 - ,t.receiptFk - ,DATE(t.created) - ,m.bankFk - INTO - vCustomer - ,vAmount - ,vReceipt - ,vDate - ,vBank - FROM tpvTransaction t - JOIN tpvMerchant m ON m.id = t.merchantFk - JOIN tpvConfig c - WHERE t.id = vSelf - FOR UPDATE; - - -- Elimina el recibo - - DELETE FROM vn.receipt - WHERE id = vReceipt LIMIT 1; - - -- Elimina la entrada de cajas - - DELETE FROM vn.till - WHERE bankFk = vBank - AND DATE(dated) = vDate - AND `in` = vAmount - LIMIT 1; - - -- Elimina los asientos contables - - SELECT accountingAccount INTO vSubaccount - FROM vn.`client` WHERE id = vCustomer; - - SELECT account INTO vAccount - FROM vn.bank WHERE id = vBank; - - DELETE FROM vn.XDiario - WHERE SUBCTA = vSubaccount - AND CONTRA = vAccount - AND DATE(FECHA) = vDate - AND EUROHABER = vAmount - LIMIT 1; - - DELETE FROM vn.XDiario - WHERE CONTRA = vSubaccount - AND SUBCTA = vAccount - AND DATE(FECHA) = vDate - AND EURODEBE = vAmount - LIMIT 1; - - -- Actualiza la transaccion - - UPDATE tpvTransaction - SET response = NULL, status = 'started' - WHERE id = vSelf; - - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 05171dbfa..687f05518 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -23,7 +23,7 @@ USE `util`; LOCK TABLES `config` WRITE; /*!40000 ALTER TABLE `config` DISABLE KEYS */; -INSERT INTO `config` VALUES (1,'10080',0,'production',NULL); +INSERT INTO `config` VALUES (1,'10120',0,'production',NULL); /*!40000 ALTER TABLE `config` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -36,7 +36,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `account`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -94,7 +94,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `salix`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -119,7 +119,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','*','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','WRITE','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(193,'Zone','editPrices','WRITE','ALLOW','ROLE','deliveryBoss'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','*','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','WRITE','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(193,'Zone','editPrices','WRITE','ALLOW','ROLE','deliveryBoss'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','salesAssistant'),(203,'UserPhone','*','WRITE','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; @@ -142,7 +142,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `vn`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -287,7 +287,7 @@ UNLOCK TABLES; LOCK TABLES `state` WRITE; /*!40000 ALTER TABLE `state` DISABLE KEYS */; -INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0),(2,'Libre',1,0,'FREE',NULL,2,0,0),(3,'OK',3,0,'OK',3,28,1,0),(4,'Impreso',4,1,'PRINTED',2,29,1,0),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1),(7,'Sin Acabar',2,0,'NOT_READY',NULL,7,0,0),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1),(9,'Encajando',9,1,'PACKING',NULL,9,0,1),(10,'Encajado',10,2,'PACKED',NULL,10,0,1),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0),(24,'Encadenado',3,0,'CHAINED',4,24,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0); +INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0),(2,'Libre',1,0,'FREE',NULL,2,0,0,0),(3,'OK',3,0,'OK',3,28,1,0,0),(4,'Impreso',4,1,'PRINTED',2,29,1,0,1),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0),(7,'Sin Acabar',2,0,'NOT_READY',NULL,7,0,0,0),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0),(9,'Encajando',9,1,'PACKING',NULL,9,0,1,0),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1,0),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0,0),(24,'Encadenado',3,0,'CHAINED',4,24,0,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0,0),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0,1); /*!40000 ALTER TABLE `state` ENABLE KEYS */; UNLOCK TABLES; @@ -297,7 +297,7 @@ UNLOCK TABLES; LOCK TABLES `sample` WRITE; /*!40000 ALTER TABLE `sample` DISABLE KEYS */; -INSERT INTO `sample` VALUES (1,'Carta_1','Aviso inicial por saldo deudor',0,'0'),(2,'Carta_2','Reiteracion de aviso por saldo deudor',0,'0'),(3,'Cred_Up','Notificación de aumento de crédito',0,'0'),(4,'Cred_down','Notificación de reducción de crédito',0,'0'),(5,'Pet_CC','Petición de datos bancarios B2B',0,'0'),(6,'SolCredito','Solicitud de crédito',0,'0'),(7,'LeyPago','Ley de pagos',0,'0'),(8,'Pet_CC_Core','Petición de datos bancarios CORE',0,'0'),(9,'nueva_alta','Documento de nueva alta de cliente',0,'0'),(10,'client_welcome','Email de bienvenida para nuevo cliente',0,'0'),(11,'setup_printer','Email de instalación de impresora',0,'0'),(12,'client-welcome','Email de bienvenida como nuevo cliente',1,'0'),(13,'printer-setup','Email de instalación y configuración de impresora de coronas',1,'0'),(14,'sepa-core','Email de solicitud de datos bancarios core',1,'1'),(15,'letter-debtor-st','Email de aviso inicial por saldo deudor',1,'1'),(16,'letter-debtor-nd','Email de aviso reiterado por saldo deudor',1,'1'),(17,'client-lcr','Email de solicitud de datos bancarios LCR',1,'1'); +INSERT INTO `sample` VALUES (1,'Carta_1','Aviso inicial por saldo deudor',0,'0'),(2,'Carta_2','Reiteracion de aviso por saldo deudor',0,'0'),(3,'Cred_Up','Notificación de aumento de crédito',0,'0'),(4,'Cred_down','Notificación de reducción de crédito',0,'0'),(5,'Pet_CC','Petición de datos bancarios B2B',0,'0'),(6,'SolCredito','Solicitud de crédito',0,'0'),(7,'LeyPago','Ley de pagos',0,'0'),(8,'Pet_CC_Core','Petición de datos bancarios CORE',0,'0'),(9,'nueva_alta','Documento de nueva alta de cliente',0,'0'),(10,'client_welcome','Email de bienvenida para nuevo cliente',0,'0'),(11,'setup_printer','Email de instalación de impresora',0,'0'),(12,'client-welcome','Bienvenida como nuevo cliente',1,'0'),(13,'printer-setup','Instalación y configuración de impresora de coronas',1,'0'),(14,'sepa-core','Solicitud de domiciliación bancaria',1,'1'),(15,'letter-debtor-st','Aviso inicial por saldo deudor',1,'1'),(16,'letter-debtor-nd','Aviso reiterado por saldo deudor',1,'1'),(17,'client-lcr','Email de solicitud de datos bancarios LCR',0,'1'); /*!40000 ALTER TABLE `sample` ENABLE KEYS */; UNLOCK TABLES; @@ -307,7 +307,7 @@ UNLOCK TABLES; LOCK TABLES `department` WRITE; /*!40000 ALTER TABLE `department` DISABLE KEYS */; -INSERT INTO `department` VALUES (1,'VERDNATURA',1,78,763,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(22,'COMPRAS',65,66,NULL,72,596,2,5,0,0,1,0,NULL,NULL),(23,'CAMARA',41,42,NULL,72,604,2,6,1,0,0,0,NULL,NULL),(31,'INFORMATICA',11,12,NULL,72,127,3,9,0,0,0,0,NULL,NULL),(34,'CONTABILIDAD',4,5,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(35,'FINANZAS',6,7,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(36,'LABORAL',8,9,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(37,'PRODUCCION',15,24,NULL,72,230,3,11,0,0,0,0,NULL,NULL),(38,'SACADO',20,21,NULL,72,230,4,14,1,0,0,0,NULL,NULL),(39,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,0,0,NULL,NULL),(41,'ADMINISTRACION',3,10,NULL,72,599,3,8,0,0,0,0,NULL,NULL),(43,'VENTAS',51,64,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(44,'GERENCIA',2,25,NULL,72,300,2,7,0,0,0,0,NULL,NULL),(45,'LOGISTICA',26,37,NULL,72,596,3,19,0,0,0,0,NULL,NULL),(46,'REPARTO',38,39,NULL,72,659,3,10,0,0,0,0,NULL,NULL),(48,'ALMACENAJE',40,47,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(49,'PROPIEDAD',48,75,NULL,72,1008,1,1,0,0,0,0,NULL,NULL),(52,'CARGA AEREA',27,28,NULL,72,163,4,28,0,0,0,0,NULL,NULL),(53,'MARKETING Y COMUNICACIÓN',60,61,NULL,72,1238,0,0,0,0,0,0,NULL,NULL),(54,'ORNAMENTALES',76,77,NULL,72,433,3,21,0,0,0,0,NULL,NULL),(55,'TALLER NATURAL',68,69,NULL,72,695,2,23,0,0,0,0,NULL,NULL),(56,'TALLER ARTIFICIAL',70,71,NULL,72,1780,2,24,0,0,0,0,NULL,NULL),(58,'CAMPOS',73,74,NULL,72,225,2,2,0,0,0,0,NULL,NULL),(59,'MANTENIMIENTO',49,50,NULL,72,1907,4,16,0,0,0,0,NULL,NULL),(60,'RECLAMACIONES',58,59,NULL,72,563,3,20,0,0,0,0,NULL,NULL),(61,'VNH',35,36,NULL,73,1297,3,17,0,0,0,0,NULL,NULL),(63,'VENTAS FRANCIA',62,63,NULL,72,277,2,27,0,0,0,0,NULL,NULL),(66,'VERDNAMADRID',31,32,NULL,72,163,3,18,0,0,0,0,NULL,NULL),(68,'COMPLEMENTOS',43,44,NULL,72,617,3,26,1,0,0,0,NULL,NULL),(69,'VERDNABARNA',33,34,NULL,74,432,3,22,0,0,0,0,NULL,NULL),(77,'PALETIZADO',18,19,NULL,72,230,4,15,1,0,0,0,NULL,NULL),(80,'EQUIPO J VALLES',56,57,NULL,72,693,3,4,0,0,0,0,NULL,NULL),(86,'LIMPIEZA',13,14,NULL,72,599,0,0,0,0,0,0,NULL,NULL),(89,'COORDINACION',16,17,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,NULL),(90,'TRAILER',29,30,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(91,'ARTIFICIAL',45,46,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,NULL),(92,'EQUIPO SILVERIO',54,55,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(93,'CONFECCION',67,72,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(94,'EQUIPO J BROCAL',52,53,NULL,0,NULL,NULL,NULL,0,0,1,0,NULL,NULL); +INSERT INTO `department` VALUES (1,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(22,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/'),(23,'CAMARA',5,6,NULL,72,604,2,6,1,0,0,0,NULL,'/'),(31,'INFORMATICA',7,8,NULL,72,127,3,9,0,0,0,0,NULL,'/'),(34,'CONTABILIDAD',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(35,'FINANZAS',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(36,'LABORAL',13,14,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(37,'PRODUCCION',15,24,NULL,72,230,3,11,0,0,0,4,NULL,'/'),(38,'SACADO',16,17,NULL,72,230,4,14,1,0,1,0,37,'/37/'),(39,'ENCAJADO',18,19,NULL,72,230,4,12,1,0,1,0,37,'/37/'),(41,'ADMINISTRACION',25,26,NULL,72,599,3,8,0,0,0,0,NULL,'/'),(43,'VENTAS',27,38,NULL,0,NULL,NULL,NULL,0,0,0,5,NULL,'/'),(44,'GERENCIA',39,40,NULL,72,300,2,7,0,0,0,0,NULL,'/'),(45,'LOGISTICA',41,42,NULL,72,596,3,19,0,0,0,0,NULL,'/'),(46,'REPARTO',20,21,NULL,72,659,3,10,0,0,1,0,37,'/37/'),(48,'ALMACENAJE',43,44,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(49,'PROPIEDAD',45,46,NULL,72,1008,1,1,0,0,0,0,NULL,'/'),(52,'CARGA AEREA',47,48,NULL,72,163,4,28,0,0,0,0,NULL,'/'),(53,'MARKETING Y COMUNICACIÓN',49,50,NULL,72,1238,0,0,0,0,0,0,NULL,'/'),(54,'ORNAMENTALES',51,52,NULL,72,433,3,21,0,0,0,0,NULL,'/'),(55,'TALLER NATURAL',53,54,NULL,72,695,2,23,0,0,0,0,NULL,'/'),(56,'TALLER ARTIFICIAL',55,56,NULL,72,1780,2,24,0,0,0,0,NULL,'/'),(58,'CAMPOS',57,58,NULL,72,225,2,2,0,0,0,0,NULL,'/'),(59,'MANTENIMIENTO',59,60,NULL,72,1907,4,16,0,0,0,0,NULL,'/'),(60,'RECLAMACIONES',61,62,NULL,72,563,3,20,0,0,0,0,NULL,'/'),(61,'VNH',63,64,NULL,73,1297,3,17,0,0,0,0,NULL,'/'),(63,'VENTAS FRANCIA',28,29,NULL,72,277,2,27,0,0,1,0,43,'/43/'),(66,'VERDNAMADRID',65,66,NULL,72,163,3,18,0,0,0,0,NULL,'/'),(68,'COMPLEMENTOS',67,68,NULL,72,617,3,26,1,0,0,0,NULL,'/'),(69,'VERDNABARNA',69,70,NULL,74,432,3,22,0,0,0,0,NULL,'/'),(77,'PALETIZADO',22,23,NULL,72,230,4,15,1,0,1,0,37,'/37/'),(80,'EQUIPO J VALLES',30,31,NULL,72,693,3,4,0,0,1,0,43,'/43/'),(86,'LIMPIEZA',71,72,NULL,72,599,0,0,0,0,0,0,NULL,'/'),(89,'COORDINACION',73,74,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/'),(90,'TRAILER',75,76,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(91,'ARTIFICIAL',77,78,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/'),(92,'EQUIPO SILVERIO',32,33,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/'),(93,'CONFECCION',79,80,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(94,'EQUIPO J BROCAL',34,35,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/'),(95,'EQUIPO C ZAMBRANO',36,37,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/'); /*!40000 ALTER TABLE `department` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -320,7 +320,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `bi`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -368,7 +368,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `cache`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -406,7 +406,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:15 USE `hedera`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -464,7 +464,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:58 +-- Dump completed on 2019-12-20 11:02:15 USE `postgresql`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -552,4 +552,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:58 +-- Dump completed on 2019-12-20 11:02:15 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index c6d7592f9..85d510f28 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -20,6 +20,18 @@ INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVo VALUES (1.30, 167.00, 138000, 71); +INSERT INTO `vn`.`chatConfig` (`uri`) + VALUES + ('https://chat.verdnatura.es/api/v1'); + +INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`) + VALUES + ('1', '11'); + +INSERT INTO `vn`.`packagingConfig`(`upperGap`) + VALUES + ('10'); + UPDATE `account`.`role` SET id = 100 WHERE id = 0; INSERT INTO `account`.`user`(`id`,`name`, `nickname`, `password`,`role`,`active`,`email`, `lang`) @@ -1914,6 +1926,11 @@ INSERT INTO `vn`.`queuePriority`(`id`, `priority`) (2, 'Normal'), (3, 'Baja'); +INSERT INTO `vn`.`userPhoneType` (`code`, `description`) + VALUES + ('businessPhone', 'Telefono de empresa del usuario'), + ('personalPhone', 'Telefono personal del usuario'); + INSERT INTO `vn`.`userPhone`(`id`, `userFk`, `typeFk`, `phone`) VALUES (1, 101, 'personalPhone', 1111111111), diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 3554c9db6..901153a58 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -2919,55 +2919,55 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, 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 - tp.Tipo AS Familia, - r.reino AS Reino, - tr.CodigoTrabajador AS Comercial, - tr2.CodigoTrabajador AS Comprador, - p.name AS Provincia, - w.name AS almacen, - tm.year AS Año, - tm.month AS Mes, - tm.week AS Semana, - v.vista AS Vista, - bt.importe AS Importe - FROM bs.ventas bt - LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador - LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador - JOIN vn2008.time tm ON tm.date = bt.fecha - JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento - LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista - LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna - LEFT JOIN vn2008.province p ON p.province_id = cs.province_id - LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id - WHERE bt.fecha >= vLastMonth AND r.mercancia; +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, 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 + tp.Tipo AS Familia, + r.reino AS Reino, + tr.CodigoTrabajador AS Comercial, + tr2.CodigoTrabajador AS Comprador, + p.name AS Provincia, + w.name AS almacen, + tm.year AS Año, + tm.month AS Mes, + tm.week AS Semana, + v.vista AS Vista, + bt.importe AS Importe + FROM bs.ventas bt + LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id + LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id + LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador + LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador + JOIN vn2008.time tm ON tm.date = bt.fecha + JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento + LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia + LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista + LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna + LEFT JOIN vn2008.province p ON p.province_id = cs.province_id + LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id + WHERE bt.fecha >= vLastMonth AND r.mercancia; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2985,33 +2985,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `call_add`() -BEGIN - DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ; - - -- Seleccionamos la ultima fecha introducida - SELECT MAX(Fecha) INTO datSTART FROM `call`; - - -- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos - DELETE FROM `call` WHERE Fecha = datSTART; - - INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) - SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, - dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone - FROM ( - SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, - hour(calldate) as Hora,src as phone - FROM vn2008.Trabajadores T - JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') - WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration - UNION ALL - SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst - FROM vn2008.Trabajadores T - JOIN vn2008.cdr C ON C.src = T.extension - WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration - ) ll - JOIN vn2008.Permisos USING(Id_Trabajador) - LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone - WHERE Id_Grupo = 6; +BEGIN + DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ; + + -- Seleccionamos la ultima fecha introducida + SELECT MAX(Fecha) INTO datSTART FROM `call`; + + -- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos + DELETE FROM `call` WHERE Fecha = datSTART; + + INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) + SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, + dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone + FROM ( + SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, + hour(calldate) as Hora,src as phone + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') + WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration + UNION ALL + SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.src = T.extension + WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration + ) ll + JOIN vn2008.Permisos USING(Id_Trabajador) + LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone + WHERE Id_Grupo = 6; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3029,205 +3029,205 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `claim_ratio_routine`() -BEGIN - DECLARE vMonthToRefund INT DEFAULT 4; - - /* - * PAK 2015-11-20 - * Se trata de añadir a la tabla Greuges todos los - * cargos que luego vamos a utilizar para calcular el recobro - */ - - -- descuentos comerciales COD 11 - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) - SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * - Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01' - HAVING nz(Importe) <> 0; - - DELETE mc.* - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - - INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - - UPDATE vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - SET Concepte = CONCAT('$ ',Concepte) - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01'; - - -- Reclamaciones demasiado sensibles - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe, Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim ',cm.id,' : ', m.Concepte) - ,round( -1 * ((sensib -1)/4) * Cantidad * - Preu * (100 - Descuento) / 100, 2) AS Reclamaciones - , 4 - , m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - -- Reclamaciones que pasan a Maná - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe , Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim_mana ',cm.id,' : ', m.Concepte) - ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) - AS Reclamaciones - ,3 - ,m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3 - AND cm.mana; - - -- Marcamos para no repetir - UPDATE vn2008.cl_act ca - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - SET greuge = 1 - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - -- Recobros - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT DISTINCT t.Id_Ticket - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket - JOIN vncontrol.inter i ON i.inter_id = ts.inter_id - JOIN vn2008.state s ON s.id = i.state_id - WHERE mc.Id_Componente = 17 - AND mc.greuge = 0 - AND t.Fecha >= '2016-10-01' - AND t.Fecha < CURDATE() - AND s.alert_level >= 3; - - DELETE g.* - FROM vn2008.Greuges g - JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket - WHERE Greuges_type_id = 2; - - INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, - Greuges_type_id, Id_Ticket) - SELECT Id_Cliente - ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) - AS dif - ,date(t.Fecha) - , 2 - ,tt.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc - ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 - GROUP BY t.Id_Ticket - HAVING ABS(dif) > 1; - - UPDATE vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket - SET greuge = 1 - WHERE Id_Componente = 17; - - /* - * Recalculamos la ratio de las reclamaciones, que luego - * se va a utilizar en el recobro - */ - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT Id_Cliente, 0,0,0,0 - FROM vn2008.Clientes; - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, - round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 - FROM bi.facturacion_media_anual fm - LEFT JOIN( - SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * - Cantidad * Preu * (100 - Descuento) / 100)) - AS Reclamaciones - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca - ON ca.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND cm.cl_est_id = 3 - AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) - GROUP BY cm.Id_Cliente - ) claims ON claims.Id_Cliente = fm.Id_Cliente; - - - -- Calculamos el porcentaje del recobro para añadirlo al precio de venta - UPDATE bi.claims_ratio cr - JOIN ( - SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge - FROM vn2008.Greuges - WHERE Fecha <= CURDATE() - GROUP BY Id_Cliente - ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(nz(Greuge) / - (nz(Consumo) * vMonthToRefund / 12 ) ,3)); - - -- Protección neonatos - UPDATE bi.claims_ratio cr - JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente - SET recobro = 0, Ratio = 0 - WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,CURDATE()); - - -- CLIENTE 7983, JULIAN SUAU - UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; - - -- CLIENTE 4358 - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; - - -- CLIENTE 5523, VERDECORA +BEGIN + DECLARE vMonthToRefund INT DEFAULT 4; + + /* + * PAK 2015-11-20 + * Se trata de añadir a la tabla Greuges todos los + * cargos que luego vamos a utilizar para calcular el recobro + */ + + -- descuentos comerciales COD 11 + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) + SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * + Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01' + HAVING nz(Importe) <> 0; + + DELETE mc.* + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) + SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + UPDATE vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + SET Concepte = CONCAT('$ ',Concepte) + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01'; + + -- Reclamaciones demasiado sensibles + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe, Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim ',cm.id,' : ', m.Concepte) + ,round( -1 * ((sensib -1)/4) * Cantidad * + Preu * (100 - Descuento) / 100, 2) AS Reclamaciones + , 4 + , m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Reclamaciones que pasan a Maná + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe , Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim_mana ',cm.id,' : ', m.Concepte) + ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) + AS Reclamaciones + ,3 + ,m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3 + AND cm.mana; + + -- Marcamos para no repetir + UPDATE vn2008.cl_act ca + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + SET greuge = 1 + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Recobros + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT DISTINCT t.Id_Ticket + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket + JOIN vncontrol.inter i ON i.inter_id = ts.inter_id + JOIN vn2008.state s ON s.id = i.state_id + WHERE mc.Id_Componente = 17 + AND mc.greuge = 0 + AND t.Fecha >= '2016-10-01' + AND t.Fecha < CURDATE() + AND s.alert_level >= 3; + + DELETE g.* + FROM vn2008.Greuges g + JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket + WHERE Greuges_type_id = 2; + + INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, + Greuges_type_id, Id_Ticket) + SELECT Id_Cliente + ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) + AS dif + ,date(t.Fecha) + , 2 + ,tt.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc + ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 + GROUP BY t.Id_Ticket + HAVING ABS(dif) > 1; + + UPDATE vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket + SET greuge = 1 + WHERE Id_Componente = 17; + + /* + * Recalculamos la ratio de las reclamaciones, que luego + * se va a utilizar en el recobro + */ + + REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) + SELECT Id_Cliente, 0,0,0,0 + FROM vn2008.Clientes; + + REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) + SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, + round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 + FROM bi.facturacion_media_anual fm + LEFT JOIN( + SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * + Cantidad * Preu * (100 - Descuento) / 100)) + AS Reclamaciones + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca + ON ca.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND cm.cl_est_id = 3 + AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) + GROUP BY cm.Id_Cliente + ) claims ON claims.Id_Cliente = fm.Id_Cliente; + + + -- Calculamos el porcentaje del recobro para añadirlo al precio de venta + UPDATE bi.claims_ratio cr + JOIN ( + SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge + FROM vn2008.Greuges + WHERE Fecha <= CURDATE() + GROUP BY Id_Cliente + ) g ON g.Id_Cliente = cr.Id_Cliente + SET recobro = GREATEST(0,round(nz(Greuge) / + (nz(Consumo) * vMonthToRefund / 12 ) ,3)); + + -- Protección neonatos + UPDATE bi.claims_ratio cr + JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente + SET recobro = 0, Ratio = 0 + WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,CURDATE()); + + -- CLIENTE 7983, JULIAN SUAU + UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; + + -- CLIENTE 4358 + UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; + + -- CLIENTE 5523, VERDECORA UPDATE bi.claims_ratio SET recobro = GREATEST(0.12, recobro) WHERE Id_Cliente = 5523; -- CLIENTE 15979, SERVEIS VETERINARIS - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979; - - -- CLIENTE 5189 i 8942, son de CSR i son el mateix client - UPDATE bi.claims_ratio cr - JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro - FROM bi.claims_ratio - WHERE Id_Cliente IN ( 5189,8942) - ) sub - SET cr.recobro = sub.recobro - WHERE Id_Cliente IN ( 5189,8942); + UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979; + + -- CLIENTE 5189 i 8942, son de CSR i son el mateix client + UPDATE bi.claims_ratio cr + JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro + FROM bi.claims_ratio + WHERE Id_Cliente IN ( 5189,8942) + ) sub + SET cr.recobro = sub.recobro + WHERE Id_Cliente IN ( 5189,8942); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3245,23 +3245,23 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); - - -- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; - - 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, CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); + + -- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; + + 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 */ ; @@ -3739,18 +3739,18 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bi.facturacion_media_anual; - - 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,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bi.facturacion_media_anual; + + 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,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3870,116 +3870,116 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `Greuge_Evolution_Add`() -BEGIN -/* - Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, - así como las ventas acumuladas en los ultimos 365 dias, para poder controlar - su evolucion. -*/ - DECLARE datFEC DATE; - DECLARE datFEC_TOMORROW DATE; - DECLARE datFEC_LASTYEAR DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - - GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; - SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - - END; - - SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; +BEGIN +/* + Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, + así como las ventas acumuladas en los ultimos 365 dias, para poder controlar + su evolucion. +*/ + DECLARE datFEC DATE; + DECLARE datFEC_TOMORROW DATE; + DECLARE datFEC_LASTYEAR DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + + GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; + SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + + END; + + SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; DELETE FROM bi.Greuge_Evolution WHERE Fecha >= TIMESTAMPADD(MONTH,-1,CURDATE()); - - SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), - TIMESTAMPADD(DAY,2,MAX(Fecha)) - INTO datFEC, - datFEC_TOMORROW - FROM bi.Greuge_Evolution; - - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; - - CREATE TEMPORARY TABLE maxInvoice - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha - FROM vn2008.Facturas - GROUP BY Id_Cliente - HAVING maxFecha < timestampadd(month,-2,datFEC); - - WHILE datFEC < CURDATE() DO - - REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) - - SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 - FROM ( - SELECT Id_Cliente, sum(Importe) as Greuge - FROM vn2008.Greuges - where Fecha <= datFEC - group by Id_Cliente - ) sub - RIGHT JOIN - - ( - - SELECT Id_Cliente, sum(Ventas) as Ventas - FROM - ( - - SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas - FROM bs.ventas - WHERE fecha = datFEC or fecha = datFEC_LASTYEAR - - UNION ALL - - SELECT Id_Cliente, Ventas - FROM bi.Greuge_Evolution - WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) - - ) sub - group by Id_Cliente - - ) v using(Id_Cliente) - ; - - -- Ahora calcularemos el greuge muerto - - UPDATE bi.Greuge_Evolution ge - JOIN maxInvoice m using(Id_Cliente) - SET FOSIL = GREUGE - WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); - - -- Recobro - - UPDATE bi.Greuge_Evolution ge - JOIN ( - SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento - WHERE t.Fecha >= datFEC - AND t.Fecha < datFEC_TOMORROW - AND mc.Id_Componente = 17 -- Recobro - GROUP BY cs.Id_Cliente - ) sub using(Id_Cliente) - SET Recobro = Importe - WHERE ge.Fecha = datFEC; - - SET datFEC = datFEC_TOMORROW; - SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - - END WHILE; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; + + SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), + TIMESTAMPADD(DAY,2,MAX(Fecha)) + INTO datFEC, + datFEC_TOMORROW + FROM bi.Greuge_Evolution; + + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; + + CREATE TEMPORARY TABLE maxInvoice + (PRIMARY KEY (Id_Cliente)) + ENGINE = MEMORY + SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha + FROM vn2008.Facturas + GROUP BY Id_Cliente + HAVING maxFecha < timestampadd(month,-2,datFEC); + + WHILE datFEC < CURDATE() DO + + REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) + + SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 + FROM ( + SELECT Id_Cliente, sum(Importe) as Greuge + FROM vn2008.Greuges + where Fecha <= datFEC + group by Id_Cliente + ) sub + RIGHT JOIN + + ( + + SELECT Id_Cliente, sum(Ventas) as Ventas + FROM + ( + + SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas + FROM bs.ventas + WHERE fecha = datFEC or fecha = datFEC_LASTYEAR + + UNION ALL + + SELECT Id_Cliente, Ventas + FROM bi.Greuge_Evolution + WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) + + ) sub + group by Id_Cliente + + ) v using(Id_Cliente) + ; + + -- Ahora calcularemos el greuge muerto + + UPDATE bi.Greuge_Evolution ge + JOIN maxInvoice m using(Id_Cliente) + SET FOSIL = GREUGE + WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); + + -- Recobro + + UPDATE bi.Greuge_Evolution ge + JOIN ( + SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe + FROM vn2008.Tickets t + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento + WHERE t.Fecha >= datFEC + AND t.Fecha < datFEC_TOMORROW + AND mc.Id_Componente = 17 -- Recobro + GROUP BY cs.Id_Cliente + ) sub using(Id_Cliente) + SET Recobro = Importe + WHERE ge.Fecha = datFEC; + + SET datFEC = datFEC_TOMORROW; + SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4063,10 +4063,10 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `nigthlyAnalisisVentas`() -BEGIN - CALL analisis_ventas_update; - CALL analisis_ventas_simple; - CALL analisis_ventas_evolution_add; +BEGIN + CALL analisis_ventas_update; + CALL analisis_ventas_simple; + CALL analisis_ventas_evolution_add; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5518,6 +5518,10 @@ CREATE TABLE `vendedores` ( `comisionArrendada` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos', `comisionCedida` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos', `comisionNuevos` decimal(10,2) DEFAULT NULL, + `sustitucionArrendada` decimal(10,2) DEFAULT NULL, + `sustitucionCedida` decimal(10,2) DEFAULT NULL, + `itemTypeLended` decimal(10,2) DEFAULT NULL, + `itemTypeBorrowed` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`Id_Trabajador`,`año`,`mes`), CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -6808,16 +6812,16 @@ BEGIN * La tabla mana_spellers es una caché * */ - - UPDATE mana_spellers me - JOIN - (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual - FROM bs.vendedores - WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) - GROUP BY Id_Trabajador - ) lastYearSales USING(Id_Trabajador) - SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; - + + UPDATE mana_spellers me + JOIN + (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual + FROM bs.vendedores + WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) + GROUP BY Id_Trabajador + ) lastYearSales USING(Id_Trabajador) + SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8859,9 +8863,9 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cacheCalc_clean`() -BEGIN - DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); - DELETE FROM cache_calc WHERE expires < vCleanTime; +BEGIN + DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); + DELETE FROM cache_calc WHERE expires < vCleanTime; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8879,27 +8883,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` 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 */ ; @@ -8917,88 +8921,88 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` 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 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 - INTO v_cache_id, v_calc, v_expires - 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 - 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 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 + INTO v_cache_id, v_calc, v_expires + 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 + 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 */ ; @@ -9016,24 +9020,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_unlock`(IN `v_calc` INT) -proc: BEGIN - DECLARE v_cache_name VARCHAR(50); - DECLARE v_params VARCHAR(100); - - IF v_calc IS NULL THEN - LEAVE proc; - END IF; - - 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; - - DELETE FROM cache_calc WHERE id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +proc: BEGIN + DECLARE v_cache_name VARCHAR(50); + DECLARE v_params VARCHAR(100); + + IF v_calc IS NULL THEN + LEAVE proc; + END IF; + + 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; + + DELETE FROM cache_calc WHERE 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 */ ; @@ -9052,9 +9056,9 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_clean`() NO SQL -BEGIN - CALL available_clean; - CALL visible_clean; +BEGIN + CALL available_clean; + CALL visible_clean; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9072,13 +9076,13 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; +BEGIN + + DECLARE vDateShort DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); + + DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10542,158 +10546,158 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) -BEGIN - DECLARE vRef INT; - DECLARE vBuy INT; - DECLARE vItem INT; - DECLARE vQty INT; - DECLARE vPackage INT; - DECLARE vIsLot BOOLEAN; - DECLARE vForceToPacking INT DEFAULT 2; - - -- Carga los datos necesarios del EKT - - SELECT ref, qty, package INTO vRef, vQty, vPackage - FROM ekt e - LEFT JOIN item i ON e.ref = i.id - WHERE e.id = vSelf; - - -- Inserta el cubo si no existe - - IF vPackage = 800 - THEN - SET vPackage = 800 + vQty; - - INSERT IGNORE INTO vn2008.Cubos SET - Id_Cubo = vPackage, - x = 7200 / vQty, - y = 1; - ELSE - INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) - SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) - FROM bucket WHERE bucket_id = vPackage; - - IF ROW_COUNT() > 0 - THEN - INSERT INTO vn2008.mail SET - `subject` = 'Cubo añadido', - `text` = CONCAT('Se ha añadido el cubo: ', vPackage), - `to` = 'ekt@verdnatura.es'; - END IF; - END IF; - - -- Intenta obtener el artículo en base a los atributos holandeses - - INSERT IGNORE INTO item_track SET - item_id = vRef; - - SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem - FROM vn2008.buy_edi e - JOIN item_track t ON t.item_id = e.ref - LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref - LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id - JOIN vn2008.config cfg - WHERE e.id = vSelf - AND l.id != vSelf - AND c.Id_Article != cfg.generic_item - AND IF(t.s1, l.s1 = e.s1, TRUE) - AND IF(t.s2, l.s2 = e.s2, TRUE) - AND IF(t.s3, l.s3 = e.s3, TRUE) - AND IF(t.s4, l.s4 = e.s4, TRUE) - AND IF(t.s5, l.s5 = e.s5, TRUE) - AND IF(t.s6, l.s6 = e.s6, TRUE) - AND IF(t.kop, l.kop = e.kop, TRUE) - AND IF(t.pac, l.pac = e.pac, TRUE) - AND IF(t.cat, l.cat = e.cat, TRUE) - AND IF(t.ori, l.ori = e.ori, TRUE) - AND IF(t.pro, l.pro = e.pro, TRUE) - AND IF(t.sub, l.sub = e.sub, TRUE) - AND IF(t.package, l.package = e.package, TRUE) - AND c.Id_Article < 170000 - ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; - - -- Determina si el articulo se vende por lotes - - IF vItem - THEN - SELECT COUNT(*) > 0 INTO vIsLot - FROM vn2008.Articles a - LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE a.Id_Article = vItem - AND t.`transaction`; - - -- Si el articulo se vende por lotes se inserta un nuevo artículo - - IF vIsLot - THEN - INSERT INTO vn2008.Articles ( - Article - ,Medida - ,Categoria - ,Id_Origen - ,iva_group_id - ,Foto - ,Color - ,Codintrastat - ,tipo_id - ,Tallos - ) - SELECT - i.`name` - ,IFNULL(e.s1, e.pac) - ,e.cat - ,IFNULL(o.id, 17) - ,IFNULL(a.iva_group_id, 1) - ,a.Foto - ,a.Color - ,a.Codintrastat - ,IFNULL(a.tipo_id, 10) - ,IF(a.tipo_id = 15, 0, 1) - FROM vn2008.buy_edi e - LEFT JOIN item i ON i.id = e.ref - LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori - LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem - WHERE e.id = vSelf; - - SET vItem = LAST_INSERT_ID(); - END IF; - END IF; - - -- Inserta la compra asociada al EKT - - INSERT INTO vn2008.Compres - ( - Id_Entrada - ,buy_edi_id - ,Costefijo - ,Id_Article - ,`grouping` - ,caja - ,Packing - ,Cantidad - ,Productor - ,Etiquetas - ,Id_Cubo - ) - SELECT - cfg.edi_entry - ,vSelf - ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri - ,IFNULL(vItem, cfg.generic_item) - ,IFNULL(c.`grouping`, e.pac) - ,vForceToPacking - ,@pac := e.pac / @t - ,@pac * e.qty - ,s.company_name - ,e.qty - ,IFNULL(c.Id_Cubo, e.package) - FROM vn2008.buy_edi e - LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy - LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article - LEFT JOIN supplier s ON e.pro = s.supplier_id - JOIN vn2008.config cfg - WHERE e.id = vSelf - LIMIT 1; +BEGIN + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + + -- Carga los datos necesarios del EKT + + SELECT ref, qty, package INTO vRef, vQty, vPackage + FROM ekt e + LEFT JOIN item i ON e.ref = i.id + WHERE e.id = vSelf; + + -- Inserta el cubo si no existe + + IF vPackage = 800 + THEN + SET vPackage = 800 + vQty; + + INSERT IGNORE INTO vn2008.Cubos SET + Id_Cubo = vPackage, + x = 7200 / vQty, + y = 1; + ELSE + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) + SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) + FROM bucket WHERE bucket_id = vPackage; + + IF ROW_COUNT() > 0 + THEN + INSERT INTO vn2008.mail SET + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Intenta obtener el artículo en base a los atributos holandeses + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem + FROM vn2008.buy_edi e + JOIN item_track t ON t.item_id = e.ref + LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref + LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND c.Id_Article != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.kop, l.kop = e.kop, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.sub, l.sub = e.sub, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND c.Id_Article < 170000 + ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; + + -- Determina si el articulo se vende por lotes + + IF vItem + THEN + SELECT COUNT(*) > 0 INTO vIsLot + FROM vn2008.Articles a + LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id + WHERE a.Id_Article = vItem + AND t.`transaction`; + + -- Si el articulo se vende por lotes se inserta un nuevo artículo + + IF vIsLot + THEN + INSERT INTO vn2008.Articles ( + Article + ,Medida + ,Categoria + ,Id_Origen + ,iva_group_id + ,Foto + ,Color + ,Codintrastat + ,tipo_id + ,Tallos + ) + SELECT + i.`name` + ,IFNULL(e.s1, e.pac) + ,e.cat + ,IFNULL(o.id, 17) + ,IFNULL(a.iva_group_id, 1) + ,a.Foto + ,a.Color + ,a.Codintrastat + ,IFNULL(a.tipo_id, 10) + ,IF(a.tipo_id = 15, 0, 1) + FROM vn2008.buy_edi e + LEFT JOIN item i ON i.id = e.ref + LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori + LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem + WHERE e.id = vSelf; + + SET vItem = LAST_INSERT_ID(); + END IF; + END IF; + + -- Inserta la compra asociada al EKT + + INSERT INTO vn2008.Compres + ( + Id_Entrada + ,buy_edi_id + ,Costefijo + ,Id_Article + ,`grouping` + ,caja + ,Packing + ,Cantidad + ,Productor + ,Etiquetas + ,Id_Cubo + ) + SELECT + cfg.edi_entry + ,vSelf + ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri + ,IFNULL(vItem, cfg.generic_item) + ,IFNULL(c.`grouping`, e.pac) + ,vForceToPacking + ,@pac := e.pac / @t + ,@pac * e.qty + ,s.company_name + ,e.qty + ,IFNULL(c.Id_Cubo, e.package) + FROM vn2008.buy_edi e + LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy + LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article + LEFT JOIN supplier s ON e.pro = s.supplier_id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10743,154 +10747,154 @@ CREATE DEFINER=`root`@`%` PROCEDURE `exchange_new`( IN `vAuction` SMALLINT, IN `vPackage` INT, IN `vPutOrderFk` INT) -BEGIN +BEGIN /** * Adds a new exchange, generates it's barcode and * inserts/updates the transaction. When the referenced * transaction exists as provisional, updates it with - * the new values. - */ - DECLARE vEkt INT; - DECLARE vRewriteKop INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; - DECLARE vIsDuplicated BOOL; + * the new values. + */ + DECLARE vEkt INT; + DECLARE vRewriteKop INT DEFAULT NULL; + DECLARE vBarcode CHAR(15) DEFAULT NULL; + DECLARE vIsDuplicated BOOL; DECLARE vUpdateExistent BOOL DEFAULT FALSE; - DECLARE duplicateKey CONDITION FOR 1062; - - DECLARE CONTINUE HANDLER FOR duplicateKey - SET vIsDuplicated = TRUE; - - -- Generates the barcode - - IF vAgj != 0 AND vAgj IS NOT NULL - THEN - SET vBarcode = CONCAT( - LPAD(vAuction, 2, 0), - LPAD(IFNULL(vClock, 99), 2, 0), - LPAD(DAYOFYEAR(vDate), 3, 0), - IF(vClock IS NULL OR vClock = 99, - LPAD(vAgj, 7, 0), - CONCAT(LPAD(vAgj, 5, 0), '01') - ), - '0' - ); - END IF; - - -- Rewrites the kop parameter - - IF vKop IS NULL THEN - SELECT defaultKop INTO vKop FROM exchangeConfig; - END IF; - - SELECT e.kop INTO vRewriteKop - FROM mailSender e - JOIN mail m ON m.senderFk = e.id - WHERE m.id = vMailFk; - - SET vKop = IFNULL(vRewriteKop, vKop); - - -- Inserts the new transaction + DECLARE duplicateKey CONDITION FOR 1062; - SET vIsDuplicated = FALSE; - INSERT INTO ekt SET - barcode = IFNULL(vBarcode, barcode) - ,deliveryNumber = vDeliveryNumber - ,entryYear = YEAR(vDate) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk; - - -- If it exists duplicado updates it - - IF NOT vIsDuplicated - THEN - SET vEkt = LAST_INSERT_ID(); - CALL ekt_load (vEkt); - - ELSEIF vDeliveryNumber != 0 - AND vDeliveryNumber IS NOT NULL - THEN - SELECT id INTO vEkt - FROM ekt - WHERE deliveryNumber = vDeliveryNumber; - - SELECT COUNT(*) = 0 INTO vUpdateExistent - FROM ekt t - JOIN `exchange` b ON b.ektFk = t.id - JOIN exchangeConfig c - WHERE t.deliveryNumber = vDeliveryNumber - AND t.entryYear = YEAR(vDate) - AND b.typeFk != c.presaleFk; - END IF; - - IF vUpdateExistent - THEN - UPDATE ekt SET - barcode = IFNULL(vBarcode, barcode) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk - WHERE id = vEkt; - END IF; - - -- Registers the exchange - - INSERT INTO `exchange` SET - mailFk = vMailFk - ,typeFk = vType - ,ektFk = vEkt; + DECLARE CONTINUE HANDLER FOR duplicateKey + SET vIsDuplicated = TRUE; + + -- Generates the barcode + + IF vAgj != 0 AND vAgj IS NOT NULL + THEN + SET vBarcode = CONCAT( + LPAD(vAuction, 2, 0), + LPAD(IFNULL(vClock, 99), 2, 0), + LPAD(DAYOFYEAR(vDate), 3, 0), + IF(vClock IS NULL OR vClock = 99, + LPAD(vAgj, 7, 0), + CONCAT(LPAD(vAgj, 5, 0), '01') + ), + '0' + ); + END IF; + + -- Rewrites the kop parameter + + IF vKop IS NULL THEN + SELECT defaultKop INTO vKop FROM exchangeConfig; + END IF; + + SELECT e.kop INTO vRewriteKop + FROM mailSender e + JOIN mail m ON m.senderFk = e.id + WHERE m.id = vMailFk; + + SET vKop = IFNULL(vRewriteKop, vKop); + + -- Inserts the new transaction + + SET vIsDuplicated = FALSE; + INSERT INTO ekt SET + barcode = IFNULL(vBarcode, barcode) + ,deliveryNumber = vDeliveryNumber + ,entryYear = YEAR(vDate) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk; + + -- If it exists duplicado updates it + + IF NOT vIsDuplicated + THEN + SET vEkt = LAST_INSERT_ID(); + CALL ekt_load (vEkt); + + ELSEIF vDeliveryNumber != 0 + AND vDeliveryNumber IS NOT NULL + THEN + SELECT id INTO vEkt + FROM ekt + WHERE deliveryNumber = vDeliveryNumber; + + SELECT COUNT(*) = 0 INTO vUpdateExistent + FROM ekt t + JOIN `exchange` b ON b.ektFk = t.id + JOIN exchangeConfig c + WHERE t.deliveryNumber = vDeliveryNumber + AND t.entryYear = YEAR(vDate) + AND b.typeFk != c.presaleFk; + END IF; + + IF vUpdateExistent + THEN + UPDATE ekt SET + barcode = IFNULL(vBarcode, barcode) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk + WHERE id = vEkt; + END IF; + + -- Registers the exchange + + INSERT INTO `exchange` SET + mailFk = vMailFk + ,typeFk = vType + ,ektFk = vEkt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -12966,30 +12970,30 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `item_listAllocation`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255), IN `vUseIds` BOOLEAN) -BEGIN -/** - * Lists visible items and it's box sizes of the specified - * type at specified date. - * - * @param vWh The warehouse id - * @param vDate The visible date - * @param vType The type id - * @param vPrefix The article prefix to filter or %NULL for all - * @param vUseIds Whether to order the result by item id - * @select List of visible items with it's box sizes - */ - CALL item_getVisible(vWh, vDate, vType, vPrefix); - - IF vUseIds - THEN - SELECT * FROM tmp.itemVisible - ORDER BY Id_Article; - ELSE - SELECT * FROM tmp.itemVisible - ORDER BY Article, packing; - END IF; - - DROP TEMPORARY TABLE tmp.itemVisible; +BEGIN +/** + * Lists visible items and it's box sizes of the specified + * type at specified date. + * + * @param vWh The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @param vUseIds Whether to order the result by item id + * @select List of visible items with it's box sizes + */ + CALL item_getVisible(vWh, vDate, vType, vPrefix); + + IF vUseIds + THEN + SELECT * FROM tmp.itemVisible + ORDER BY Id_Article; + ELSE + SELECT * FROM tmp.itemVisible + ORDER BY Article, packing; + END IF; + + DROP TEMPORARY TABLE tmp.itemVisible; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -14242,9 +14246,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -14288,9 +14292,9 @@ BEGIN GROUP BY r.warehouse_id; DECLARE cRows CURSOR FOR - SELECT r.id, r.item_id, a.Article, r.amount, r.price, r.rate + SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate FROM order_row r - JOIN vn2008.Articles a ON a.Id_Article = r.item_id + JOIN vn.item i ON i.id = r.item_id WHERE r.amount != 0 AND r.warehouse_id = vWarehouse AND r.order_id = vOrder @@ -14308,12 +14312,12 @@ BEGIN -- Carga los datos del pedido SELECT o.date_send, o.address_id, o.note, - o.confirmed, cs.Id_Cliente, o.company_id, o.agency_id + o.confirmed, a.clientFk, o.company_id, o.agency_id INTO vDelivery, vAddress, vNotes, vIsConfirmed, vClientId, vCompanyId, vAgencyModeId FROM hedera.`order` o - JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = o.address_id - WHERE id = vOrder; + JOIN vn.address a ON a.id = o.address_id + WHERE o.id = vOrder; -- Comprueba que el pedido no está confirmado @@ -14332,7 +14336,7 @@ BEGIN -- Carga las fechas de salida de cada almacén - CALL vn.zoneGetShippedWarehouse (vDelivery, vAddress, vAgencyModeId); + CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); -- Trabajador que realiza la acción @@ -14358,19 +14362,18 @@ BEGIN -- Busca un ticket existente que coincida con los parametros - SELECT Id_Ticket INTO vTicket - FROM vn2008.Tickets t - LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket + SELECT t.id INTO vTicket + FROM vn.ticket t + LEFT JOIN vn.ticketState tls on tls.ticket = t.id JOIN `order` o - ON o.address_id = t.Id_Consigna - AND vWarehouse = t.warehouse_id - AND o.agency_id = t.Id_Agencia - AND t.landing = o.date_send - AND vShipment = DATE(t.Fecha) + ON o.address_id = t.addressFk + AND vWarehouse = t.warehouseFk + AND o.agency_id = t.agencyModeFk + AND o.date_send = t.landed + AND vShipment = DATE(t.shipped) WHERE o.id = vOrder - AND t.Factura IS NULL + AND t.invoiceOutFk IS NULL AND IFNULL(tls.alertLevel,0) = 0 - AND t.Id_Cliente <> 1118 LIMIT 1; -- Crea el ticket en el caso de no existir uno adecuado @@ -14392,23 +14395,24 @@ BEGIN ELSE INSERT INTO vncontrol.inter SET Id_Ticket = vTicket, + Id_Trabajador = vUserId, state_id = TICKET_FREE; END IF; - INSERT IGNORE INTO vn2008.order_Tickets - SET order_id = vOrder, - Id_Ticket = vTicket; + INSERT IGNORE INTO vn.orderTicket + SET orderFk = vOrder, + ticketFk = vTicket; -- Añade las notas IF vNotes IS NOT NULL AND vNotes != '' THEN - INSERT INTO vn2008.ticket_observation SET - Id_Ticket = vTicket, - observation_type_id = 4 /* salesperson */ , - `text` = vNotes + INSERT INTO vn.ticketObservation SET + ticketFk = vTicket, + observationTypeFk = 4 /* salesperson */ , + `description` = vNotes ON DUPLICATE KEY UPDATE - `text` = CONCAT(VALUES(`text`),'. ', `text`); + `description` = CONCAT(VALUES(`description`),'. ', `description`); END IF; -- Añade los movimientos y sus componentes @@ -14424,20 +14428,20 @@ BEGIN LEAVE lRows; END IF; - INSERT INTO vn2008.Movimientos + INSERT INTO vn.sale SET - Id_Article = vItem, - Id_Ticket = vTicket, - Concepte = vConcept, - Cantidad = vAmount, - Preu = vPrice, - CostFixat = 0, - PrecioFijado = TRUE; + itemFk = vItem, + ticketFk = vTicket, + concept = vConcept, + quantity = vAmount, + price = vPrice, + priceFixed = 0, + isPriceFixed = TRUE; SET vSale = LAST_INSERT_ID(); - INSERT INTO vn2008.Movimientos_componentes - (Id_Movimiento, Id_Componente, Valor) + INSERT INTO vn.saleComponent + (saleFk, componentFk, `value`) SELECT vSale, cm.component_id, cm.price FROM order_component cm JOIN bi.tarifa_componentes tc @@ -14458,20 +14462,20 @@ BEGIN CREATE TEMPORARY TABLE tComponents (INDEX (saleFk)) ENGINE = MEMORY - SELECT SUM(mc.Valor) valueSum, mc.Id_Movimiento saleFk - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc USING(Id_Componente) + SELECT SUM(sc.`value`) valueSum, sc.saleFk + FROM vn.saleComponent sc + JOIN bi.tarifa_componentes tc ON tc.Id_Componente = sc.componentFk JOIN bi.tarifa_componentes_series tcs ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base - JOIN vn2008.Movimientos m - ON m.Id_Movimiento = mc.Id_Movimiento - WHERE m.Id_Ticket = vTicket - GROUP BY mc.Id_Movimiento; + JOIN vn.sale s + ON s.id = sc.saleFk + WHERE s.ticketFk = vTicket + GROUP BY sc.saleFk; - UPDATE vn2008.Movimientos m - JOIN tComponents mc ON mc.saleFk = m.Id_Movimiento - SET m.CostFixat = valueSum; + UPDATE vn.sale s + JOIN tComponents mc ON mc.saleFk = s.id + SET s.priceFixed = valueSum; DROP TEMPORARY TABLE tComponents; END LOOP; @@ -15148,9 +15152,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -15218,7 +15222,7 @@ BEGIN ,vEmployee ,vDate FROM tpvMerchant m - JOIN tpvConfig c ON c.id = 1 + JOIN tpvConfig c LEFT JOIN tpvTransaction t ON t.id = vOrder WHERE m.id = vMerchant; @@ -15238,7 +15242,7 @@ BEGIN -- Código redundante - DO vn2008.till_entry + DO vn.till_new ( vCustomer ,vBank @@ -15265,7 +15269,6 @@ BEGIN ,errorCode = vErrorCode ,status = vStatus WHERE id = vOrder; - COMMIT; END ;; DELIMITER ; @@ -15370,9 +15373,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -15414,33 +15417,33 @@ BEGIN -- Elimina el recibo - DELETE FROM vn2008.Recibos - WHERE Id = vReceipt LIMIT 1; + DELETE FROM vn.receipt + WHERE id = vReceipt LIMIT 1; -- Elimina la entrada de cajas - DELETE FROM vn2008.Cajas - WHERE Id_Banco = vBank - AND DATE(CajaFecha) = vDate - AND Entrada = vAmount + DELETE FROM vn.till + WHERE bankFk = vBank + AND DATE(dated) = vDate + AND `in` = vAmount LIMIT 1; -- Elimina los asientos contables - SELECT Cuenta INTO vSubaccount - FROM vn2008.Clientes WHERE Id_Cliente = vCustomer; + SELECT accountingAccount INTO vSubaccount + FROM vn.`client` WHERE id = vCustomer; - SELECT Cuenta INTO vAccount - FROM vn2008.Bancos WHERE Id_Banco = vBank; + SELECT account INTO vAccount + FROM vn.bank WHERE id = vBank; - DELETE FROM vn2008.XDiario + DELETE FROM vn.XDiario WHERE SUBCTA = vSubaccount AND CONTRA = vAccount AND DATE(FECHA) = vDate AND EUROHABER = vAmount LIMIT 1; - DELETE FROM vn2008.XDiario + DELETE FROM vn.XDiario WHERE CONTRA = vSubaccount AND SUBCTA = vAccount AND DATE(FECHA) = vDate @@ -17897,7 +17900,7 @@ CREATE TABLE `log` ( `tableId` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `tableName` (`tableName`,`tableId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; +) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -18292,28 +18295,98 @@ DELIMITER ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; /*!50003 SET character_set_client = utf8mb4 */ ; /*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `log_add`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) -proc: BEGIN - -- XXX: Disabled while testing - LEAVE proc; - - IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vOldId, - operation = 'delete'; - END IF; - - IF vNewId IS NOT NULL THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vNewId, - operation = 'insert'; - END IF; +proc: BEGIN + -- XXX: Disabled while testing + LEAVE proc; + + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `log_add_beta` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_add_beta`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) +proc: BEGIN + -- XXX: Disabled while testing + DECLARE vLanded DATE; + DECLARE vWarehouseFk INT; + DECLARE vBuyerFk INT; + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vItemName VARCHAR(50); + + -- LEAVE proc; + + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; + END IF; + + IF vTableName = 'buy' THEN + + SELECT IFNULL(tr.landed,'2000-01-01') + INTO vLanded + FROM vn.travel tr + JOIN vn.entry e ON e.travelFk = tr.id + JOIN vn.buy b ON b.entryFk = e.id + JOIN vn.warehouse w ON w.id = tr.warehouseInFk + WHERE b.id = vNewId + AND w.isBuyerToBeEmailed; + + IF vLanded = CURDATE() THEN + + SELECT it.workerFk, b.entryFk, i.id, i.longName + INTO vBuyerFk, vEntryFk, vItemFk, vItemName + FROM vn.itemType it + JOIN vn.item i ON i.typeFk = it.id + JOIN vn.buy b ON b.itemFk = i.id + WHERE b.id = vNewId; + + CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'), + CONCAT(account.myUserGetName(),'@verdnatura.es'), + CONCAT('E-',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName), + 'Este email se ha generado automáticamente'); + + END IF; + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18581,29 +18654,29 @@ CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshSale`( BEGIN DROP TEMPORARY TABLE IF EXISTS tValues; CREATE TEMPORARY TABLE tValues - ENGINE = MEMORY - SELECT - m.id saleFk, - m.ticketFk, - m.itemFk, - t.warehouseFk, - t.shipped, + ENGINE = MEMORY + SELECT + m.id saleFk, + m.ticketFk, + m.itemFk, + t.warehouseFk, + t.shipped, ABS(m.quantity) quantity, m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked - FROM vn.sale m - JOIN vn.ticket t ON t.id = m.ticketFk + m.isPicked OR s.alertLevel > 1 isPicked + FROM vn.sale m + JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.item i ON i.id = m.itemFk - JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.itemType tp ON tp.id = i.typeFk WHERE ( - vTableId IS NULL - OR (vTableName = 'ticket' AND t.id = vTableId) - OR (vTableName = 'sale' AND m.id = vTableId) - ) - AND t.shipped >= vn.getInventoryDate() + vTableId IS NULL + OR (vTableName = 'ticket' AND t.id = vTableId) + OR (vTableName = 'sale' AND m.id = vTableId) + ) + AND t.shipped >= vn.getInventoryDate() AND m.quantity != 0; REPLACE INTO inbound ( @@ -18636,7 +18709,7 @@ BEGIN FROM tValues WHERE !isIn; - DROP TEMPORARY TABLE tValues; + DROP TEMPORARY TABLE tValues; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -20955,6 +21028,22 @@ CREATE TABLE `chain` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Grupos de clientes'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `chatConfig` +-- + +DROP TABLE IF EXISTS `chatConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `chatConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `uri` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `user` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `password` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `claim` -- @@ -21373,9 +21462,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -21383,9 +21472,7 @@ DELIMITER ;; BEFORE UPDATE ON `client` FOR EACH ROW BEGIN - -- BERNAT: WORKING IN THIS FILE DECLARE vText VARCHAR(255) DEFAULT NULL; - -- Comprueba que el formato de los teléfonos es válido IF !(NEW.phone <=> OLD.phone) THEN @@ -21395,7 +21482,7 @@ BEGIN IF !(NEW.mobile <=> OLD.mobile) THEN CALL pbx.phone_isValid(NEW.mobile); END IF; - + IF !(NEW.fax <=> OLD.fax) THEN CALL pbx.phone_isValid(NEW.fax); END IF; @@ -21416,7 +21503,7 @@ BEGIN IF vText IS NOT NULL THEN - INSERT INTO vn2008.mail(`to`, reply_to, subject, text) + INSERT INTO mail(sender, replyTo, `subject`, body) SELECT CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), 'administracion@verdnatura.es', @@ -21862,6 +21949,22 @@ SET character_set_client = utf8; 1 AS `level`*/; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `collectionVolumetry` +-- + +DROP TABLE IF EXISTS `collectionVolumetry`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `collectionVolumetry` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `level` int(10) unsigned NOT NULL DEFAULT '0', + `lines` int(10) unsigned NOT NULL DEFAULT '1', + `liters` int(10) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `company` -- @@ -21931,7 +22034,8 @@ SET character_set_client = utf8; 1 AS `typeFk`, 1 AS `classRate`, 1 AS `tax`, - 1 AS `isRenewable`*/; + 1 AS `isRenewable`, + 1 AS `code`*/; SET character_set_client = @saved_cs_client; -- @@ -22334,21 +22438,20 @@ CREATE TABLE `creditClassification` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditClassification_BEFORE_UPDATE` BEFORE UPDATE ON `creditClassification` FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditClassification_beforeUpdate` BEFORE UPDATE ON `creditClassification` FOR EACH ROW BEGIN - -- BERNAT: WORKING IN THIS FILE IF NEW.client <> OLD.client THEN CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT'); END IF; IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN - UPDATE vn2008.Clientes c - SET creditInsurance = 0 WHERE c.Id_cliente = NEW.client; + UPDATE `client` c + SET creditInsurance = 0 WHERE c.id = NEW.client; END IF; END */;; DELIMITER ; @@ -22378,17 +22481,16 @@ CREATE TABLE `creditInsurance` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditInsurance_AFTER_INSERT` AFTER INSERT ON `creditInsurance` FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditInsurance_afterInsert` AFTER INSERT ON `creditInsurance` FOR EACH ROW BEGIN - -- BERNAT: WORKING IN THIS FILE - UPDATE vn2008.Clientes c - JOIN vn.creditClassification cc ON cc.client = c.Id_Cliente + UPDATE `client` c + JOIN vn.creditClassification cc ON cc.client = c.id SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; END */;; @@ -22737,13 +22839,18 @@ CREATE TABLE `dms` ( `contentType` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, `file` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, `hasFile` tinyint(4) NOT NULL DEFAULT '0', - `workerFk` int(11) NOT NULL, + `workerFk` int(11) DEFAULT NULL, `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `emp_id` (`companyFk`,`hardCopyNumber`,`warehouseFk`), KEY `trabajador_id` (`workerFk`), - KEY `warehouse_id` (`warehouseFk`) + KEY `warehouse_id` (`warehouseFk`), + KEY `dms_dmsTypeFk_idx` (`dmsTypeFk`), + CONSTRAINT `dms_companyFk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, + CONSTRAINT `dms_dmsTypeFk` FOREIGN KEY (`dmsTypeFk`) REFERENCES `dmsType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `dms_warehouseFk` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `dms_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='document managment system'; /*!40101 SET character_set_client = @saved_cs_client */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; @@ -23117,24 +23224,23 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_beforeUpdate` +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`entry_beforeUpdate` BEFORE UPDATE ON `entry` FOR EACH ROW BEGIN - -- Bernat: working in this file - DECLARE vIsClone BOOL; + DECLARE vIsVirtual BOOL; DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; IF !(NEW.travelFk <=> OLD.travelFk) THEN - SELECT COUNT(*) > 0 INTO vIsClone - FROM vn2008.Entradas_Auto WHERE Id_Entrada = NEW.id; + SELECT COUNT(*) > 0 INTO vIsVirtual + FROM entryVirtual WHERE entryFk = NEW.id; SELECT !(o.warehouseInFk <=> n.warehouseInFk) OR !(o.warehouseOutFk <=> n.warehouseOutFk) @@ -23143,7 +23249,7 @@ BEGIN WHERE o.id = OLD.travelFk AND n.id = NEW.travelFk; - IF vIsClone AND vHasDistinctWarehouses THEN + IF vIsVirtual AND vHasDistinctWarehouses THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; END IF; @@ -23171,12 +23277,11 @@ BEGIN END IF; IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN - INSERT INTO vn2008.Entradas_dits SET - idaccion_dits = 105, - Id_Trabajador = myWorker_getId(), - Id_Ticket = NEW.id, - value_old = OLD.isBooked, - value_new = NEW.isBooked; + INSERT INTO entryLog SET + action = 'update', + description = 'Cambia a Contabilizada', + userFk = myWorker_getId(), + originFk = NEW.id; END IF; END */;; DELIMITER ; @@ -23476,7 +23581,6 @@ CREATE TABLE `expedition` ( DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`expedition_beforeInsert` BEFORE INSERT ON `expedition` FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one BEGIN DECLARE intcounter INT; DECLARE vShipFk INT; @@ -23497,11 +23601,10 @@ BEGIN SET NEW.`counter` = intcounter; END IF; - -- JGF 14/01/19 si existe un polizon queda anulado SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk; IF vShipFk THEN - CALL stowawayUnBoarding(vShipFk, NEW.ticketFk); + CALL stowaway_unboarding(vShipFk, NEW.ticketFk); END IF; END */;; DELIMITER ; @@ -25902,6 +26005,20 @@ CREATE TABLE `packaging` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `packagingConfig` +-- + +DROP TABLE IF EXISTS `packagingConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `packagingConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `upperGap` int(11) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `parking` -- @@ -25986,6 +26103,7 @@ DROP TABLE IF EXISTS `payMethod`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `payMethod` ( `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(50) CHARACTER SET utf8 DEFAULT NULL, `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `solution` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, `outstandingDebt` tinyint(3) unsigned zerofill NOT NULL DEFAULT '000', @@ -26422,6 +26540,36 @@ CREATE TABLE `printServerQueue` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `printServerQueue2` +-- + +DROP TABLE IF EXISTS `printServerQueue2`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `printServerQueue2` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `printerFk` tinyint(3) unsigned DEFAULT NULL, + `priorityFk` tinyint(3) unsigned DEFAULT NULL, + `reportFk` tinyint(3) unsigned DEFAULT '0', + `statusFk` tinyint(3) unsigned DEFAULT '1', + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, + `param1` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `workerFk` int(11) DEFAULT '20', + `param2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `param3` text COLLATE utf8_unicode_ci, + `error` text COLLATE utf8_unicode_ci, + PRIMARY KEY (`id`), + UNIQUE KEY `Id_Impresora_2` (`printerFk`,`priorityFk`,`reportFk`,`statusFk`,`param1`,`workerFk`,`param2`), + KEY `Id_estado` (`statusFk`), + KEY `Id_Impresora` (`printerFk`), + KEY `Id_Informe` (`reportFk`), + KEY `Id_Prioridad` (`priorityFk`), + KEY `Id_Trabajador` (`workerFk`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `printingQueueCheck` -- @@ -26848,11 +26996,14 @@ CREATE TABLE `route` ( `cost` double unsigned DEFAULT NULL, `m3` decimal(10,1) unsigned DEFAULT NULL, `description` text COLLATE utf8_unicode_ci, + `zoneFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `Id_Agencia` (`agencyModeFk`), KEY `Fecha` (`created`), KEY `gestdoc_id` (`gestdocFk`), KEY `route_ibfk_2_idx` (`workerFk`), + KEY `fk_route_1_idx` (`zoneFk`), + CONSTRAINT `fk_route_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE, CONSTRAINT `route_ibfk_1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `route_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -27412,6 +27563,7 @@ CREATE TABLE `sector` ( `code` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, `pickingPlacement` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, `path` int(11) DEFAULT NULL, + `isPreviousPrepared` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`,`warehouseFk`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `sector_fk1_idx` (`warehouseFk`), @@ -27768,6 +27920,7 @@ CREATE TABLE `state` ( `nextStateFk` tinyint(4) NOT NULL COMMENT 'Estado al que tiene que cambiar el ticket despues de preparacion previa', `isPreviousPreparable` tinyint(1) NOT NULL DEFAULT '0', `isPicked` tinyint(1) NOT NULL DEFAULT '0', + `isPreparable` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `code_UNIQUE` (`code`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -28674,7 +28827,7 @@ CREATE TABLE `ticketRequest` ( `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `isOk` tinyint(1) DEFAULT NULL, `requesterFk` int(11) DEFAULT NULL, - `atenderFk` int(11) DEFAULT NULL, + `attenderFk` int(11) DEFAULT NULL, `ticketFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `Id_Movimiento_UNIQUE` (`saleFk`), @@ -28684,10 +28837,10 @@ CREATE TABLE `ticketRequest` ( KEY `Id_Movimiento` (`saleFk`), KEY `Id_Vendedor` (`salesPersonCode`), KEY `fgnRequester_idx` (`requesterFk`), - KEY `fgnAtender_idx` (`atenderFk`), + KEY `fgnAtender_idx` (`attenderFk`), KEY `fgnTicket_idx` (`ticketFk`), CONSTRAINT `fgbMovimiento` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `fgnAtender` FOREIGN KEY (`atenderFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `fgnAtender` FOREIGN KEY (`attenderFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `fgnRequester` FOREIGN KEY (`requesterFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `fgnTicket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -28695,25 +28848,25 @@ CREATE TABLE `ticketRequest` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW BEGIN - IF NEW.ticketFk IS NULL THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.requesterFk IS NULL THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; + IF NEW.ticketFk IS NULL THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; - IF NEW.atenderFk IS NULL THEN - SET NEW.atenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; + IF NEW.requesterFk IS NULL THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.attenderFk IS NULL THEN + SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28723,25 +28876,25 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW BEGIN - IF NEW.saleFk <> OLD.saleFk THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.salesPersonCode <> OLD.salesPersonCode THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; + IF NEW.saleFk <> OLD.saleFk THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; - IF NEW.buyerCode <> OLD.buyerCode THEN - SET NEW.atenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; + IF NEW.salesPersonCode <> OLD.salesPersonCode THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.buyerCode <> OLD.buyerCode THEN + SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29248,6 +29401,33 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Table structure for table `travelLog` +-- + +DROP TABLE IF EXISTS `travelLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `travelLog` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `travelObservation` -- @@ -29340,6 +29520,67 @@ CREATE TABLE `userConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuración de usuario en Salix'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `userLog` +-- + +DROP TABLE IF EXISTS `userLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `userPhone` +-- + +DROP TABLE IF EXISTS `userPhone`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userPhone` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `userFk` int(10) unsigned NOT NULL, + `typeFk` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `phone` varchar(25) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UserFk_Phone` (`userFk`,`typeFk`,`phone`), + KEY `fgnTypeFk` (`typeFk`), + CONSTRAINT `fgnTypeFk` FOREIGN KEY (`typeFk`) REFERENCES `userPhoneType` (`code`) ON UPDATE CASCADE, + CONSTRAINT `fgnUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `userPhoneType` +-- + +DROP TABLE IF EXISTS `userPhoneType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userPhoneType` ( + `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `vehicle` -- @@ -29394,6 +29635,7 @@ CREATE TABLE `warehouse` ( `hasStowaway` tinyint(1) NOT NULL DEFAULT '0', `hasDms` tinyint(1) NOT NULL DEFAULT '0', `pickUpAgencyModeFk` int(11) DEFAULT NULL, + `isBuyerToBeEmailed` tinyint(2) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `name_UNIQUE` (`name`), KEY `Id_Paises` (`countryFk`), @@ -30236,7 +30478,7 @@ CREATE TABLE `zone` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `hour` datetime NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL, + `warehouseFk__` smallint(6) unsigned DEFAULT NULL, `agencyModeFk` int(11) NOT NULL, `travelingDays` int(11) NOT NULL DEFAULT '1', `price` double NOT NULL DEFAULT '0', @@ -30244,10 +30486,10 @@ CREATE TABLE `zone` ( `isVolumetric` tinyint(1) NOT NULL DEFAULT '0', `inflation` decimal(5,2) NOT NULL DEFAULT '1.00', PRIMARY KEY (`id`), - KEY `fk_zone_1_idx` (`warehouseFk`), + KEY `fk_zone_1_idx` (`warehouseFk__`), KEY `fk_zone_2_idx` (`agencyModeFk`), KEY `zone_name_idx` (`name`), - CONSTRAINT `fk_zone_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `fk_zone_1` FOREIGN KEY (`warehouseFk__`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, CONSTRAINT `fk_zone_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; @@ -30269,6 +30511,49 @@ CREATE TABLE `zoneCalendar` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `zoneEvent` +-- + +DROP TABLE IF EXISTS `zoneEvent`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneEvent` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `type` enum('day','indefinitely','range') NOT NULL, + `dated` date DEFAULT NULL, + `started` date DEFAULT NULL, + `ended` date DEFAULT NULL, + `weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL, + `hour` datetime DEFAULT NULL, + `travelingDays` int(11) DEFAULT NULL, + `price` decimal(10,2) DEFAULT NULL, + `bonus` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `zoneFk` (`zoneFk`), + CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `zoneExclusion` +-- + +DROP TABLE IF EXISTS `zoneExclusion`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneExclusion` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `dated` date NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `zoneFk_2` (`zoneFk`,`dated`), + KEY `zoneFk` (`zoneFk`), + CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `zoneGeo` -- @@ -30366,11 +30651,47 @@ CREATE TABLE `zoneIncluded` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `zoneWarehouse` +-- + +DROP TABLE IF EXISTS `zoneWarehouse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneWarehouse` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`), + KEY `warehouseFk` (`warehouseFk`), + CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Dumping events for database 'vn' -- /*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `envialiaThreHoldChecker` */; +/*!50106 DROP EVENT IF EXISTS `department_doCalc` */; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8 */ ;; +/*!50003 SET character_set_results = utf8 */ ;; +/*!50003 SET collation_connection = utf8_general_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `envialiaThreHoldChecker` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; /*!50003 SET @saved_cs_results = @@character_set_results */ ;; @@ -30426,90 +30747,90 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN - - DECLARE vCurrentCount INT; - DECLARE vCheckSum INT; - DECLARE vIsAlreadyNotified BOOLEAN; - DECLARE vTableQueue TEXT; - DECLARE vLineQueue TEXT; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vCur CURSOR FOR - SELECT CONCAT(' - ', IFNULL(pq.id, ''), ' - ', IFNULL(p.path, ''),' - ', IFNULL(i.Informe, ''),' - ', IFNULL(e.Estado, ''),' - ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' - ', IFNULL(pq.`error`, ''),' - ') - FROM vn.printingQueue pq - LEFT JOIN vn.worker w ON w.id = pq.worker - LEFT JOIN vn.printer p ON p.id = pq.printer - LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report - JOIN vn2008.Estados e ON e.Id_Estado = pq.state - LIMIT 30; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum - FROM vn.printingQueue WHERE state = 1; - - SELECT isAlreadyNotified INTO vIsAlreadyNotified - FROM printingQueueCheck; - - IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND - (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND - vIsAlreadyNotified = FALSE AND vCurrentCount > 0 - THEN - - SELECT ' - - - - - - - - ' INTO vTableQueue; - - OPEN vCur; - - l: LOOP - - SET vDone = FALSE; - - FETCH vCur INTO vLineQueue; - - IF vDone THEN - LEAVE l; - END IF; - - SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; - - END LOOP; - - CLOSE vCur; - - INSERT INTO vn2008.mail (`to`, subject, text) - VALUES ('cau@verdnatura.es', - 'servidor de impresion parado', - CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); - - UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; - END IF; - - IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND - vIsAlreadyNotified = TRUE - THEN - UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; - END IF; - - UPDATE printingQueueCheck - SET lastCount = vCurrentCount, - lastCheckSum = vCheckSum; - +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN + + DECLARE vCurrentCount INT; + DECLARE vCheckSum INT; + DECLARE vIsAlreadyNotified BOOLEAN; + DECLARE vTableQueue TEXT; + DECLARE vLineQueue TEXT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCur CURSOR FOR + SELECT CONCAT(' + ', IFNULL(pq.id, ''), ' + ', IFNULL(p.path, ''),' + ', IFNULL(i.Informe, ''),' + ', IFNULL(e.Estado, ''),' + ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' + ', IFNULL(pq.`error`, ''),' + ') + FROM vn.printingQueue pq + LEFT JOIN vn.worker w ON w.id = pq.worker + LEFT JOIN vn.printer p ON p.id = pq.printer + LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report + JOIN vn2008.Estados e ON e.Id_Estado = pq.state + LIMIT 30; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum + FROM vn.printingQueue WHERE state = 1; + + SELECT isAlreadyNotified INTO vIsAlreadyNotified + FROM printingQueueCheck; + + IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND + (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND + vIsAlreadyNotified = FALSE AND vCurrentCount > 0 + THEN + + SELECT ' + + + + + + + + ' INTO vTableQueue; + + OPEN vCur; + + l: LOOP + + SET vDone = FALSE; + + FETCH vCur INTO vLineQueue; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; + + END LOOP; + + CLOSE vCur; + + INSERT INTO vn2008.mail (`to`, subject, text) + VALUES ('cau@verdnatura.es', + 'servidor de impresion parado', + CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); + + UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; + END IF; + + IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND + vIsAlreadyNotified = TRUE + THEN + UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; + END IF; + + UPDATE printingQueueCheck + SET lastCount = vCurrentCount, + lastCheckSum = vCheckSum; + END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -30634,6 +30955,42 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `address_getGeo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `address_getGeo`(vSelf INT) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Returns the geo for the passed address. + * + * @param vSelf The address id + * @return The geo id + */ + DECLARE vGeoFk INT; + + 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 + WHERE a.id = vSelf + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + RETURN vGeoFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `barcodeToItem` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -30678,6 +31035,107 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `bionicCalcReverse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `bionicCalcReverse`(vWarehouse INT, + vMargin DECIMAL(10,3), + vRetailedPrice DECIMAL(10,3), + vM3 DECIMAL(10,3), + vAddress INT, + vAgencyMode INT) RETURNS decimal(10,3) + DETERMINISTIC +BEGIN + DECLARE vGeneralInflationCoeficient INT; + DECLARE vVerdnaturaVolumeBox BIGINT; + DECLARE vClientFk INT; + DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection'; + DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana'; + DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery'; + DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin'; + DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue'; + DECLARE vComponentCostValue DECIMAL(10,2); + DECLARE vItem INT DEFAULT 98; + DECLARE vItemCarryBox INT; + + SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox + INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox + FROM bionicConfig; + + SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress; + + -- Creamos la tabla tmp.bionicComponent + DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent; + CREATE TEMPORARY TABLE tmp.bionicComponent( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `componentFk` int(10) unsigned NOT NULL, + `value` decimal(10,4) NOT NULL, + UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH, + KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE + ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + + -- Margin + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, id, vMargin + FROM component + WHERE code = vComponentMargin; + + -- Recobro + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) + FROM bi.claims_ratio cr + JOIN component c ON c.code = vComponentRecovery + WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009; + + -- Componente de maná automático, en función del maná acumulado por el comercial. + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3) + FROM client c + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + JOIN component co ON co.code = vComponentMana + WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1; + + -- Reparto + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient + * ROUND( + vM3 + * az.price + * az.inflation + / vVerdnaturaVolumeBox, 4 + ) + FROM agencyMode ag + JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode + JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk + AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk + JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode + AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse + JOIN component co ON co.code = vComponentPort; + + -- Coste + SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue + FROM tmp.bionicComponent; + + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, id,vComponentCostValue + FROM component + WHERE code = vComponentCost; + + RETURN vComponentCostValue; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP FUNCTION IF EXISTS `bionicCalcReverse__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -31112,27 +31570,34 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` FUNCTION `clientGetMana`(vClient INT) RETURNS decimal(10,2) - READS SQL DATA + DETERMINISTIC BEGIN /** - * BERNAT: WORKING IN THIS FILE - * Devuelve el maná del cliente. - * + * Devuelve el mana del cliente. + * * @param vClient Id del cliente - * @return Maná del cliente + * @return Mana del cliente */ - DECLARE vMana DECIMAL(10,2); DECLARE vFromDated DATE; DECLARE vHasMana BOOLEAN; - + DECLARE vManaComponent INT; + DECLARE vAutoManaComponent INT; + DECLARE vManaBank INT; + DECLARE vManaGreugeType INT; + + SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; + SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; + SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; + SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; + SELECT COUNT(*) INTO vHasMana FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; @@ -31142,52 +31607,43 @@ BEGIN END IF; SELECT max(dated) INTO vFromDated - FROM vn.clientManaCache; + FROM clientManaCache; SELECT sum(mana) INTO vMana FROM ( SELECT mana - FROM vn.clientManaCache + FROM clientManaCache WHERE clientFk = vClient - AND dated = vFromDated - + AND dated = vFromDated UNION ALL - - SELECT s.quantity * Valor - FROM vn.ticket t - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.sale s on s.ticketFk = t.id - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = s.id - WHERE Id_Componente IN (37, 39) + SELECT s.quantity * value + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN sale s on s.ticketFk = t.id + JOIN saleComponent sc on sc.saleFk = s.id + WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) AND t.shipped > vFromDated AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE()) AND a.clientFk = vClient - UNION ALL - - SELECT - Entregado - FROM vn2008.Recibos r - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE r.Id_Banco = 66 - AND r.Fechacobro > vFromDated - AND r.Fechacobro <= CURDATE() - AND c.Id_Cliente = vClient - + SELECT - amountPaid + FROM receipt r + JOIN `client` c ON c.id = r.clientFk + WHERE r.bankFk = vManaBank + AND r.payed > vFromDated + AND r.payed <= CURDATE() + AND c.id = vClient UNION ALL - - SELECT g.Importe - FROM vn2008.Greuges g - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE g.Greuges_type_id = 3 -- Maná - AND g.Fecha > vFromDated - AND g.Fecha <= CURDATE() - AND c.Id_Cliente = vClient - + SELECT g.amount + FROM greuge g + JOIN `client` c ON c.id = g.clientFk + WHERE g.greugeTypeFk = vManaGreugeType + AND g.shipped > vFromDated + AND g.shipped <= CURDATE() + AND c.id = vClient ) sub; - RETURN IFNULL(vMana,0); - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31590,9 +32046,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -31606,26 +32062,50 @@ 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 commission INTO vCurrentCommission - FROM supplier s - WHERE s.id = vSupplierFk; - RETURN vCurrentCommission; - END IF; - - 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; + + 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; - RETURN IFNULL(vCommission, 0); + 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 + + 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; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33735,9 +34215,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -33748,21 +34228,22 @@ BEGIN DECLARE vLastIn DATETIME; DECLARE vDayStayMax INT; DECLARE vHasDirectionOut INT; + DECLARE vLastInsertedId INT; SELECT dayStayMax INTO vDayStayMax - FROM vn.workerTimeControlParams; + FROM workerTimeControlParams; - SELECT vn.timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; IF vDirection = 'out' THEN SELECT MAX(timed) INTO vLastIn - FROM vn.workerTimeControl + FROM workerTimeControl WHERE userFk = vUserFk AND direction = 'in' AND timed < vTimed; - UPDATE vn.workerTimeControl wtc + UPDATE workerTimeControl wtc SET wtc.direction = 'middle' WHERE userFk = vUserFk AND direction = 'out' @@ -33771,25 +34252,28 @@ BEGIN ELSE IF vDirection = 'in' THEN SELECT COUNT(*) INTO vHasDirectionOut - FROM vn.workerTimeControl wtc + FROM workerTimeControl wtc WHERE userFk = vUserFk AND direction = 'out' AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - UPDATE vn.workerTimeControl wtc + UPDATE workerTimeControl wtc SET wtc.direction = IF (vHasDirectionOut,'middle','out') WHERE userFk = vUserFk AND direction = 'in' AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - + END IF; END IF; INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - -RETURN LAST_INSERT_ID(); + SET vLastInsertedId = LAST_INSERT_ID(); + + CALL workerTimeControlSOWP(vUserFk, vTimed); + + RETURN vLastInsertedId; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34218,7 +34702,7 @@ BEGIN -- Establecemos los almacenes y las fechas que van a entrar al disponible - CALL vn.zoneGetShippedWarehouse(vDate, vAddress, vAgencyMode); + CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode); DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; CREATE TEMPORARY TABLE tmp.availableCalc( @@ -34371,23 +34855,28 @@ BEGIN DECLARE vWarehouseOut INT; DECLARE vIsMerchandise BOOL; DECLARE vIsFeedStock BOOL; - + DECLARE vLanded DATE; + DECLARE vBuyerFk INT; + DECLARE vItemName VARCHAR(50); + SELECT entryFk, itemFk, stickers, packing INTO vEntryFk, vItemFk, vStickers, vPacking FROM buy WHERE id = vSelf; - SELECT t.warehouseInFk, t.warehouseOutFk - INTO vWarehouse, vWarehouseOut + SELECT t.warehouseInFk, t.warehouseOutFk, t.landed + INTO vWarehouse, vWarehouseOut, vLanded FROM entry e JOIN travel t ON t.id = e.travelFk WHERE e.id = vEntryFk; - SELECT k.merchandise INTO vIsMerchandise + SELECT k.merchandise, it.workerFk, i.longName + INTO vIsMerchandise, vBuyerFk, vItemName FROM itemCategory k JOIN itemType it ON it.categoryFk = k.id JOIN item i ON i.typeFk = it.id WHERE i.id = vItemFk; + IF vIsMerchandise THEN REPLACE bi.rotacion SET Id_Article = vItemFk, @@ -34410,6 +34899,20 @@ BEGIN CALL vn.buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking); END IF; END IF; + + -- Aviso al comprador de modificacion de entrada en Barajas + IF (SELECT isBuyerToBeEmailed FROM warehouse WHERE id = vWarehouse) + AND vLanded = CURDATE() + AND vBuyerFk != account.myUserGetId() + THEN + + CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'), + CONCAT(account.myUserGetName(),'@verdnatura.es'), + CONCAT('E ',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName), + 'Este email se ha generado automáticamente'); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34860,7 +35363,7 @@ BEGIN ENGINE = MEMORY SELECT vItemFk itemFk; - CALL ticketCalculate(vLanded, vAddressFk, vAgencyModeFk); + CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE tmp.item; END ;; DELIMITER ; @@ -34886,7 +35389,7 @@ proc: BEGIN /** * Calcula los articulos disponibles y sus precios * - * @table tmp.item(itemFk) Listado de artículos a calcular + * @table tmp.item(itemFk) Listado de artículos a calcular * @param vLanded Fecha de recepcion de mercancia * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id de la agencia @@ -34906,7 +35409,7 @@ proc: BEGIN DECLARE vZoneFk INT; DECLARE vDone BOOL; DECLARE cTravelTree CURSOR FOR - SELECT id, warehouseFk, shipped FROM tmp.zoneGetShipped; + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -34915,7 +35418,7 @@ proc: BEGIN SELECT clientFk INTO vClient FROM address WHERE id = vAddressFk; - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot( @@ -34982,7 +35485,7 @@ proc: BEGIN LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible JOIN origin o ON o.id = i.originFk JOIN ( - SELECT MIN(price) price, itemFk, MIN(priceKg) priceKg + SELECT MIN(price) price, itemFk, priceKg FROM tmp.ticketComponentPrice GROUP BY itemFk ) bl ON bl.itemFk = b.itemFk @@ -34998,9 +35501,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -35020,6 +35523,7 @@ proc: BEGIN * packing, grouping, groupingMode, buyFk, typeFk) * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) */ + DECLARE vClientFk INT; DECLARE vGeneralInflationCoefficient INT DEFAULT 1; DECLARE vMinimumDensityWeight INT DEFAULT 167; @@ -35069,9 +35573,9 @@ proc: BEGIN LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk LEFT JOIN ( SELECT * FROM ( - SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, z.warehouseFk + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk FROM priceFixed pf - JOIN zone z ON z.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0 + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC ) tpf GROUP BY tpf.itemFk, tpf.warehouseFk @@ -35351,27 +35855,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean__`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE oneYearAgo DATE; - DECLARE twoYearsAgo DATE; - DECLARE fourYearsAgo DATE; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); - SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); - SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); - - DELETE FROM vn.message WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; - DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; - DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); - CALL shelving_clean; - +BEGIN + DECLARE vDateShort DATETIME; + DECLARE oneYearAgo DATE; + DECLARE twoYearsAgo DATE; + DECLARE fourYearsAgo DATE; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); + SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); + SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); + + DELETE FROM vn.message WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; + DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; + DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); + CALL shelving_clean; + CALL vn.ticketPackagingRecovery; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35938,15 +36442,14 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientPackagingOverstock`(vClientFk INT, vGraceDays INT ) BEGIN - -- Bernat: WORKING IN THIS FILE DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock; CREATE TEMPORARY TABLE tmp.clientPackagingOverstock ENGINE = MEMORY @@ -35957,10 +36460,8 @@ BEGIN sum(GotfromClient) - sum(SenttoClient), sum(InvoicedtoClient) - sum(InvoicedfromClient) ) as abonables - - FROM - ( - + FROM + ( SELECT t.*, IF(@month = month, 0, 1) monthEnd, @month := month @@ -35977,10 +36478,8 @@ BEGIN x.refFk as invoice, month(shipped) month, x.companyFk - FROM ( - SELECT t.id, t.shipped, IFNULL(pe.equivalentFk, s.itemFk) itemFk, @@ -35991,16 +36490,14 @@ BEGIN t.refFk, @month := 0 month, t.companyFk - FROM vn.sale s - JOIN vn.ticket t on t.id = s.ticketFk - JOIN vn2008.Cubos c ON c.item_id = s.itemFk - LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = s.itemFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk + JOIN packaging p ON p.itemFk = s.itemFk + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk WHERE t.clientFk = vClientFk AND t.shipped > '2017-11-30' - AND c.Retornable - + AND p.isPackageReturnable UNION ALL - SELECT NULL, '2017-11-30', IFNULL(pe.equivalentFk, tps.itemFk) itemFk, @@ -36012,13 +36509,11 @@ BEGIN NULL, NULL - FROM vn.ticketPackagingStartingStock tps - LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = tps.itemFk + FROM ticketPackagingStartingStock tps + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk WHERE tps.clientFk = vClientFk AND tps.isForgetable = FALSE - UNION ALL - SELECT t.id, t.shipped, IFNULL(pe.equivalentFk, p.itemFk) itemFk, @@ -36029,22 +36524,19 @@ BEGIN NULL AS refFk, NULL, t.companyFk - FROM vn.ticketPackaging tp - JOIN vn.ticket t on t.id = tp.ticketFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = p.itemFk + FROM ticketPackaging tp + JOIN ticket t on t.id = tp.ticketFk + JOIN packaging p ON p.id = tp.packagingFk + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk WHERE t.clientFk = vClientFk AND t.shipped > '2017-11-21' ) x - JOIN vn.item i ON x.itemFk = i.id + JOIN item i ON x.itemFk = i.id GROUP BY x.id, x.itemFk - ) t ORDER BY itemFk, shipped DESC ) t2 - GROUP BY itemFk - -; + GROUP BY itemFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36171,54 +36663,54 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker`() -BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vClientFk INT; - - DECLARE rs CURSOR FOR - SELECT c.clientFk - FROM tmp.clientGetDebt c - LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk - WHERE IFNULL(r.risk,0) = 0; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT cd.id as clientFk - FROM bs.clientDied cd - LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id - JOIN vn.client c ON c.id = cd.id - JOIN vn.province p ON p.id = c.provinceFk - JOIN vn.country co ON co.id = p.countryFk - WHERE cd.Aviso = 'TERCER AVISO' - AND cp.clientFk IS NULL - AND co.country NOT IN ('Portugal','Francia','España exento') - AND c.salesPersonFk IS NOT NULL; - - CALL vn.clientGetDebt(curdate()); - - DROP TEMPORARY TABLE IF EXISTS tmp.contador; - CREATE TEMPORARY TABLE tmp.contador (id INT) - ENGINE = MEMORY; - - OPEN rs; - FETCH rs INTO vClientFk; - - WHILE NOT done DO - INSERT INTO tmp.contador SET id = vClientFk; - CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + + DECLARE rs CURSOR FOR + SELECT c.clientFk + FROM tmp.clientGetDebt c + LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk + WHERE IFNULL(r.risk,0) = 0; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT cd.id as clientFk + FROM bs.clientDied cd + LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id + JOIN vn.client c ON c.id = cd.id + JOIN vn.province p ON p.id = c.provinceFk + JOIN vn.country co ON co.id = p.countryFk + WHERE cd.Aviso = 'TERCER AVISO' + AND cp.clientFk IS NULL + AND co.country NOT IN ('Portugal','Francia','España exento') + AND c.salesPersonFk IS NOT NULL; + + CALL vn.clientGetDebt(curdate()); + + DROP TEMPORARY TABLE IF EXISTS tmp.contador; + CREATE TEMPORARY TABLE tmp.contador (id INT) + ENGINE = MEMORY; + + OPEN rs; + FETCH rs INTO vClientFk; + + WHILE NOT done DO + INSERT INTO tmp.contador SET id = vClientFk; + CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; INSERT INTO vn.clientLog (originFk, userFk, `action`, description) VALUES (vClientFk, account.userGetId(), 'update', CONCAT('Se ha desasignado el cliente por que no ha comprado en 3 meses')); - + REPLACE bs.clientNewBorn(clientFk, shipped) - VALUES(vClientFk, CURDATE()); - FETCH rs INTO vClientFk; - END WHILE; - - CLOSE rs; + VALUES(vClientFk, CURDATE()); + FETCH rs INTO vClientFk; + END WHILE; + + CLOSE rs; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36229,183 +36721,137 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) -BEGIN - -- BERNAT: WORKING IN THIS FILE - DECLARE vTravelNew INT; - DECLARE vEntryNew INT; - DECLARE vDone BIT DEFAULT 0; - DECLARE vAuxEntryFk INT; - DECLARE vRsEntry CURSOR FOR - SELECT e.id - FROM vn.entry e - JOIN vn.travel t - ON t.id = e.travelFk - WHERE e.travelFk = vTravelFk; - - DECLARE vRsBuy CURSOR FOR - SELECT b.* - FROM vn.buy b - JOIN vn.entry e - ON b.entryFk = e.id - WHERE e.travelFk = vTravelNew and b.entryFk=entryNew - ORDER BY e.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - INSERT INTO vn.travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) - SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg - FROM vn.travel - WHERE id = vTravelFk; - - SET vTravelNew = LAST_INSERT_ID(); - SET vDone = 0; - OPEN vRsEntry ; - FETCH vRsEntry INTO vAuxEntryFk; - - WHILE NOT vDone DO - INSERT INTO vn.entry (supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - travelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk) - SELECT supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - vTravelNew, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk - FROM vn.entry - WHERE id = vAuxEntryFk; - - SET vEntryNew = LAST_INSERT_ID(); - - /* INSERT INTO vn.buy ( - entryFk, - itemFk, - amount, - buyingValue, - quantity, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isCkecked) - SELECT - vEntryNew, - itemFk, - amount, - buyingValue, - quantity, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isCkecked - FROM buy - WHERE entryFk = vAuxEntryFk;*/ - - INSERT INTO vn2008.Compres (Id_Entrada, - Id_Article, - Cantidad, - Costefijo, - Id_Cubo, - Etiquetas, - Portefijo, - Embalajefijo, - Comisionfija, - Packing, - `grouping`, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP, - Productor, - Vida, - punteo) - SELECT vEntryNew, - Id_Article, - Cantidad, - Costefijo, - Id_Cubo, - Etiquetas, - Portefijo, - Embalajefijo, - Comisionfija, - Packing, - `grouping`, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP, - Productor, - Vida, - punteo - FROM vn2008.Compres - WHERE Id_Entrada = vAuxEntryFk; - - - FETCH vRsEntry INTO vAuxEntryFk; - END WHILE; - CLOSE vRsEntry; - COMMIT; +BEGIN + + DECLARE vTravelNew INT; + DECLARE vEntryNew INT; + DECLARE vDone BIT DEFAULT 0; + DECLARE vAuxEntryFk INT; + DECLARE vRsEntry CURSOR FOR + SELECT e.id + FROM entry e + JOIN travel t + ON t.id = e.travelFk + WHERE e.travelFk = vTravelFk; + + DECLARE vRsBuy CURSOR FOR + SELECT b.* + FROM buy b + JOIN entry e + ON b.entryFk = e.id + WHERE e.travelFk = vTravelNew and b.entryFk=entryNew + ORDER BY e.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + INSERT INTO travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) + SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg + FROM travel + WHERE id = vTravelFk; + + SET vTravelNew = LAST_INSERT_ID(); + SET vDone = 0; + OPEN vRsEntry ; + FETCH vRsEntry INTO vAuxEntryFk; + + WHILE NOT vDone DO + INSERT INTO entry (supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + travelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk) + SELECT supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + vTravelNew, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk + FROM entry + WHERE id = vAuxEntryFk; + + SET vEntryNew = LAST_INSERT_ID(); + + + INSERT INTO buy (entryFk, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked) + SELECT vEntryNew, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked + FROM buy + WHERE entryFk = vAuxEntryFk; + + + FETCH vRsEntry INTO vAuxEntryFk; + END WHILE; + CLOSE vRsEntry; + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36435,6 +36881,175 @@ BEGIN FROM vn.ticketCollection tc WHERE tc.collectionFk = vCollectionFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_new` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_new`(vSectorFk INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vTicketLiters INT; + DECLARE vTicketLines INT; + DECLARE vTicketFk INT; + DECLARE vIsTicketCollected BOOLEAN; + DECLARE vMaxTickets INT; + DECLARE vStateFk INT; + DECLARE vVolumetryLiters INT; + DECLARE vVolumetryLines INT; + DECLARE vVolumetryFk INT; + DECLARE vVolumetryLevel INT; + DECLARE vVolumetryLitersMax INT; + DECLARE vVolumetryLinesMax INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + + DECLARE cVolumetry CURSOR FOR + SELECT level, liters, `lines` + FROM vn.collectionVolumetry + ORDER BY `level`; + + DECLARE cTicket CURSOR FOR + SELECT pb.Id_Ticket ticketFk, + pb.lines, + pb.m3 * 1000 liters + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE pb.problems = 0 + AND tc.ticketFk IS NULL + AND s.isPreparable + ORDER BY pb.Hora, pb.Minuto, m3 DESC, pb.lines DESC + LIMIT vMaxTickets; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SELECT isPreviousPrepared, warehouseFk + INTO vIsPreviousPrepared, vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + IF vIsPreviousPrepared THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + SELECT COUNT(*), sum(liters), sum(`lines`) + INTO vMaxTickets, vVolumetryLitersMax, vVolumetryLinesMax + FROM vn.collectionVolumetry; + + CALL vn2008.production_control_source(vWarehouseFk, 0); + + -- Empieza el bucle + OPEN cVolumetry; + OPEN cTicket; + + DROP TEMPORARY TABLE IF EXISTS tmp.kk; + CREATE TEMPORARY TABLE tmp.kk + SELECT pb.Id_Ticket ticketFk,pb.Hora, pb.Minuto, + pb.lines, + pb.m3 * 1000 liters + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE pb.problems = 0 + AND tc.ticketFk IS NULL + AND s.isPreparable + ORDER BY pb.Hora, pb.Minuto, m3 DESC, pb.lines DESC + LIMIT vMaxTickets; + + FETCH cTicket INTO vTicketFk, vTicketLines, vTicketLiters; + FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines; + + IF NOT vDone THEN + + INSERT INTO vn.collection + SET workerFk = account.myUserGetId(); + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + END IF; + + bucle:WHILE NOT vDone DO + + IF (vVolumetryLitersMax < vTicketLiters OR vVolumetryLinesMax < vTicketLines) AND vVolumetryLevel > 1 THEN + LEAVE bucle; + END IF; + + SELECT COUNT(*) INTO vIsTicketCollected + FROM vn.ticketCollection + WHERE ticketFk = vTicketFk + AND collectionFk = vCollectionFk; + + IF vIsTicketCollected THEN + + UPDATE vn.ticketCollection + SET level = CONCAT(level, vVolumetryLevel) + WHERE ticketFk = vTicketFk + AND collectionFk = vCollectionFk; + + ELSE + + INSERT INTO vn.ticketCollection + SET collectionFk = vCollectionFk, + ticketFk = vTicketFk, + level = vVolumetryLevel; + + INSERT INTO vncontrol.inter + SET state_id = vStateFk, + Id_Ticket = vTicketFk, + Id_Trabajador = account.myUserGetId(); + + END IF; + + SET vVolumetryLitersMax = GREATEST(0,vVolumetryLitersMax - vVolumetryLiters); + SET vVolumetryLinesMax = GREATEST(0,vVolumetryLinesMax - vVolumetryLines); + SET vTicketLiters = GREATEST(0,vTicketLiters - vVolumetryLiters); + SET vTicketLines = GREATEST(0,vTicketLines - vVolumetryLines); + + IF vVolumetryLitersMax = 0 OR vVolumetryLinesMax = 0 THEN + LEAVE bucle; + END IF; + + IF vTicketLiters > 0 OR vTicketLines > 0 THEN + + FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines; + + ELSE + + FETCH cTicket INTO vTicketFk, vTicketLines, vTicketLiters; + FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines; + + END IF; + + END WHILE; + + SELECT vCollectionFk; + + CLOSE cVolumetry; + CLOSE cTicket; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36852,9 +37467,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -36896,9 +37511,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -36974,6 +37589,139 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `department_doCalc` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`() +proc: BEGIN +/** + * Recalculates the department tree. + */ + DECLARE vIsChanged BOOL; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.department_doCalc'); + RESIGNAL; + END; + + IF !GET_LOCK('vn.department_doCalc', 0) THEN + LEAVE proc; + END IF; + + SELECT isChanged INTO vIsChanged + FROM department_recalc; + + IF vIsChanged THEN + UPDATE department_recalc SET isChanged = FALSE; + CALL vn.department_calcTree; + END IF; + + DO RELEASE_LOCK('vn.department_doCalc'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `department_getLeaves` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `department_getLeaves`( + vParentFk INT, + vSearch VARCHAR(255) +) +BEGIN + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id FROM department LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id FROM department + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + ENGINE = MEMORY + SELECT id FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + ENGINE = MEMORY + SELECT id FROM department LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM department g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF ROW_COUNT() = 0 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 !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id FROM department + WHERE parentFk <=> vParentFk; + END IF; + + SELECT d.id, + d.`name`, + d.parentFk, + d.sons + FROM department d + JOIN tNodes n ON n.id = d.id + ORDER BY depth, `name`; + + DROP TEMPORARY TABLE tNodes; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `duaEntryValueUpdate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -37027,8 +37775,6 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT) BEGIN - - -- BERNAT: WORKING IN THIS FILE DECLARE done BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; DECLARE vASIEN BIGINT DEFAULT 0; @@ -37071,13 +37817,13 @@ BEGIN IF vCounter > 0 OR vASIEN > 0 THEN - UPDATE vn2008.XDiario x - JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN + UPDATE XDiario x + JOIN config c ON c.ASIEN = x.ASIEN SET x.ASIEN = vASIEN; ELSE - SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig; + SELECT ASIEN INTO vASIEN FROM config; END IF; @@ -37580,216 +38326,216 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryConverter`(IN `vEntry` INT) -BEGIN - - DECLARE vWarehouseIn INT; - DECLARE vWarehouseOut INT; - DECLARE vTravel INT; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE vId_Entrada INT; - DECLARE vId_Article INT; - DECLARE vEtiquetas INT; - DECLARE vId_Cubo VARCHAR(10); - DECLARE vPacking INT; - DECLARE vGrouping INT; - DECLARE vCantidad INT; - DECLARE vCostefijo DECIMAL(10,3); - DECLARE vPortefijo DECIMAL(10,3); - DECLARE vEmbalajefijo DECIMAL(10); - DECLARE vComisionfija DECIMAL(10,3); - DECLARE vCaja INT; - DECLARE vNicho VARCHAR(5); - DECLARE vTarifa1 DECIMAL(10,2); - DECLARE vTarifa2 DECIMAL(10,2); - DECLARE vTarifa3 DECIMAL(10,2); - DECLARE vPVP DECIMAL(10,2); - DECLARE vCompra INT; - - DECLARE rs CURSOR FOR - SELECT - b.Id_Entrada, - b.Id_Article, - b.Etiquetas, - b.Id_Cubo, - b.Packing, - b.`grouping`, - b.Cantidad, - b.Costefijo, - b.Portefijo, - b.Embalajefijo, - b.Comisionfija, - b.caja, - b.Nicho, - b.Tarifa1, - b.Tarifa2, - b.Tarifa3, - b.PVP - FROM vn2008.Compres b - JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article - WHERE Id_Entrada = vEntry; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT warehouseInFk, warehouseOutFk, tr.id - INTO vWarehouseIn, vWarehouseOut, vTravel - FROM travel tr - JOIN entry e ON e.travelFk = tr.id - WHERE e.id = vEntry; - - UPDATE travel - SET warehouseInFk = vWarehouseOut, - warehouseOutFk = vWarehouseIn - WHERE id = vTravel; - - UPDATE vn2008.Compres c - LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article - SET Etiquetas = 0, Cantidad = 0 - WHERE c.Id_Entrada = vEntry - AND ic.espItemFk IS NULL; - - OPEN rs; - - DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - WHILE NOT done DO - - -- Primero la linea original con las cantidades invertidas - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - VALUES - ( - vId_Entrada, - vId_Article, - - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP); - - -- Ahora la linea nueva, con el item genérico - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - SELECT - vId_Entrada, - genItemFk as Id_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP - FROM itemConversor - WHERE espItemFk = vId_Article; - - SELECT LAST_INSERT_ID() - INTO vCompra; - - REPLACE vn2008.Compres_mark(Id_Compra,`comment`) - SELECT vCompra, vId_Article; - - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - END WHILE; - - - CLOSE rs; - - - +BEGIN + + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vTravel INT; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE vId_Entrada INT; + DECLARE vId_Article INT; + DECLARE vEtiquetas INT; + DECLARE vId_Cubo VARCHAR(10); + DECLARE vPacking INT; + DECLARE vGrouping INT; + DECLARE vCantidad INT; + DECLARE vCostefijo DECIMAL(10,3); + DECLARE vPortefijo DECIMAL(10,3); + DECLARE vEmbalajefijo DECIMAL(10); + DECLARE vComisionfija DECIMAL(10,3); + DECLARE vCaja INT; + DECLARE vNicho VARCHAR(5); + DECLARE vTarifa1 DECIMAL(10,2); + DECLARE vTarifa2 DECIMAL(10,2); + DECLARE vTarifa3 DECIMAL(10,2); + DECLARE vPVP DECIMAL(10,2); + DECLARE vCompra INT; + + DECLARE rs CURSOR FOR + SELECT + b.Id_Entrada, + b.Id_Article, + b.Etiquetas, + b.Id_Cubo, + b.Packing, + b.`grouping`, + b.Cantidad, + b.Costefijo, + b.Portefijo, + b.Embalajefijo, + b.Comisionfija, + b.caja, + b.Nicho, + b.Tarifa1, + b.Tarifa2, + b.Tarifa3, + b.PVP + FROM vn2008.Compres b + JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article + WHERE Id_Entrada = vEntry; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT warehouseInFk, warehouseOutFk, tr.id + INTO vWarehouseIn, vWarehouseOut, vTravel + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + WHERE e.id = vEntry; + + UPDATE travel + SET warehouseInFk = vWarehouseOut, + warehouseOutFk = vWarehouseIn + WHERE id = vTravel; + + UPDATE vn2008.Compres c + LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article + SET Etiquetas = 0, Cantidad = 0 + WHERE c.Id_Entrada = vEntry + AND ic.espItemFk IS NULL; + + OPEN rs; + + DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + WHILE NOT done DO + + -- Primero la linea original con las cantidades invertidas + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + VALUES + ( + vId_Entrada, + vId_Article, + - vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + - vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP); + + -- Ahora la linea nueva, con el item genérico + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + SELECT + vId_Entrada, + genItemFk as Id_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP + FROM itemConversor + WHERE espItemFk = vId_Article; + + SELECT LAST_INSERT_ID() + INTO vCompra; + + REPLACE vn2008.Compres_mark(Id_Compra,`comment`) + SELECT vCompra, vId_Article; + + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + END WHILE; + + + CLOSE rs; + + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37851,62 +38597,62 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryPrepare`(IN `idE` BIGINT) -BEGIN - SELECT - b.quantity / b.packing AS Paquetes, - b.packing AS `Grouping`, - barcode, - 'ASEGURADO' AS asegurado, - ic.name, - ic.order, - s.name AS Consignatario, - e.supplierFk AS Id_Cliente, - e.isOrdered, - e.isConfirmed, - 10 AS Calidad, - LPAD(IFNULL(cpd.id, ip.code), - 5, - '0') AS path, - b.entryFk AS Id_Ticket, - t.landed AS Fecha, - b.itemFk, - b.quantity, - i.name AS Concepte, - i.size, - i.inkFk, - i.category, - o.code AS Origen, - 0 AS Bultos, - wIn.`name` AS Tipo, - 0 AS OK, - 0 AS Reservado, - i.stems, - b.id AS Id_Movimiento, - ip.code, - 'PEDIDO ASEGURADO' AS MSG, - 0 AS Seguro, - i.image, - pr.name AS producer - FROM vn.buy b - JOIN vn.entry e ON b.entryFk = e.id - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk - JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk - JOIN vn.item i ON i.id = b.itemFk - JOIN vn.itemType it ON it.id =i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.packaging pkg ON pkg.id = b.packageFk - LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk - LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk - LEFT JOIN vn.origin o ON o.id = i.originFk - LEFT JOIN vn.supplier s ON s.id = e.supplierFk - LEFT JOIN vn.producer pr on pr.id = i.producerFk - LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway - WHERE - NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid - AND e.id = 158772 - AND i.typeFk IS NOT NULL - AND ic.merchandise IS NOT FALSE; +BEGIN + SELECT + b.quantity / b.packing AS Paquetes, + b.packing AS `Grouping`, + barcode, + 'ASEGURADO' AS asegurado, + ic.name, + ic.order, + s.name AS Consignatario, + e.supplierFk AS Id_Cliente, + e.isOrdered, + e.isConfirmed, + 10 AS Calidad, + LPAD(IFNULL(cpd.id, ip.code), + 5, + '0') AS path, + b.entryFk AS Id_Ticket, + t.landed AS Fecha, + b.itemFk, + b.quantity, + i.name AS Concepte, + i.size, + i.inkFk, + i.category, + o.code AS Origen, + 0 AS Bultos, + wIn.`name` AS Tipo, + 0 AS OK, + 0 AS Reservado, + i.stems, + b.id AS Id_Movimiento, + ip.code, + 'PEDIDO ASEGURADO' AS MSG, + 0 AS Seguro, + i.image, + pr.name AS producer + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id =i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.packaging pkg ON pkg.id = b.packageFk + LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk + LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.supplier s ON s.id = e.supplierFk + LEFT JOIN vn.producer pr on pr.id = i.producerFk + LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway + WHERE + NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid + AND e.id = 158772 + AND i.typeFk IS NOT NULL + AND ic.merchandise IS NOT FALSE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38254,32 +39000,8 @@ CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`( vWarehouse TINYINT, vRefresh BOOL) BEGIN - - /*deprecated usar vn.itemGetVisibleAvailable - jgf 2019/09/10 */ - DECLARE vVisibleCalc INT; - DECLARE vAvailableCalc INT; - - -- FIXME: Android app is always passing %TRUE for #vRefresh, this leads to DB performance issues - CALL cache.visible_refresh(vVisibleCalc, FALSE /*vRefresh*/, vWarehouse); - CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, vWarehouse, vDate); - - SELECT a.Id_Article, a.Article, a.Medida, a.Tallos, - a.caja, O.Abreviatura AS origen, a.Color, tipo_id, - an.Nicho, a.Categoria, p.`name` AS producer, - v.visible, av.available, an.reserve - FROM vn2008.Articles a - LEFT JOIN vn2008.Articles_nicho an - ON a.Id_Article = an.Id_Article AND an.warehouse_id = vWarehouse - LEFT JOIN cache.visible v - ON v.item_id = a.Id_Article AND v.calc_id = vVisibleCalc - LEFT JOIN cache.available av - ON av.item_id = a.Id_Article AND av.calc_id = vAvailableCalc - LEFT JOIN vn2008.Origen O - ON O.id = a.id_origen - LEFT JOIN vn2008.producer p - ON p.producer_id = a.producer_id - WHERE (vItem IS NULL OR a.Id_Article = vItem); + -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 + CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39299,11 +40021,11 @@ BEGIN FECREGCON, empresa_id ) - SELECT vBookNumber ASIEN, + SELECT vBookNumber ASIEN, n.bookEntried FECHA, tc.code SUBCTA, s.supplierAccount CONTRA, - SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE, + ROUND(tc.rate/100 * SUM(it.taxableBase) + 0.0001, 2) EURODEBE, SUM(it.taxableBase) BASEEURO, GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, vSerialNumber FACTURA, @@ -41508,65 +42230,8 @@ CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`( vWarehouse TINYINT, vRefresh BOOL) BEGIN - - DECLARE vVisibleCalc INT; - DECLARE vAvailableCalc INT; - DECLARE vVisibleAltillo INT; - - CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, vWarehouse, vDate); - CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); - - - - SELECT visible INTO vVisibleAltillo - FROM vn.itemShelvingStock - WHERE itemFk = vItem - AND warehouseFk = vWarehouse; - - IF vRefresh THEN - - DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; - CREATE TEMPORARY TABLE vn2008.tmp_item - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT vItem item_id, 0 stock, 0 visible; - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - vi.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN vn2008.tmp_item v - ON v.item_id = i.id - LEFT JOIN cache.available av - ON av.calc_id = vAvailableCalc AND av.item_id = i.id - LEFT JOIN cache.visible vi - ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id - LEFT JOIN cache.stock st - ON st.warehouse_id = vWarehouse AND st.item_id = i.id - WHERE (vItem IS NULL OR i.id = vItem); - - ELSE - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - v.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN cache.visible v - ON v.item_id = i.id AND v.calc_id = vVisibleCalc - LEFT JOIN cache.available av - ON av.item_id = i.id AND av.calc_id = vAvailableCalc - WHERE (vItem IS NULL OR i.id = vItem); - - END IF; - + -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 + CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41584,38 +42249,38 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemLastEntries`(IN `vItem` INT, IN `vDays` DATE) -BEGIN - SELECT - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.`grouping`, - b.groupingMode, - i.stems, - b.quantity, - b.buyingValue, - b.packageFk , - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - RIGHT JOIN (entry e - LEFT JOIN supplier s ON s.id = e.supplierFk - RIGHT JOIN buy b ON b.entryFk = e.id - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk - LEFT JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN warehouse w ON w.id = tr.warehouseInFk - LEFT JOIN origin o ON o.id = i.originFk - ) ON it.id = i.typeFk - LEFT JOIN edi.ekt ek ON b.ektFk = ek.id - WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND CURDATE() - ORDER BY tr.landed DESC , b.id DESC; +BEGIN + SELECT + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.`grouping`, + b.groupingMode, + i.stems, + b.quantity, + b.buyingValue, + b.packageFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND CURDATE() + ORDER BY tr.landed DESC , b.id DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43485,6 +44150,84 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_getVisibleAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisibleAvailable`( + vItem INT, + vDate DATE, + vWarehouse TINYINT, + vRefresh BOOL) +BEGIN + DECLARE vVisibleCalc INT; + DECLARE vAvailableCalc INT; + DECLARE vVisibleAltillo INT; + + CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate); + CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); + + SELECT visible INTO vVisibleAltillo + FROM vn.itemShelvingStock + WHERE itemFk = vItem + AND warehouseFk = vWarehouse; + + IF vRefresh THEN + + DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; + CREATE TEMPORARY TABLE vn2008.tmp_item + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT vItem item_id, 0 stock, 0 visible; + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + vi.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN vn2008.tmp_item v + ON v.item_id = i.id + LEFT JOIN cache.available av + ON av.calc_id = vAvailableCalc AND av.item_id = i.id + LEFT JOIN cache.visible vi + ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id + LEFT JOIN cache.stock st + ON st.warehouse_id = vWarehouse AND st.item_id = i.id + WHERE (vItem IS NULL OR i.id = vItem); + + ELSE + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + v.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN cache.visible v + ON v.item_id = i.id AND v.calc_id = vVisibleCalc + LEFT JOIN cache.available av + ON av.item_id = i.id AND av.calc_id = vAvailableCalc + WHERE (vItem IS NULL OR i.id = vItem); + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `ledger_next` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -43612,6 +44355,48 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `mail_insert` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mail_insert`( + vSender VARCHAR(50), + vReplyTo VARCHAR(50), + vSubject VARCHAR(50), + vBody VARCHAR(255)) +BEGIN + + DECLARE vIsRepeated BOOLEAN; + + SELECT COUNT(*) INTO vIsRepeated + FROM vn.mail + WHERE creationDate >= CURDATE() + AND sender = vSender + AND `replyTo` = vReplyTo + AND `subject` = vSubject; + + IF NOT vIsRepeated THEN + + INSERT INTO vn.mail SET + `sender` = vSender, + `replyTo` = vReplyTo, + `subject` = vSubject, + `body` = vBody; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `makeNewItem` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -44764,6 +45549,56 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `rangeDateInfo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `rangeDateInfo`(vStarted DATE, vEnded DATE) +BEGIN +/** + * Crea una tabla temporal con las fechas + * desde una fecha inicial a una final + * @param vStarted fecha inicial + * @param vEnded fecha final + */ + DECLARE vDated DATE DEFAULT vStarted; + + DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; + CREATE TEMPORARY TABLE tmp.rangeDate( + `dated` DATE, + `period` INT, + `month` INT, + `year` INT, + `day` INT, + `week` INT, + `yearMonth` INT + ) + ENGINE = MEMORY; + + WHILE vDated <= vEnded DO + INSERT INTO tmp.rangeDate + SET `dated` = vDated, + `period` = YEAR(vDated) * 100 + WEEK(vDated, 1), + `month` = MONTH(vDated), + `year` = YEAR(vDated), + `day` = DAY(vDated), + `week` = WEEK(vDated, 1), + `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); + + SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); + END WHILE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `refund` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -44808,8 +45643,7 @@ BEGIN WHERE id = vOriginTicket; SELECT id INTO vZoneFk - FROM zone WHERE agencyModeFk = vRefundAgencyMode - ORDER BY (warehouseFk = vWarehouse) DESC + FROM zone WHERE agencyModeFk = vRefundAgencyMode LIMIT 1; INSERT INTO vn2008.Tickets ( @@ -45353,77 +46187,77 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT) -BEGIN - - SET @rest:= CAST(0 AS DECIMAL(10,0)); - SET @saleFk := CAST(0 AS DECIMAL(10,0)); - SET @reserved := CAST(0 AS DECIMAL(10,0)); - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN sale s ON s.id = sis.saleFk - SET ish.visible = sis.quantity + ish.visible, - ish.available = sis.quantity + ish.visible - WHERE s.ticketFk = vTicketFk; - - DELETE sis.* - FROM saleItemShelving sis - JOIN sale s ON s.id = sis.saleFk - WHERE s.ticketFk = vTicketFk; - - INSERT INTO saleItemShelving( saleFk, - itemShelvingFk, - quantity, - ubication) - SELECT saleFk, - itemShelvingFk, - CAST(Reserved as DECIMAL(10,0)) as Reserved, - ubication - FROM - (SELECT saleFk, - itemShelvingFk, - ubication, - @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, - @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, - @rest := @rest - @reserved, - @saleFk := saleFk - FROM - ( SELECT s.id as saleFk, - ish.created, - ish.id as itemShelvingFk, - ish.available, - s.quantity, - ish.packing, - CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk - JOIN vn.parking p ON p.sectorFk = sc.id - JOIN vn.shelving sh ON sh.parkingFk = p.id - JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk - WHERE t.id = vTicketFk - AND sc.id = vSectorFk - AND s.quantity MOD ish.packing = 0 - AND s.quantity >= ish.packing - ORDER BY s.id, - sh.priority DESC, - ish.packing DESC, - ish.created - ) sub - ) sub2 - WHERE Reserved > 0; - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN vn.sale s ON s.id = sis.saleFk - SET ish.available = ish.visible - sis.quantity, - ish.visible = ish.visible - sis.quantity - WHERE s.ticketFk = vTicketFk - AND s.isPicked = FALSE; - - CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); - - +BEGIN + + SET @rest:= CAST(0 AS DECIMAL(10,0)); + SET @saleFk := CAST(0 AS DECIMAL(10,0)); + SET @reserved := CAST(0 AS DECIMAL(10,0)); + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN sale s ON s.id = sis.saleFk + SET ish.visible = sis.quantity + ish.visible, + ish.available = sis.quantity + ish.visible + WHERE s.ticketFk = vTicketFk; + + DELETE sis.* + FROM saleItemShelving sis + JOIN sale s ON s.id = sis.saleFk + WHERE s.ticketFk = vTicketFk; + + INSERT INTO saleItemShelving( saleFk, + itemShelvingFk, + quantity, + ubication) + SELECT saleFk, + itemShelvingFk, + CAST(Reserved as DECIMAL(10,0)) as Reserved, + ubication + FROM + (SELECT saleFk, + itemShelvingFk, + ubication, + @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, + @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, + @rest := @rest - @reserved, + @saleFk := saleFk + FROM + ( SELECT s.id as saleFk, + ish.created, + ish.id as itemShelvingFk, + ish.available, + s.quantity, + ish.packing, + CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk + JOIN vn.parking p ON p.sectorFk = sc.id + JOIN vn.shelving sh ON sh.parkingFk = p.id + JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk + WHERE t.id = vTicketFk + AND sc.id = vSectorFk + AND s.quantity MOD ish.packing = 0 + AND s.quantity >= ish.packing + ORDER BY s.id, + sh.priority DESC, + ish.packing DESC, + ish.created + ) sub + ) sub2 + WHERE Reserved > 0; + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN vn.sale s ON s.id = sis.saleFk + SET ish.available = ish.visible - sis.quantity, + ish.visible = ish.visible - sis.quantity + WHERE s.ticketFk = vTicketFk + AND s.isPicked = FALSE; + + CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45819,7 +46653,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `sale_calculateComponent`(vSale INT, vOption INT) proc: BEGIN - +/** + * Actualiza los componentes + * + * @param vSale Delivery date + * @param vOption indica en que componente pone el descuadre, NULL en casos habituales + * @return tmp.ticketLot(warehouseFk, available, itemFk, buyFk) + * @return tmp.sale(saleFk, warehouseFk) + */ DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; @@ -45915,33 +46756,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`() -BEGIN - CALL nestTree( - 'vn2008', - 'scan', - 'vn2008', - 'scanTree' - ); - - UPDATE vn2008.scanTree st - JOIN ( - SELECT sl.scan_id, - MAX(sl.odbc_date) lastScanned, - COUNT(DISTINCT t.routeFk) routeCount, - MIN(t.routeFk) mod 1000 as minRoute, - MAX(t.routeFk) mod 1000 as maxRoute, - COUNT(sl.scan_line_id) as scanned - FROM vn2008.scan_line sl - JOIN expedition e ON e.id = sl.`code` - JOIN ticket t ON t.id = e.ticketFk - WHERE t.routeFk - GROUP BY sl.scan_id - ) rs ON rs.scan_id = st.id - SET st.lastScanned = rs.lastScanned, - st.routeCount = rs.routeCount, - st.minRoute = rs.minRoute, - st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), - st.scanned = rs.scanned; +BEGIN + CALL nestTree( + 'vn2008', + 'scan', + 'vn2008', + 'scanTree' + ); + + UPDATE vn2008.scanTree st + JOIN ( + SELECT sl.scan_id, + MAX(sl.odbc_date) lastScanned, + COUNT(DISTINCT t.routeFk) routeCount, + MIN(t.routeFk) mod 1000 as minRoute, + MAX(t.routeFk) mod 1000 as maxRoute, + COUNT(sl.scan_line_id) as scanned + FROM vn2008.scan_line sl + JOIN expedition e ON e.id = sl.`code` + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk + GROUP BY sl.scan_id + ) rs ON rs.scan_id = st.id + SET st.lastScanned = rs.lastScanned, + st.routeCount = rs.routeCount, + st.minRoute = rs.minRoute, + st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), + st.scanned = rs.scanned; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46731,19 +47572,18 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stowawayUnBoarding` */; +/*!50003 DROP PROCEDURE IF EXISTS `stowaway_unboarding` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stowawayUnBoarding`(vShipFk INT, vStowawayFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `stowaway_unboarding`(vShipFk INT, vStowawayFk INT) BEGIN - DECLARE vWorker VARCHAR(255); DELETE FROM stowaway @@ -46754,11 +47594,13 @@ BEGIN WHERE code = 'BOARDING' AND ticketFk = vShipFk; DELETE FROM sale - WHERE ticketFk = vShipFk AND itemFk = 98 AND concept = CONCAT('POLIZÓN! ',vStowawayFk); + WHERE ticketFk = vShipFk + AND itemFk = 98 + AND concept = CONCAT('POLIZÓN! ',vStowawayFk); SELECT u.`name` INTO vWorker - FROM account.user u JOIN vn.worker w ON w.userFk = u.id - WHERE w.id = vn2008.Averiguar_ComercialCliente_IdTicket_Id(vStowawayFk); + FROM account.user u JOIN worker w ON w.userFk = u.id + WHERE w.id = client_getSalesPersonByTicket(vStowawayFk); SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a; END ;; @@ -47094,32 +47936,42 @@ BEGIN DECLARE vAddress INT; DECLARE vLanded DATE; DECLARE vAgency INT; + DECLARE vZoneFk INT; REPLACE INTO orderTicket(orderFk,ticketFk) SELECT orderFk, vTicketNew FROM orderTicket WHERE ticketFk = vTicketOld; - - SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk - INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency + + SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk + INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk FROM vn.agencyMode a JOIN vn.ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicketNew; + + IF vLanded IS NULL THEN + CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); + UPDATE ticket t + JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk + SET t.landed = zgl.landed, + t.zone = zgl.zoneFk + WHERE t.id = vTicketNew; + + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + END IF; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CALL zoneGetShippedWarehouse(vLanded, vAddress, vAgencyMode); - DELETE FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouse; - - CALL buyUltimate(vWarehouse, vShipped); -- rellena la tabla tmp.buyUltimate con la ultima compra + -- rellena la tabla tmp.buyUltimate con la ultima compra + CALL buyUltimate(vWarehouse, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; + SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; - CALL ticketComponentCalculate(vAddress,vAgencyMode); + CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode); -- Bionizamos lineas con Preu = 0 DROP TEMPORARY TABLE IF EXISTS tmp.sale; @@ -47141,14 +47993,6 @@ BEGIN AND s.price > 0; CALL ticketComponentUpdateSale(6); - - IF vLanded IS NULL THEN - CALL zoneGetLanded(vShipped, vAddress, vAgency,vWarehouse); - UPDATE ticket t - JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk - SET t.landed = zgl.landed - WHERE t.id = vTicketNew; - END IF; -- Log CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); @@ -47307,18 +48151,15 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vTicket BIGINT; DECLARE vItem BIGINT; - DECLARE vLanded DATE; - DECLARE vZoneFk INT; - DECLARE vHasZone BOOLEAN DEFAULT FALSE; - + DECLARE vZoneFk INT; SELECT ticketFk, itemFk INTO vTicket, vItem FROM sale WHERE id = vSale; - SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.landed, t.zoneFk - INTO vWarehouseFk, vShipped, vAddressFk, vLanded, vZoneFk + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk FROM agencyMode a JOIN ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicket; @@ -47360,9 +48201,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -47374,18 +48215,15 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vTicket BIGINT; DECLARE vItem BIGINT; - DECLARE vLanded DATE; DECLARE vZoneFk INT; - DECLARE vHasZone BOOLEAN DEFAULT FALSE; - - + SELECT ticketFk, itemFk INTO vTicket, vItem FROM sale WHERE id = vSale; - SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.landed, t.zoneFk - INTO vWarehouseFk, vShipped, vAddressFk, vLanded, vZoneFk + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk FROM agencyMode a JOIN ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicket; @@ -47538,7 +48376,7 @@ BEGIN SELECT ticketFk FROM tmp.ticketClosure; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; END; @@ -47604,9 +48442,6 @@ BEGIN CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL); -- Facturar si está contabilizado IF vIsTaxDataChecked THEN - - -- JGF cau 12220 - -- IF (SELECT clientTaxArea(vClientFk, vCompanyFk)) = 'NATIONAL' THEN CALL invoiceOut_newFromClient( vClientFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), @@ -47614,15 +48449,10 @@ BEGIN vCompanyFk, NULL, vNewInvoiceId); - /*ELSE - CALL invoiceOut_newFromTicket(vTicketFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'R')), NULL, vNewInvoiceId); - END IF;*/ - END IF; ELSE -- Albaran_print CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); - INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); END IF; -- ticketClosure end @@ -47887,23 +48717,23 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentCalculate` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentCalculate__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate__`( vAddressFk INT, vAgencyModeFk INT) proc: BEGIN -- OBSOLETO usar catalog_componentCalculate /** - * Calcula los componentes de un ticket + * Calcula los componentes de un ticket * * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id del modo de agencia @@ -48155,7 +48985,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentMakeUpdate` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentMakeUpdate__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48165,7 +48995,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentMakeUpdate`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentMakeUpdate__`( vTicketFk INT, vClientFk INT, vAgencyModeFk INT, @@ -48204,7 +49034,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPreview` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPreview__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48214,7 +49044,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPreview`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPreview__`( vTicketFk INT, vLanded DATE, vAddressFk INT, @@ -48311,7 +49141,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPriceDifference` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPriceDifference__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48321,7 +49151,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPriceDifference`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPriceDifference__`( vTicketFk INT, vLanded DATE, vAddressFk INT, @@ -48643,9 +49473,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -48657,7 +49487,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( ,vAddressFk INT ,vAgencyModeFk INT ,vRouteFk INT - ,vLanded DATE + ,vlanded DATE ,vUserId INT ,OUT vNewTicket INT) BEGIN @@ -48680,9 +49510,9 @@ BEGIN WHERE clientFk = vClientId AND isDefaultAddress; END IF; - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - SELECT id INTO vZoneFk FROM tmp.zoneGetShipped + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; INSERT INTO vn2008.Tickets ( @@ -48699,14 +49529,14 @@ BEGIN ) SELECT vClientId, - IFNULL(vShipped,vLanded), + vShipped, a.id, IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), a.nickname, vWarehouseFk, IF(vRouteFk,vRouteFk,NULL), vCompanyFk, - vLanded, + vlanded, vZoneFk FROM address a JOIN agencyMode am ON am.id = a.agencyModeFk @@ -48740,9 +49570,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -48754,7 +49584,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( ,vAddressFk INT ,vAgencyModeFk INT ,vRouteFk INT - ,vLanded DATE + ,vlanded DATE ,vUserId INT ,OUT vNewTicket INT) BEGIN @@ -48773,9 +49603,9 @@ BEGIN IF vAgencyModeFk IS NOT NULL THEN - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - SELECT id INTO vZoneFk FROM tmp.zoneGetShipped + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; IF vZoneFk IS NULL OR vZoneFk = 0 THEN @@ -48796,14 +49626,14 @@ BEGIN ) SELECT vClientId, - IFNULL(vShipped,vLanded), + vShipped, a.id, vAgencyModeFk, a.nickname, vWarehouseFk, IF(vRouteFk,vRouteFk,NULL), vCompanyFk, - vLanded, + vlanded, vZoneFk FROM address a JOIN agencyMode am ON am.id = a.agencyModeFk @@ -50543,9 +51373,10 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vLanded DATE; DECLARE vIsTicketEditable BOOLEAN; + DECLARE vZoneFk INTEGER; - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE - INTO vIsTicketEditable + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket WHERE id = vTicketFk; @@ -50567,7 +51398,7 @@ proc: BEGIN WHERE s.ticketFk = vTicketFk GROUP BY s.itemFk; - CALL vn.ticketComponentCalculate(vAddressFk,vAgencyModeFk); + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -50625,10 +51456,11 @@ proc: BEGIN DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; DECLARE vLanded DATE; + DECLARE vZoneFk INTEGER; IF vIsTicketEditable IS NULL THEN - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE - INTO vIsTicketEditable + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket WHERE id = vTicketFk; END IF; @@ -50650,7 +51482,7 @@ proc: BEGIN WHERE s.ticketFk = vTicketFk GROUP BY s.itemFk; - CALL vn.ticketComponentCalculate(vAddressFk,vAgencyModeFk); + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -50687,15 +51519,15 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN - -- BERNAT: WORKING IN THIS FILE + /** * Horas que debe trabajar un empleado según contrato y día. * @param vDatedFrom workerTimeControl @@ -50707,7 +51539,9 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime; - + + CALL rangeDateInfo(vDatedFrom, vDatedTo); + CREATE TEMPORARY TABLE tmp.timeBusinessCalculate SELECT dated, businessFk, @@ -50724,7 +51558,7 @@ BEGIN type, permissionrate, hoursWeek - FROM(SELECT t.dated, + FROM(SELECT rd.dated, b.business_id businessFk, w.userFk, bl.department_id departmentFk, @@ -50734,8 +51568,8 @@ BEGIN cs.type, cs.permissionRate, cl.hours_week hoursWeek - FROM vn.time t - LEFT JOIN postgresql.business b ON t.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) + FROM tmp.rangeDate rd + LEFT JOIN postgresql.business b ON rd.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id @@ -50745,10 +51579,10 @@ BEGIN LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id - LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(t.dated)+1 - LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = t.dated + LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(rd.dated)+1 + LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = rd.dated LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id - WHERE t.dated BETWEEN vDatedFrom AND vDatedTo + WHERE rd.dated BETWEEN vDatedFrom AND vDatedTo GROUP BY w.userFk,dated )sub; @@ -50778,6 +51612,7 @@ BEGIN t.type = 'Festivo' WHERE t.type IS NULL; +DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50949,34 +51784,38 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN - -/** - * Horas totales trabajadas a partir de las fichadas, tiene en cuenta los descansos y fichadas impares - * (si hay fichadas impares nop devuelve info) - * @param vDatedFrom workerTimeControl - * @param vDatedTo workerTimeControl - * @table tmp.user(userFk) - * @return tmp.timeControlCalculate - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; - - CREATE TEMPORARY TABLE tmp.timeControlCalculate - SELECT userFk, - dated, - IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, - SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, - @timeWork / 3600 timeWorkDecimal - FROM (SELECT wtc.userFk, - DATE(wtc.timed) dated, - SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))) timeWork - FROM vn.workerTimeControl wtc - JOIN tmp.`user` w ON w.userFk = wtc.userFk - WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo - GROUP BY wtc.userFk,dated - ORDER BY userFk,dated - )sub - WHERE sub.timeWork > 0; + SET @vIsOdd := TRUE; + SET @vUser := NULL; + SET @vDated := NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; + + CREATE TEMPORARY TABLE tmp.timeControlCalculate + SELECT userFk, + dated, + IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, + SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, + @timeWork / 3600 timeWorkDecimal + FROM (SELECT SUM(timeWork) timeWork, + userFk, + dated + FROM (SELECT IF(@vUser = wtc.userFk, @vUser :=@vUser, @vUser := wtc.userFk ), + IF(@vIsOdd, @vIsOdd := FALSE, @vIsOdd := TRUE ), + IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd ), + IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed:=@vLastTimed), + IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed)-@vLastTimed) timeWork, + IF(direction='in', @vDated := DATE(wtc.timed), @vDated :=@vDated) dated, + wtc.userFk, + wtc.timed timed, + direction + FROM workerTimeControl wtc + JOIN tmp.`user` w ON w.userFk = wtc.userFk + WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo + ORDER BY userFk, timed + ) sub + GROUP BY userFk, dated + ORDER BY userFk, dated + )sub2; END ;; DELIMITER ; @@ -52401,16 +53240,17 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) BEGIN - SELECT vn.workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); - CALL vn.workerTimeControlSOWP(vUserFk, vTimed); + + + SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52511,6 +53351,9 @@ proc: BEGIN 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 @@ -52524,13 +53367,25 @@ proc: BEGIN SELECT MAX(timed) INTO vLastOut FROM vn.workerTimeControl WHERE userFk = vUserFk - AND direction = 'out'; + AND direction = 'out'; + + SELECT email INTO vTo + FROM vn.worker w + WHERE w.id = (SELECT bossFk FROM vn.worker WHERE id = vUserFk); + + SELECT CONCAT(firstName,' ',lastName) INTO vUserName + FROM vn.worker w + WHERE w.id = vUserFk; + IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA -- VERIFICAR DESCANSO DIARIO IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN SELECT "Descansos 12 h" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; @@ -52541,7 +53396,10 @@ proc: BEGIN AND timed >= vLastIn ) THEN SELECT "Dias con fichadas impares" AS problem; - LEAVE proc; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; END IF; -- VERIFICAR VACACIONES @@ -52559,7 +53417,11 @@ proc: BEGIN IF(LENGTH(vCalendarStateType)) THEN SELECT vCalendarStateType AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; + END IF; @@ -52574,7 +53436,11 @@ proc: BEGIN AND IFNULL(b.date_end,vDated) >= vDated ) = 0 THEN SELECT "No hay un contrato en vigor" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; + END IF; -- VERIFICAR DESCANSO SEMANAL @@ -52593,6 +53459,9 @@ proc: BEGIN IF UNIX_TIMESTAMP(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 a podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; @@ -52609,6 +53478,9 @@ proc: BEGIN IF vTimedWorked > vDayWorkMax THEN SELECT "Jornadas" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; @@ -52624,7 +53496,10 @@ proc: BEGIN WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk ) = 0 THEN SELECT "No perteneces a este departamento." AS problem; - LEAVE proc; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; END IF; END IF; @@ -53532,98 +54407,7 @@ BEGIN * @select Listado de agencias disponibles */ - DECLARE vGeoFk INT; - - 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 - WHERE a.id = vAddress - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; - CREATE TEMPORARY TABLE tmp.zoneGetAgency - (INDEX (agencyModeFk)) ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM ( - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, - am.deliveryMethodFk, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - zi.isIncluded, - z.warehouseFk, - z.id zoneFk - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - JOIN agencyMode am ON am.id = z.agencyModeFk - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = vLanded - AND TIMESTAMPADD(DAY,-z.travelingDays, vLanded) >= CURDATE() - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, zgFather.depth DESC, zi.isIncluded DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0 - ORDER BY shipped) t - GROUP BY agencyModeFk; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zoneGetFirstShipped` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetFirstShipped`(vAgencyModeFk INT, vAddress INT, vWarehouseFk INT) -BEGIN -/** -* Devuelve la primera fecha de envio disponible para una agencia en una direccion y un warehouse -* -* @param vAgencyMode id de la agencia en vn.agencyMode -* @param vAddress id de la direccion -* @param vWarehouse id del warehouse -* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida -*/ - - - DECLARE vGeoFk INT; - - 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 - WHERE a.id = vAddress - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - SELECT * FROM ( - SELECT TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) shipped, - zc.delivered landed, - zi.isIncluded - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND z.agencyModeFk = vAgencyModeFk - AND z.warehouseFk = vWarehouseFk - AND TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) >= CURDATE() - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY landed ASC, zgFather.depth DESC) t - HAVING isIncluded > 0 LIMIT 1; + CALL zone_getAgency(vAddress,vLanded); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53634,58 +54418,23 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddress INT, vAgencyMode INT, vWarehouse INT) BEGIN /** * Devuelve una tabla temporal con el dia de recepcion para vShipped. * * @param vShipped Fecha de preparacion de mercancia -* @param vAddressFk Id de consignatario, %NULL para recogida -* @param vAgencyModeFk Id agencia +* @param vAddress Id de consignatario, %NULL para recogida +* @param vAgencyMode Id agencia * @table tmp.zoneGetLanded Datos de recepción */ - DECLARE vGeoFk INT; - - 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 - WHERE a.id = vAddressFk - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - CREATE TEMPORARY TABLE tmp.zoneGetLanded - ENGINE = MEMORY - SELECT - id zoneFk, - vShipped shipped, - delivered landed, - vWarehouseFk warehouseFk, - agencyModeFk, - isIncluded - FROM ( - SELECT zi.isIncluded, zc.delivered, z.id, z.agencyModeFk - FROM vn.zoneGeo zgSon - JOIN vn.zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = TIMESTAMPADD(DAY,z.travelingDays, vShipped) - AND IF(vShipped = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - AND z.agencyModeFk = vAgencyModeFk - AND z.warehouseFk = vWarehouseFk - ORDER BY zgFather.depth DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0 - LIMIT 1; + CALL zone_getLanded(vShipped,vAddress,vAgencyMode,vWarehouse); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53696,15 +54445,16 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) BEGIN /** + * OBSOLETO usar zone_getShippedWarehouse * Devuelve la mínima fecha de envía para cada warehouse * * @param vLanded La fecha de recepcion @@ -53712,41 +54462,10 @@ BEGIN * @param vAgencyModeFk Id de la agencia * @return tmp.zoneGetShipped */ - - DECLARE vGeoFk INT; - - 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 - WHERE a.id = vAddressFk - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - SELECT * FROM ( - SELECT * FROM ( - SELECT z.id zoneFk, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - vLanded landed, - vWarehouseFk warehouseFk, - z.agencyModeFk, - zi.isIncluded - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = vLanded - AND z.agencyModeFk = vAgencyModeFk - AND z.warehouseFk = vWarehouseFk - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, zgFather.depth DESC, isIncluded DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0 - ORDER BY shipped) - t - GROUP BY agencyModeFk; + CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53773,40 +54492,7 @@ BEGIN * @param vAgencyModeFk Id de la agencia * @return tmp.zoneGetShipped */ - - DECLARE vGeoFk INT; - - 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 - WHERE a.id = vAddressFk - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CREATE TEMPORARY TABLE tmp.zoneGetShipped - ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM ( - SELECT z.id, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - zi.isIncluded,z.warehouseFk - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = vLanded - AND z.agencyModeFk = vAgencyModeFk - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, shipped ASC, zgFather.depth DESC, zi.isIncluded DESC) t - GROUP BY warehouseFk, id - HAVING isIncluded > 0 - ORDER BY shipped) t - GROUP BY warehouseFk; + CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53877,7 +54563,272 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zone_getLeaves` */; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGetWarehouse__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetWarehouse__`(vAddress INT, vLanded DATE, vWarehouse INT) +BEGIN +/** +* Devuelve el listado de agencias disponibles para la fecha, + * dirección y warehouse pasadas + * + * @param vAddress + * @param vWarehouse warehouse + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + DECLARE vGeoFk INT; + + 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 + WHERE a.id = vAddress + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + SELECT * FROM ( + SELECT * FROM ( + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, + z.warehouseFk, + zi.isIncluded, + z.id zoneFk + FROM zoneGeo zgSon + JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + JOIN agencyMode am ON am.id = z.agencyModeFk + WHERE zgSon.`id` = vGeoFk + AND delivered = vLanded + AND z.warehouseFk = vWarehouse + AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + ORDER BY z.id, zgFather.depth DESC) t + GROUP BY zoneFk + HAVING isIncluded > 0) t + GROUP BY agencyModeFk; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getAgency` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(vAddress INT, vLanded DATE) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha + * y dirección pasadas. + * + * @param vAddress Id de dirección de envío, %NULL si es recogida + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; + CREATE TEMPORARY TABLE tmp.zoneGetAgency + (INDEX (agencyModeFk)) ENGINE = MEMORY + SELECT am.name agencyMode, + am.description, + z.agencyModeFk, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + TRUE isIncluded, + zo.zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + GROUP BY agencyModeFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getAvailable` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAvailable`(vAddress INT, vLanded DATE) +BEGIN + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + SELECT * FROM tmp.zoneOption; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getEvents` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`( + vProvinceFk INT, + vPostCode VARCHAR(255), + vAgencyModeFk INT) +BEGIN +/** + * Returns available events for the passed province/postcode and agency. + * + * @param vAgencyModeFk The agency mode id + * @param vProvinceFk The province id + * @param vPostCode The postcode or %NULL to use the province + */ + DECLARE vGeoFk INT; + + IF vPostCode IS NOT NULL THEN + SELECT p.geoFk INTO vGeoFk + FROM postCode p + JOIN town t ON t.id = p.townFk + WHERE p.`code` = vPostCode + AND t.provinceFk = vProvinceFk; + ELSE + SELECT geoFk INTO vGeoFk + FROM province + WHERE id = vProvinceFk; + END IF; + + CALL zone_getFromGeo(vGeoFk); + + IF vAgencyModeFk IS NOT NULL THEN + DELETE t FROM tmp.zone t + JOIN zone z ON z.id = t.id + WHERE z.agencyModeFk != vAgencyModeFk; + END IF; + + SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays + FROM tmp.zone t + JOIN zoneEvent e ON e.zoneFk = t.id; + + SELECT e.zoneFk, e.dated + FROM tmp.zone t + JOIN zoneExclusion e ON e.zoneFk = t.id; + + DROP TEMPORARY TABLE tmp.zone; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getFromGeo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getFromGeo`(vGeoFk INT) +BEGIN +/** + * Returns all zones which have the passed geo included. + * + * @param vGeoFk The geo id + * @return tmp.zone(id) The list of zones + */ + DECLARE vChildFk INT DEFAULT vGeoFk; + DECLARE vParentFk INT; + DECLARE vLevel INT DEFAULT 1; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT vGeoFk id, vLevel `level`; + + myLoop: LOOP + SELECT parentFk INTO vParentFk + FROM zoneGeo + WHERE id = vChildFk; + + SET vChildFk = vParentFk; + SET vLevel = vLevel + 1; + + INSERT IGNORE INTO tNodes + SELECT vChildFk, vLevel + FROM DUAL + WHERE vChildFk IS NOT NULL; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + END LOOP; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE tmp.zone + (INDEX (id)) + ENGINE = MEMORY + SELECT id FROM ( + SELECT zoneFk id, isIncluded + FROM ( + SELECT i.zoneFk, i.isIncluded + FROM tNodes n + JOIN zoneIncluded i ON i.geoFk = n.id + ORDER BY zoneFk, n.`level` + ) t + GROUP BY id HAVING isIncluded + ) t; + + DROP TEMPORARY TABLE tNodes; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getLanded` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -53887,12 +54838,59 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +BEGIN +/** +* Devuelve una tabla temporal con el dia de recepcion para vShipped. +* +* @param vShipped Fecha de preparacion de mercancia +* @param vAddressFk Id de consignatario, %NULL para recogida +* @param vAgencyModeFk Id agencia +* @param vWarehouseFk vWarehouseFk +* @table tmp.zoneGetLanded Datos de recepción +*/ + + CALL zone_getFromGeo(address_getGeo(vAddressFk)); + CALL zone_getOptionsForShipment(vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + CREATE TEMPORARY TABLE tmp.zoneGetLanded + ENGINE = MEMORY + SELECT vWarehouseFk warehouseFk, + TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed, + zo.zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN zoneWarehouse zw ON zw.zoneFk = z.id + WHERE agencyModeFk = vAgencyModeFk + AND zw.warehouseFk = vWarehouseFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getLeaves` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves`( vSelf INT, vParentFk INT, vSearch VARCHAR(255) ) -BEGIN +BEGIN DECLARE vIsNumber BOOL; DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; @@ -53976,6 +54974,260 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForLanding` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE) +BEGIN +/** + * Gets computed options for the passed zones and delivery date. + * + * @table tmp.zones(id) The zones ids + * @param vLanded The delivery date + * @return tmp.zoneOption The computed options + */ + DECLARE vHour TIME DEFAULT TIME(NOW()); + + DROP TEMPORARY TABLE IF EXISTS tTemp; + CREATE TEMPORARY TABLE tTemp + ENGINE = MEMORY + SELECT t.id zoneFk, + IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, + IFNULL(e.travelingDays, z.travelingDays) travelingDays, + IFNULL(e.price, z.price) price, + IFNULL(e.bonus, z.bonus) bonus, + CASE + WHEN e.`type` = 'day' + THEN 1 + WHEN e.`type` = 'range' + THEN 2 + ELSE 3 + END specificity + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id + WHERE ( + e.`type` = 'day' + AND e.dated = vLanded + ) OR ( + e.`type` != 'day' + AND e.weekDays & (1 << WEEKDAY(vLanded)) + AND (e.`started` IS NULL OR vLanded >= e.`started`) + AND (e.`ended` IS NULL OR vLanded <= e.`ended`) + ); + + DELETE t FROM tTemp t + JOIN zoneExclusion e + ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded; + + DELETE FROM tTemp + WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE() + OR @shipped = CURDATE() AND vHour > `hour`; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + CREATE TEMPORARY TABLE tmp.zoneOption + ENGINE = MEMORY + SELECT * + FROM ( + SELECT * FROM tTemp + ORDER BY zoneFk, specificity + ) t + GROUP BY zoneFk; + + DROP TEMPORARY TABLE tTemp; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForShipment` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE) +BEGIN +/** + * Gets computed options for the passed zones and shipping date. + * + * @table tmp.zones(id) The zones ids + * @param vShipped The shipping date + * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options + */ + DROP TEMPORARY TABLE IF EXISTS tLandings; + CREATE TEMPORARY TABLE tLandings + (INDEX (eventFk)) + ENGINE = MEMORY + SELECT e.id eventFk, + @travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays, + TIMESTAMPADD(DAY, @travelingDays, vShipped) landed + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id; + + DROP TEMPORARY TABLE IF EXISTS tTemp; + CREATE TEMPORARY TABLE tTemp + ENGINE = MEMORY + SELECT t.id zoneFk, + IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, + IFNULL(e.price, z.price) price, + IFNULL(e.bonus, z.bonus) bonus, + CASE + WHEN e.`type` = 'day' + THEN 1 + WHEN e.`type` = 'range' + THEN 2 + ELSE 3 + END specificity, + l.travelingDays, + l.landed + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id + JOIN tLandings l ON l.eventFk = e.id + WHERE ( + e.`type` = 'day' + AND e.`dated` = l.landed + ) OR ( + e.`type` != 'day' + AND e.weekDays & (1 << WEEKDAY(l.landed)) + AND (e.`started` IS NULL OR l.landed >= e.`started`) + AND (e.`ended` IS NULL OR l.landed <= e.`ended`) + ); + + DELETE t FROM tTemp t + JOIN zoneExclusion e + ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + CREATE TEMPORARY TABLE tmp.zoneOption + ENGINE = MEMORY + SELECT * + FROM ( + SELECT * FROM tTemp + ORDER BY zoneFk, specificity + ) t + GROUP BY zoneFk; + + DROP TEMPORARY TABLE + tTemp, + tLandings; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getShippedWarehouse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) +BEGIN +/** + * Devuelve la mínima fecha de envío para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + + CALL zone_getFromGeo(address_getGeo(vAddressFk)); + CALL zone_getOptionsForLanding(vLanded); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; + CREATE TEMPORARY TABLE tmp.zoneGetShipped + ENGINE = MEMORY + SELECT * FROM ( + SELECT zo.zoneFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + zw.warehouseFk, + z.agencyModeFk + FROM tmp.zoneOption zo + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + JOIN zone z ON z.id = zo.zoneFk + WHERE z.agencyModeFk = vAgencyModeFk + ORDER BY shipped) t + GROUP BY warehouseFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getWarehouse` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha, + * dirección y almacén pasados. + * + * @param vAddress + * @param vWarehouse warehouse + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, + zw.warehouseFk, + z.id zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + WHERE zw.warehouseFk + GROUP BY z.agencyModeFk + ORDER BY agencyMode; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Current Database: `vncontrol` @@ -54038,7 +55290,6 @@ CREATE TABLE `inter` ( KEY `ticket` (`Id_Ticket`), KEY `inter_state` (`state_id`), KEY `inter_id` (`Id_Ticket`,`inter_id`) USING BTREE, - CONSTRAINT `currante` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `inter_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn`.`ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `inter_state` FOREIGN KEY (`state_id`) REFERENCES `vn`.`state` (`id`) ON UPDATE CASCADE, CONSTRAINT `responsable` FOREIGN KEY (`Id_Supervisor`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE @@ -55263,7 +56514,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `component` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `typeFk`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable` from `bi`.`tarifa_componentes` `t` */; +/*!50001 VIEW `component` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `typeFk`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable`,`t`.`code` AS `code` from `bi`.`tarifa_componentes` `t` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -55996,9 +57247,9 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ /*!50001 VIEW `saleFreight` AS select `s`.`ticketFk` AS `ticketFk`,`t`.`clientFk` AS `clientFk`,`t`.`routeFk` AS `routeFk`,`s`.`id` AS `saleFk`,`t`.`zoneFk` AS `zoneFk`,`t`.`companyFk` AS `companyFk`,`t`.`shipped` AS `shipped`,`zc`.`price` AS `price`,((((`s`.`quantity` * `r`.`cm3`) * `zc`.`price`) * `i`.`compression`) / `cb`.`volume`) AS `freight`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `volume` from (((((`vn`.`sale` `s` join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`packaging` `cb` on((`cb`.`id` = '94'))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `s`.`itemFk`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) join `vn`.`zoneCalendar` `zc` on(((`zc`.`zoneFk` = `t`.`zoneFk`) and (`zc`.`delivered` = `t`.`landed`)))) */; @@ -56381,4 +57632,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-16 10:31:31 +-- Dump completed on 2019-12-20 11:02:02 diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 0f7810ed2..ea6a787b0 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -56,6 +56,7 @@ module.exports = Self => { ]; for (const key in params) { + console.log('key', key); if (validUpdateParams.indexOf(key) === -1) throw new UserError(`You don't have enough privileges to do that`); }